id
int32
0
252k
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
241,400
biocore/mustached-octo-ironman
moi/group.py
get_id_from_user
def get_id_from_user(user): """Get an ID from a user, creates if necessary""" id = r_client.hget('user-id-map', user) if id is None: id = str(uuid4()) r_client.hset('user-id-map', user, id) r_client.hset('user-id-map', id, user) return id
python
def get_id_from_user(user): """Get an ID from a user, creates if necessary""" id = r_client.hget('user-id-map', user) if id is None: id = str(uuid4()) r_client.hset('user-id-map', user, id) r_client.hset('user-id-map', id, user) return id
[ "def", "get_id_from_user", "(", "user", ")", ":", "id", "=", "r_client", ".", "hget", "(", "'user-id-map'", ",", "user", ")", "if", "id", "is", "None", ":", "id", "=", "str", "(", "uuid4", "(", ")", ")", "r_client", ".", "hset", "(", "'user-id-map'", ",", "user", ",", "id", ")", "r_client", ".", "hset", "(", "'user-id-map'", ",", "id", ",", "user", ")", "return", "id" ]
Get an ID from a user, creates if necessary
[ "Get", "an", "ID", "from", "a", "user", "creates", "if", "necessary" ]
54128d8fdff327e1b7ffd9bb77bf38c3df9526d7
https://github.com/biocore/mustached-octo-ironman/blob/54128d8fdff327e1b7ffd9bb77bf38c3df9526d7/moi/group.py#L384-L391
241,401
biocore/mustached-octo-ironman
moi/group.py
Group.traverse
def traverse(self, id_=None): """Traverse groups and yield info dicts for jobs""" if id_ is None: id_ = self.group nodes = r_client.smembers(_children_key(id_)) while nodes: current_id = nodes.pop() details = r_client.get(current_id) if details is None: # child has expired or been deleted, remove from :children r_client.srem(_children_key(id_), current_id) continue details = self._decode(details) if details['type'] == 'group': children = r_client.smembers(_children_key(details['id'])) if children is not None: nodes.update(children) yield details
python
def traverse(self, id_=None): """Traverse groups and yield info dicts for jobs""" if id_ is None: id_ = self.group nodes = r_client.smembers(_children_key(id_)) while nodes: current_id = nodes.pop() details = r_client.get(current_id) if details is None: # child has expired or been deleted, remove from :children r_client.srem(_children_key(id_), current_id) continue details = self._decode(details) if details['type'] == 'group': children = r_client.smembers(_children_key(details['id'])) if children is not None: nodes.update(children) yield details
[ "def", "traverse", "(", "self", ",", "id_", "=", "None", ")", ":", "if", "id_", "is", "None", ":", "id_", "=", "self", ".", "group", "nodes", "=", "r_client", ".", "smembers", "(", "_children_key", "(", "id_", ")", ")", "while", "nodes", ":", "current_id", "=", "nodes", ".", "pop", "(", ")", "details", "=", "r_client", ".", "get", "(", "current_id", ")", "if", "details", "is", "None", ":", "# child has expired or been deleted, remove from :children", "r_client", ".", "srem", "(", "_children_key", "(", "id_", ")", ",", "current_id", ")", "continue", "details", "=", "self", ".", "_decode", "(", "details", ")", "if", "details", "[", "'type'", "]", "==", "'group'", ":", "children", "=", "r_client", ".", "smembers", "(", "_children_key", "(", "details", "[", "'id'", "]", ")", ")", "if", "children", "is", "not", "None", ":", "nodes", ".", "update", "(", "children", ")", "yield", "details" ]
Traverse groups and yield info dicts for jobs
[ "Traverse", "groups", "and", "yield", "info", "dicts", "for", "jobs" ]
54128d8fdff327e1b7ffd9bb77bf38c3df9526d7
https://github.com/biocore/mustached-octo-ironman/blob/54128d8fdff327e1b7ffd9bb77bf38c3df9526d7/moi/group.py#L83-L104
241,402
biocore/mustached-octo-ironman
moi/group.py
Group.close
def close(self): """Unsubscribe the group and all jobs being listened too""" for channel in self._listening_to: self.toredis.unsubscribe(channel) self.toredis.unsubscribe(self.group_pubsub)
python
def close(self): """Unsubscribe the group and all jobs being listened too""" for channel in self._listening_to: self.toredis.unsubscribe(channel) self.toredis.unsubscribe(self.group_pubsub)
[ "def", "close", "(", "self", ")", ":", "for", "channel", "in", "self", ".", "_listening_to", ":", "self", ".", "toredis", ".", "unsubscribe", "(", "channel", ")", "self", ".", "toredis", ".", "unsubscribe", "(", "self", ".", "group_pubsub", ")" ]
Unsubscribe the group and all jobs being listened too
[ "Unsubscribe", "the", "group", "and", "all", "jobs", "being", "listened", "too" ]
54128d8fdff327e1b7ffd9bb77bf38c3df9526d7
https://github.com/biocore/mustached-octo-ironman/blob/54128d8fdff327e1b7ffd9bb77bf38c3df9526d7/moi/group.py#L109-L113
241,403
biocore/mustached-octo-ironman
moi/group.py
Group.listen_for_updates
def listen_for_updates(self): """Attach a callback on the group pubsub""" self.toredis.subscribe(self.group_pubsub, callback=self.callback)
python
def listen_for_updates(self): """Attach a callback on the group pubsub""" self.toredis.subscribe(self.group_pubsub, callback=self.callback)
[ "def", "listen_for_updates", "(", "self", ")", ":", "self", ".", "toredis", ".", "subscribe", "(", "self", ".", "group_pubsub", ",", "callback", "=", "self", ".", "callback", ")" ]
Attach a callback on the group pubsub
[ "Attach", "a", "callback", "on", "the", "group", "pubsub" ]
54128d8fdff327e1b7ffd9bb77bf38c3df9526d7
https://github.com/biocore/mustached-octo-ironman/blob/54128d8fdff327e1b7ffd9bb77bf38c3df9526d7/moi/group.py#L126-L128
241,404
biocore/mustached-octo-ironman
moi/group.py
Group.listen_to_node
def listen_to_node(self, id_): """Attach a callback on the job pubsub if it exists""" if r_client.get(id_) is None: return else: self.toredis.subscribe(_pubsub_key(id_), callback=self.callback) self._listening_to[_pubsub_key(id_)] = id_ return id_
python
def listen_to_node(self, id_): """Attach a callback on the job pubsub if it exists""" if r_client.get(id_) is None: return else: self.toredis.subscribe(_pubsub_key(id_), callback=self.callback) self._listening_to[_pubsub_key(id_)] = id_ return id_
[ "def", "listen_to_node", "(", "self", ",", "id_", ")", ":", "if", "r_client", ".", "get", "(", "id_", ")", "is", "None", ":", "return", "else", ":", "self", ".", "toredis", ".", "subscribe", "(", "_pubsub_key", "(", "id_", ")", ",", "callback", "=", "self", ".", "callback", ")", "self", ".", "_listening_to", "[", "_pubsub_key", "(", "id_", ")", "]", "=", "id_", "return", "id_" ]
Attach a callback on the job pubsub if it exists
[ "Attach", "a", "callback", "on", "the", "job", "pubsub", "if", "it", "exists" ]
54128d8fdff327e1b7ffd9bb77bf38c3df9526d7
https://github.com/biocore/mustached-octo-ironman/blob/54128d8fdff327e1b7ffd9bb77bf38c3df9526d7/moi/group.py#L130-L137
241,405
biocore/mustached-octo-ironman
moi/group.py
Group.unlisten_to_node
def unlisten_to_node(self, id_): """Stop listening to a job Parameters ---------- id_ : str An ID to remove Returns -------- str or None The ID removed or None if the ID was not removed """ id_pubsub = _pubsub_key(id_) if id_pubsub in self._listening_to: del self._listening_to[id_pubsub] self.toredis.unsubscribe(id_pubsub) parent = json_decode(r_client.get(id_)).get('parent', None) if parent is not None: r_client.srem(_children_key(parent), id_) r_client.srem(self.group_children, id_) return id_
python
def unlisten_to_node(self, id_): """Stop listening to a job Parameters ---------- id_ : str An ID to remove Returns -------- str or None The ID removed or None if the ID was not removed """ id_pubsub = _pubsub_key(id_) if id_pubsub in self._listening_to: del self._listening_to[id_pubsub] self.toredis.unsubscribe(id_pubsub) parent = json_decode(r_client.get(id_)).get('parent', None) if parent is not None: r_client.srem(_children_key(parent), id_) r_client.srem(self.group_children, id_) return id_
[ "def", "unlisten_to_node", "(", "self", ",", "id_", ")", ":", "id_pubsub", "=", "_pubsub_key", "(", "id_", ")", "if", "id_pubsub", "in", "self", ".", "_listening_to", ":", "del", "self", ".", "_listening_to", "[", "id_pubsub", "]", "self", ".", "toredis", ".", "unsubscribe", "(", "id_pubsub", ")", "parent", "=", "json_decode", "(", "r_client", ".", "get", "(", "id_", ")", ")", ".", "get", "(", "'parent'", ",", "None", ")", "if", "parent", "is", "not", "None", ":", "r_client", ".", "srem", "(", "_children_key", "(", "parent", ")", ",", "id_", ")", "r_client", ".", "srem", "(", "self", ".", "group_children", ",", "id_", ")", "return", "id_" ]
Stop listening to a job Parameters ---------- id_ : str An ID to remove Returns -------- str or None The ID removed or None if the ID was not removed
[ "Stop", "listening", "to", "a", "job" ]
54128d8fdff327e1b7ffd9bb77bf38c3df9526d7
https://github.com/biocore/mustached-octo-ironman/blob/54128d8fdff327e1b7ffd9bb77bf38c3df9526d7/moi/group.py#L139-L163
241,406
biocore/mustached-octo-ironman
moi/group.py
Group.action
def action(self, verb, args): """Process the described action Parameters ---------- verb : str, {'add', 'remove', 'get'} The specific action to perform args : {list, set, tuple} Any relevant arguments for the action. Raises ------ TypeError If args is an unrecognized type ValueError If the action specified is unrecognized Returns ------- list Elements dependent on the action """ if not isinstance(args, (list, set, tuple)): raise TypeError("args is unknown type: %s" % type(args)) if verb == 'add': response = ({'add': i} for i in self._action_add(args)) elif verb == 'remove': response = ({'remove': i} for i in self._action_remove(args)) elif verb == 'get': response = ({'get': i} for i in self._action_get(args)) else: raise ValueError("Unknown action: %s" % verb) self.forwarder(response)
python
def action(self, verb, args): """Process the described action Parameters ---------- verb : str, {'add', 'remove', 'get'} The specific action to perform args : {list, set, tuple} Any relevant arguments for the action. Raises ------ TypeError If args is an unrecognized type ValueError If the action specified is unrecognized Returns ------- list Elements dependent on the action """ if not isinstance(args, (list, set, tuple)): raise TypeError("args is unknown type: %s" % type(args)) if verb == 'add': response = ({'add': i} for i in self._action_add(args)) elif verb == 'remove': response = ({'remove': i} for i in self._action_remove(args)) elif verb == 'get': response = ({'get': i} for i in self._action_get(args)) else: raise ValueError("Unknown action: %s" % verb) self.forwarder(response)
[ "def", "action", "(", "self", ",", "verb", ",", "args", ")", ":", "if", "not", "isinstance", "(", "args", ",", "(", "list", ",", "set", ",", "tuple", ")", ")", ":", "raise", "TypeError", "(", "\"args is unknown type: %s\"", "%", "type", "(", "args", ")", ")", "if", "verb", "==", "'add'", ":", "response", "=", "(", "{", "'add'", ":", "i", "}", "for", "i", "in", "self", ".", "_action_add", "(", "args", ")", ")", "elif", "verb", "==", "'remove'", ":", "response", "=", "(", "{", "'remove'", ":", "i", "}", "for", "i", "in", "self", ".", "_action_remove", "(", "args", ")", ")", "elif", "verb", "==", "'get'", ":", "response", "=", "(", "{", "'get'", ":", "i", "}", "for", "i", "in", "self", ".", "_action_get", "(", "args", ")", ")", "else", ":", "raise", "ValueError", "(", "\"Unknown action: %s\"", "%", "verb", ")", "self", ".", "forwarder", "(", "response", ")" ]
Process the described action Parameters ---------- verb : str, {'add', 'remove', 'get'} The specific action to perform args : {list, set, tuple} Any relevant arguments for the action. Raises ------ TypeError If args is an unrecognized type ValueError If the action specified is unrecognized Returns ------- list Elements dependent on the action
[ "Process", "the", "described", "action" ]
54128d8fdff327e1b7ffd9bb77bf38c3df9526d7
https://github.com/biocore/mustached-octo-ironman/blob/54128d8fdff327e1b7ffd9bb77bf38c3df9526d7/moi/group.py#L204-L238
241,407
biocore/mustached-octo-ironman
moi/group.py
Group._action_add
def _action_add(self, ids): """Add IDs to the group Parameters ---------- ids : {list, set, tuple, generator} of str The IDs to add Returns ------- list of dict The details of the added jobs """ return self._action_get((self.listen_to_node(id_) for id_ in ids))
python
def _action_add(self, ids): """Add IDs to the group Parameters ---------- ids : {list, set, tuple, generator} of str The IDs to add Returns ------- list of dict The details of the added jobs """ return self._action_get((self.listen_to_node(id_) for id_ in ids))
[ "def", "_action_add", "(", "self", ",", "ids", ")", ":", "return", "self", ".", "_action_get", "(", "(", "self", ".", "listen_to_node", "(", "id_", ")", "for", "id_", "in", "ids", ")", ")" ]
Add IDs to the group Parameters ---------- ids : {list, set, tuple, generator} of str The IDs to add Returns ------- list of dict The details of the added jobs
[ "Add", "IDs", "to", "the", "group" ]
54128d8fdff327e1b7ffd9bb77bf38c3df9526d7
https://github.com/biocore/mustached-octo-ironman/blob/54128d8fdff327e1b7ffd9bb77bf38c3df9526d7/moi/group.py#L272-L285
241,408
biocore/mustached-octo-ironman
moi/group.py
Group._action_remove
def _action_remove(self, ids): """Remove IDs from the group Parameters ---------- ids : {list, set, tuple, generator} of str The IDs to remove Returns ------- list of dict The details of the removed jobs """ return self._action_get((self.unlisten_to_node(id_) for id_ in ids))
python
def _action_remove(self, ids): """Remove IDs from the group Parameters ---------- ids : {list, set, tuple, generator} of str The IDs to remove Returns ------- list of dict The details of the removed jobs """ return self._action_get((self.unlisten_to_node(id_) for id_ in ids))
[ "def", "_action_remove", "(", "self", ",", "ids", ")", ":", "return", "self", ".", "_action_get", "(", "(", "self", ".", "unlisten_to_node", "(", "id_", ")", "for", "id_", "in", "ids", ")", ")" ]
Remove IDs from the group Parameters ---------- ids : {list, set, tuple, generator} of str The IDs to remove Returns ------- list of dict The details of the removed jobs
[ "Remove", "IDs", "from", "the", "group" ]
54128d8fdff327e1b7ffd9bb77bf38c3df9526d7
https://github.com/biocore/mustached-octo-ironman/blob/54128d8fdff327e1b7ffd9bb77bf38c3df9526d7/moi/group.py#L287-L300
241,409
biocore/mustached-octo-ironman
moi/group.py
Group._action_get
def _action_get(self, ids): """Get the details for ids Parameters ---------- ids : {list, set, tuple, generator} of str The IDs to get Notes ----- If ids is empty, then all IDs are returned. Returns ------- list of dict The details of the jobs """ if not ids: ids = self.jobs result = [] ids = set(ids) while ids: id_ = ids.pop() if id_ is None: continue try: payload = r_client.get(id_) except ResponseError: # wrong key type continue try: payload = self._decode(payload) except ValueError: # unable to decode or data doesn't exist in redis continue else: result.append(payload) if payload['type'] == 'group': for obj in self.traverse(id_): ids.add(obj['id']) return result
python
def _action_get(self, ids): """Get the details for ids Parameters ---------- ids : {list, set, tuple, generator} of str The IDs to get Notes ----- If ids is empty, then all IDs are returned. Returns ------- list of dict The details of the jobs """ if not ids: ids = self.jobs result = [] ids = set(ids) while ids: id_ = ids.pop() if id_ is None: continue try: payload = r_client.get(id_) except ResponseError: # wrong key type continue try: payload = self._decode(payload) except ValueError: # unable to decode or data doesn't exist in redis continue else: result.append(payload) if payload['type'] == 'group': for obj in self.traverse(id_): ids.add(obj['id']) return result
[ "def", "_action_get", "(", "self", ",", "ids", ")", ":", "if", "not", "ids", ":", "ids", "=", "self", ".", "jobs", "result", "=", "[", "]", "ids", "=", "set", "(", "ids", ")", "while", "ids", ":", "id_", "=", "ids", ".", "pop", "(", ")", "if", "id_", "is", "None", ":", "continue", "try", ":", "payload", "=", "r_client", ".", "get", "(", "id_", ")", "except", "ResponseError", ":", "# wrong key type", "continue", "try", ":", "payload", "=", "self", ".", "_decode", "(", "payload", ")", "except", "ValueError", ":", "# unable to decode or data doesn't exist in redis", "continue", "else", ":", "result", ".", "append", "(", "payload", ")", "if", "payload", "[", "'type'", "]", "==", "'group'", ":", "for", "obj", "in", "self", ".", "traverse", "(", "id_", ")", ":", "ids", ".", "add", "(", "obj", "[", "'id'", "]", ")", "return", "result" ]
Get the details for ids Parameters ---------- ids : {list, set, tuple, generator} of str The IDs to get Notes ----- If ids is empty, then all IDs are returned. Returns ------- list of dict The details of the jobs
[ "Get", "the", "details", "for", "ids" ]
54128d8fdff327e1b7ffd9bb77bf38c3df9526d7
https://github.com/biocore/mustached-octo-ironman/blob/54128d8fdff327e1b7ffd9bb77bf38c3df9526d7/moi/group.py#L302-L348
241,410
jordanncg/Bison
bison/libs/process.py
main
def main(): """Main method that runs the build""" data = Common.open_file(F_INFO) config = Common.open_file(F_CONFIG) file_full_path = "" env = load_jinja2_env(config['p_template']) for index, page in data.iteritems(): logging.info('Creating ' + index + ' page:') template = env.get_template(page['f_template'] + \ config['f_template_ext']) for lang, content in page['content'].items(): if lang == "NaL": if page['f_directory'] != '': Common.make_dir(config['p_build'] + page['f_directory']) file_full_path = config['p_build'] + page['f_directory'] + \ page['f_name'] +page['f_endtype'] else: if page['f_directory'] != '': Common.make_dir(config['p_build'] + lang + '/' + \ page['f_directory']) file_full_path = config['p_build'] + lang + '/' + \ page['f_directory'] + page['f_name'] +page['f_endtype'] with open(file_full_path, 'w') as target_file: target_file.write(template.render(content)) logging.info('Page ' + index + ' created.')
python
def main(): """Main method that runs the build""" data = Common.open_file(F_INFO) config = Common.open_file(F_CONFIG) file_full_path = "" env = load_jinja2_env(config['p_template']) for index, page in data.iteritems(): logging.info('Creating ' + index + ' page:') template = env.get_template(page['f_template'] + \ config['f_template_ext']) for lang, content in page['content'].items(): if lang == "NaL": if page['f_directory'] != '': Common.make_dir(config['p_build'] + page['f_directory']) file_full_path = config['p_build'] + page['f_directory'] + \ page['f_name'] +page['f_endtype'] else: if page['f_directory'] != '': Common.make_dir(config['p_build'] + lang + '/' + \ page['f_directory']) file_full_path = config['p_build'] + lang + '/' + \ page['f_directory'] + page['f_name'] +page['f_endtype'] with open(file_full_path, 'w') as target_file: target_file.write(template.render(content)) logging.info('Page ' + index + ' created.')
[ "def", "main", "(", ")", ":", "data", "=", "Common", ".", "open_file", "(", "F_INFO", ")", "config", "=", "Common", ".", "open_file", "(", "F_CONFIG", ")", "file_full_path", "=", "\"\"", "env", "=", "load_jinja2_env", "(", "config", "[", "'p_template'", "]", ")", "for", "index", ",", "page", "in", "data", ".", "iteritems", "(", ")", ":", "logging", ".", "info", "(", "'Creating '", "+", "index", "+", "' page:'", ")", "template", "=", "env", ".", "get_template", "(", "page", "[", "'f_template'", "]", "+", "config", "[", "'f_template_ext'", "]", ")", "for", "lang", ",", "content", "in", "page", "[", "'content'", "]", ".", "items", "(", ")", ":", "if", "lang", "==", "\"NaL\"", ":", "if", "page", "[", "'f_directory'", "]", "!=", "''", ":", "Common", ".", "make_dir", "(", "config", "[", "'p_build'", "]", "+", "page", "[", "'f_directory'", "]", ")", "file_full_path", "=", "config", "[", "'p_build'", "]", "+", "page", "[", "'f_directory'", "]", "+", "page", "[", "'f_name'", "]", "+", "page", "[", "'f_endtype'", "]", "else", ":", "if", "page", "[", "'f_directory'", "]", "!=", "''", ":", "Common", ".", "make_dir", "(", "config", "[", "'p_build'", "]", "+", "lang", "+", "'/'", "+", "page", "[", "'f_directory'", "]", ")", "file_full_path", "=", "config", "[", "'p_build'", "]", "+", "lang", "+", "'/'", "+", "page", "[", "'f_directory'", "]", "+", "page", "[", "'f_name'", "]", "+", "page", "[", "'f_endtype'", "]", "with", "open", "(", "file_full_path", ",", "'w'", ")", "as", "target_file", ":", "target_file", ".", "write", "(", "template", ".", "render", "(", "content", ")", ")", "logging", ".", "info", "(", "'Page '", "+", "index", "+", "' created.'", ")" ]
Main method that runs the build
[ "Main", "method", "that", "runs", "the", "build" ]
c7f04fd67d141fe26cd29db3c3fb3fc0fd0c45df
https://github.com/jordanncg/Bison/blob/c7f04fd67d141fe26cd29db3c3fb3fc0fd0c45df/bison/libs/process.py#L33-L65
241,411
PRIArobotics/HedgehogUtils
hedgehog/utils/zmq/__init__.py
_ConfigureSocketMixin.configure
def configure(self, *, hwm: int=None, rcvtimeo: int=None, sndtimeo: int=None, linger: int=None) -> 'Socket': """ Allows to configure some common socket options and configurations, while allowing method chaining """ if hwm is not None: self.set_hwm(hwm) if rcvtimeo is not None: self.setsockopt(zmq.RCVTIMEO, rcvtimeo) if sndtimeo is not None: self.setsockopt(zmq.SNDTIMEO, sndtimeo) if linger is not None: self.setsockopt(zmq.LINGER, linger) return self
python
def configure(self, *, hwm: int=None, rcvtimeo: int=None, sndtimeo: int=None, linger: int=None) -> 'Socket': """ Allows to configure some common socket options and configurations, while allowing method chaining """ if hwm is not None: self.set_hwm(hwm) if rcvtimeo is not None: self.setsockopt(zmq.RCVTIMEO, rcvtimeo) if sndtimeo is not None: self.setsockopt(zmq.SNDTIMEO, sndtimeo) if linger is not None: self.setsockopt(zmq.LINGER, linger) return self
[ "def", "configure", "(", "self", ",", "*", ",", "hwm", ":", "int", "=", "None", ",", "rcvtimeo", ":", "int", "=", "None", ",", "sndtimeo", ":", "int", "=", "None", ",", "linger", ":", "int", "=", "None", ")", "->", "'Socket'", ":", "if", "hwm", "is", "not", "None", ":", "self", ".", "set_hwm", "(", "hwm", ")", "if", "rcvtimeo", "is", "not", "None", ":", "self", ".", "setsockopt", "(", "zmq", ".", "RCVTIMEO", ",", "rcvtimeo", ")", "if", "sndtimeo", "is", "not", "None", ":", "self", ".", "setsockopt", "(", "zmq", ".", "SNDTIMEO", ",", "sndtimeo", ")", "if", "linger", "is", "not", "None", ":", "self", ".", "setsockopt", "(", "zmq", ".", "LINGER", ",", "linger", ")", "return", "self" ]
Allows to configure some common socket options and configurations, while allowing method chaining
[ "Allows", "to", "configure", "some", "common", "socket", "options", "and", "configurations", "while", "allowing", "method", "chaining" ]
cc368df270288c870cc66d707696ccb62823ca9c
https://github.com/PRIArobotics/HedgehogUtils/blob/cc368df270288c870cc66d707696ccb62823ca9c/hedgehog/utils/zmq/__init__.py#L11-L23
241,412
PRIArobotics/HedgehogUtils
hedgehog/utils/zmq/__init__.py
_AsyncSocketExtensionsMixin.recv_multipart_expect
async def recv_multipart_expect(self, data: Tuple[bytes, ...]=(b'',)) -> None: """ Waits for the next multipart message and asserts that it contains the given data. """ expect_all(await self.recv_multipart(), data)
python
async def recv_multipart_expect(self, data: Tuple[bytes, ...]=(b'',)) -> None: """ Waits for the next multipart message and asserts that it contains the given data. """ expect_all(await self.recv_multipart(), data)
[ "async", "def", "recv_multipart_expect", "(", "self", ",", "data", ":", "Tuple", "[", "bytes", ",", "...", "]", "=", "(", "b''", ",", ")", ")", "->", "None", ":", "expect_all", "(", "await", "self", ".", "recv_multipart", "(", ")", ",", "data", ")" ]
Waits for the next multipart message and asserts that it contains the given data.
[ "Waits", "for", "the", "next", "multipart", "message", "and", "asserts", "that", "it", "contains", "the", "given", "data", "." ]
cc368df270288c870cc66d707696ccb62823ca9c
https://github.com/PRIArobotics/HedgehogUtils/blob/cc368df270288c870cc66d707696ccb62823ca9c/hedgehog/utils/zmq/__init__.py#L71-L75
241,413
renzon/gaepagseguro
gaepagseguro/pagseguro_facade.py
generate_payment
def generate_payment(redirect_url, client_name, client_email, payment_owner, validate_address_cmd, *validate_item_cmds): """ Function used to generate a payment on pagseguro See facade_tests to undestand the steps before generating a payment @param redirect_url: the url where payment status change must be sent @param client_name: client's name @param client_email: client's email @param payment_owner: owner of payment. Her payments can be listed with search_payments function @param validate_address_cmd: cmd generated with validate_address_cmd function @param validate_item_cmds: list of cmds generated with validate_item_cmd function @return: A command that generate the payment when executed """ return GeneratePayment(redirect_url, client_name, client_email, payment_owner, validate_address_cmd, *validate_item_cmds)
python
def generate_payment(redirect_url, client_name, client_email, payment_owner, validate_address_cmd, *validate_item_cmds): """ Function used to generate a payment on pagseguro See facade_tests to undestand the steps before generating a payment @param redirect_url: the url where payment status change must be sent @param client_name: client's name @param client_email: client's email @param payment_owner: owner of payment. Her payments can be listed with search_payments function @param validate_address_cmd: cmd generated with validate_address_cmd function @param validate_item_cmds: list of cmds generated with validate_item_cmd function @return: A command that generate the payment when executed """ return GeneratePayment(redirect_url, client_name, client_email, payment_owner, validate_address_cmd, *validate_item_cmds)
[ "def", "generate_payment", "(", "redirect_url", ",", "client_name", ",", "client_email", ",", "payment_owner", ",", "validate_address_cmd", ",", "*", "validate_item_cmds", ")", ":", "return", "GeneratePayment", "(", "redirect_url", ",", "client_name", ",", "client_email", ",", "payment_owner", ",", "validate_address_cmd", ",", "*", "validate_item_cmds", ")" ]
Function used to generate a payment on pagseguro See facade_tests to undestand the steps before generating a payment @param redirect_url: the url where payment status change must be sent @param client_name: client's name @param client_email: client's email @param payment_owner: owner of payment. Her payments can be listed with search_payments function @param validate_address_cmd: cmd generated with validate_address_cmd function @param validate_item_cmds: list of cmds generated with validate_item_cmd function @return: A command that generate the payment when executed
[ "Function", "used", "to", "generate", "a", "payment", "on", "pagseguro", "See", "facade_tests", "to", "undestand", "the", "steps", "before", "generating", "a", "payment" ]
c88f00580c380ff5b35d873311d6c786fa1f29d2
https://github.com/renzon/gaepagseguro/blob/c88f00580c380ff5b35d873311d6c786fa1f29d2/gaepagseguro/pagseguro_facade.py#L57-L72
241,414
renzon/gaepagseguro
gaepagseguro/pagseguro_facade.py
validate_address_cmd
def validate_address_cmd(street, number, quarter, postalcode, town, state, complement="Sem Complemento"): """ Build an address form to be used with payment function """ return ValidateAddressCmd(street=street, number=number, quarter=quarter, postalcode=postalcode, town=town, state=state, complement=complement)
python
def validate_address_cmd(street, number, quarter, postalcode, town, state, complement="Sem Complemento"): """ Build an address form to be used with payment function """ return ValidateAddressCmd(street=street, number=number, quarter=quarter, postalcode=postalcode, town=town, state=state, complement=complement)
[ "def", "validate_address_cmd", "(", "street", ",", "number", ",", "quarter", ",", "postalcode", ",", "town", ",", "state", ",", "complement", "=", "\"Sem Complemento\"", ")", ":", "return", "ValidateAddressCmd", "(", "street", "=", "street", ",", "number", "=", "number", ",", "quarter", "=", "quarter", ",", "postalcode", "=", "postalcode", ",", "town", "=", "town", ",", "state", "=", "state", ",", "complement", "=", "complement", ")" ]
Build an address form to be used with payment function
[ "Build", "an", "address", "form", "to", "be", "used", "with", "payment", "function" ]
c88f00580c380ff5b35d873311d6c786fa1f29d2
https://github.com/renzon/gaepagseguro/blob/c88f00580c380ff5b35d873311d6c786fa1f29d2/gaepagseguro/pagseguro_facade.py#L87-L92
241,415
renzon/gaepagseguro
gaepagseguro/pagseguro_facade.py
validate_item_cmd
def validate_item_cmd(description, price, quantity, reference=None): """ Create a commando to save items from the order. A list of items or commands must be created to save a order @param description: Item's description @param price: Item's price @param quantity: Item's quantity @param reference: a product reference for the item. Must be a Node @return: A Command that validate and save a item """ return ValidateItemCmd(description=description, price=price, quantity=quantity, reference=reference)
python
def validate_item_cmd(description, price, quantity, reference=None): """ Create a commando to save items from the order. A list of items or commands must be created to save a order @param description: Item's description @param price: Item's price @param quantity: Item's quantity @param reference: a product reference for the item. Must be a Node @return: A Command that validate and save a item """ return ValidateItemCmd(description=description, price=price, quantity=quantity, reference=reference)
[ "def", "validate_item_cmd", "(", "description", ",", "price", ",", "quantity", ",", "reference", "=", "None", ")", ":", "return", "ValidateItemCmd", "(", "description", "=", "description", ",", "price", "=", "price", ",", "quantity", "=", "quantity", ",", "reference", "=", "reference", ")" ]
Create a commando to save items from the order. A list of items or commands must be created to save a order @param description: Item's description @param price: Item's price @param quantity: Item's quantity @param reference: a product reference for the item. Must be a Node @return: A Command that validate and save a item
[ "Create", "a", "commando", "to", "save", "items", "from", "the", "order", ".", "A", "list", "of", "items", "or", "commands", "must", "be", "created", "to", "save", "a", "order" ]
c88f00580c380ff5b35d873311d6c786fa1f29d2
https://github.com/renzon/gaepagseguro/blob/c88f00580c380ff5b35d873311d6c786fa1f29d2/gaepagseguro/pagseguro_facade.py#L95-L105
241,416
renzon/gaepagseguro
gaepagseguro/pagseguro_facade.py
search_all_payments
def search_all_payments(payment_status=None, page_size=20, start_cursor=None, offset=0, use_cache=True, cache_begin=True, relations=None): """ Returns a command to search all payments ordered by creation desc @param payment_status: The payment status. If None is going to return results independent from status @param page_size: number of payments per page @param start_cursor: cursor to continue the search @param offset: offset number of payment on search @param use_cache: indicates with should use cache or not for results @param cache_begin: indicates with should use cache on beginning or not for results @param relations: list of relations to bring with payment objects. possible values on list: logs, pay_items, owner @return: Returns a command to search all payments ordered by creation desc """ if payment_status: return PaymentsByStatusSearch(payment_status, page_size, start_cursor, offset, use_cache, cache_begin, relations) return AllPaymentsSearch(page_size, start_cursor, offset, use_cache, cache_begin, relations)
python
def search_all_payments(payment_status=None, page_size=20, start_cursor=None, offset=0, use_cache=True, cache_begin=True, relations=None): """ Returns a command to search all payments ordered by creation desc @param payment_status: The payment status. If None is going to return results independent from status @param page_size: number of payments per page @param start_cursor: cursor to continue the search @param offset: offset number of payment on search @param use_cache: indicates with should use cache or not for results @param cache_begin: indicates with should use cache on beginning or not for results @param relations: list of relations to bring with payment objects. possible values on list: logs, pay_items, owner @return: Returns a command to search all payments ordered by creation desc """ if payment_status: return PaymentsByStatusSearch(payment_status, page_size, start_cursor, offset, use_cache, cache_begin, relations) return AllPaymentsSearch(page_size, start_cursor, offset, use_cache, cache_begin, relations)
[ "def", "search_all_payments", "(", "payment_status", "=", "None", ",", "page_size", "=", "20", ",", "start_cursor", "=", "None", ",", "offset", "=", "0", ",", "use_cache", "=", "True", ",", "cache_begin", "=", "True", ",", "relations", "=", "None", ")", ":", "if", "payment_status", ":", "return", "PaymentsByStatusSearch", "(", "payment_status", ",", "page_size", ",", "start_cursor", ",", "offset", ",", "use_cache", ",", "cache_begin", ",", "relations", ")", "return", "AllPaymentsSearch", "(", "page_size", ",", "start_cursor", ",", "offset", ",", "use_cache", ",", "cache_begin", ",", "relations", ")" ]
Returns a command to search all payments ordered by creation desc @param payment_status: The payment status. If None is going to return results independent from status @param page_size: number of payments per page @param start_cursor: cursor to continue the search @param offset: offset number of payment on search @param use_cache: indicates with should use cache or not for results @param cache_begin: indicates with should use cache on beginning or not for results @param relations: list of relations to bring with payment objects. possible values on list: logs, pay_items, owner @return: Returns a command to search all payments ordered by creation desc
[ "Returns", "a", "command", "to", "search", "all", "payments", "ordered", "by", "creation", "desc" ]
c88f00580c380ff5b35d873311d6c786fa1f29d2
https://github.com/renzon/gaepagseguro/blob/c88f00580c380ff5b35d873311d6c786fa1f29d2/gaepagseguro/pagseguro_facade.py#L127-L143
241,417
TAPPGuild/tapp-config
tapp_config.py
get_config
def get_config(name=__name__): """ Get a configuration parser for a given TAPP name. Reads config.ini files only, not in-database configuration records. :param name: The tapp name to get a configuration for. :rtype: ConfigParser :return: A config parser matching the given name """ cfg = ConfigParser() path = os.environ.get('%s_CONFIG_FILE' % name.upper()) if path is None or path == "": fname = '/etc/tapp/%s.ini' % name if isfile(fname): path = fname elif isfile('cfg.ini'): path = 'cfg.ini' else: raise ValueError("Unable to get configuration for tapp %s" % name) cfg.read(path) return cfg
python
def get_config(name=__name__): """ Get a configuration parser for a given TAPP name. Reads config.ini files only, not in-database configuration records. :param name: The tapp name to get a configuration for. :rtype: ConfigParser :return: A config parser matching the given name """ cfg = ConfigParser() path = os.environ.get('%s_CONFIG_FILE' % name.upper()) if path is None or path == "": fname = '/etc/tapp/%s.ini' % name if isfile(fname): path = fname elif isfile('cfg.ini'): path = 'cfg.ini' else: raise ValueError("Unable to get configuration for tapp %s" % name) cfg.read(path) return cfg
[ "def", "get_config", "(", "name", "=", "__name__", ")", ":", "cfg", "=", "ConfigParser", "(", ")", "path", "=", "os", ".", "environ", ".", "get", "(", "'%s_CONFIG_FILE'", "%", "name", ".", "upper", "(", ")", ")", "if", "path", "is", "None", "or", "path", "==", "\"\"", ":", "fname", "=", "'/etc/tapp/%s.ini'", "%", "name", "if", "isfile", "(", "fname", ")", ":", "path", "=", "fname", "elif", "isfile", "(", "'cfg.ini'", ")", ":", "path", "=", "'cfg.ini'", "else", ":", "raise", "ValueError", "(", "\"Unable to get configuration for tapp %s\"", "%", "name", ")", "cfg", ".", "read", "(", "path", ")", "return", "cfg" ]
Get a configuration parser for a given TAPP name. Reads config.ini files only, not in-database configuration records. :param name: The tapp name to get a configuration for. :rtype: ConfigParser :return: A config parser matching the given name
[ "Get", "a", "configuration", "parser", "for", "a", "given", "TAPP", "name", ".", "Reads", "config", ".", "ini", "files", "only", "not", "in", "-", "database", "configuration", "records", "." ]
20fdbe00e4763f38a90845ad2cfb63c94e13ca81
https://github.com/TAPPGuild/tapp-config/blob/20fdbe00e4763f38a90845ad2cfb63c94e13ca81/tapp_config.py#L20-L41
241,418
TAPPGuild/tapp-config
tapp_config.py
setup_logging
def setup_logging(name, prefix="trademanager", cfg=None): """ Create a logger, based on the given configuration. Accepts LOGFILE and LOGLEVEL settings. :param name: the name of the tapp to log :param cfg: The configuration object with logging info. :return: The session and the engine as a list (in that order) """ logname = "/var/log/%s/%s_tapp.log" % (prefix, name) logfile = cfg.get('log', 'LOGFILE') if cfg is not None and \ cfg.get('log', 'LOGFILE') is not None and cfg.get('log', 'LOGFILE') != "" else logname loglevel = cfg.get('log', 'LOGLEVEL') if cfg is not None and \ cfg.get('log', 'LOGLEVEL') is not None else logging.INFO logging.basicConfig(filename=logfile, level=loglevel) return logging.getLogger(name)
python
def setup_logging(name, prefix="trademanager", cfg=None): """ Create a logger, based on the given configuration. Accepts LOGFILE and LOGLEVEL settings. :param name: the name of the tapp to log :param cfg: The configuration object with logging info. :return: The session and the engine as a list (in that order) """ logname = "/var/log/%s/%s_tapp.log" % (prefix, name) logfile = cfg.get('log', 'LOGFILE') if cfg is not None and \ cfg.get('log', 'LOGFILE') is not None and cfg.get('log', 'LOGFILE') != "" else logname loglevel = cfg.get('log', 'LOGLEVEL') if cfg is not None and \ cfg.get('log', 'LOGLEVEL') is not None else logging.INFO logging.basicConfig(filename=logfile, level=loglevel) return logging.getLogger(name)
[ "def", "setup_logging", "(", "name", ",", "prefix", "=", "\"trademanager\"", ",", "cfg", "=", "None", ")", ":", "logname", "=", "\"/var/log/%s/%s_tapp.log\"", "%", "(", "prefix", ",", "name", ")", "logfile", "=", "cfg", ".", "get", "(", "'log'", ",", "'LOGFILE'", ")", "if", "cfg", "is", "not", "None", "and", "cfg", ".", "get", "(", "'log'", ",", "'LOGFILE'", ")", "is", "not", "None", "and", "cfg", ".", "get", "(", "'log'", ",", "'LOGFILE'", ")", "!=", "\"\"", "else", "logname", "loglevel", "=", "cfg", ".", "get", "(", "'log'", ",", "'LOGLEVEL'", ")", "if", "cfg", "is", "not", "None", "and", "cfg", ".", "get", "(", "'log'", ",", "'LOGLEVEL'", ")", "is", "not", "None", "else", "logging", ".", "INFO", "logging", ".", "basicConfig", "(", "filename", "=", "logfile", ",", "level", "=", "loglevel", ")", "return", "logging", ".", "getLogger", "(", "name", ")" ]
Create a logger, based on the given configuration. Accepts LOGFILE and LOGLEVEL settings. :param name: the name of the tapp to log :param cfg: The configuration object with logging info. :return: The session and the engine as a list (in that order)
[ "Create", "a", "logger", "based", "on", "the", "given", "configuration", ".", "Accepts", "LOGFILE", "and", "LOGLEVEL", "settings", "." ]
20fdbe00e4763f38a90845ad2cfb63c94e13ca81
https://github.com/TAPPGuild/tapp-config/blob/20fdbe00e4763f38a90845ad2cfb63c94e13ca81/tapp_config.py#L44-L59
241,419
edwards-lab/libGWAS
libgwas/pheno_covar.py
PhenoCovar.destandardize_variables
def destandardize_variables(self, tv, blin, bvar, errBeta, nonmissing): """Destandardize betas and other components.""" return self.test_variables.destandardize(tv, blin, bvar, errBeta, nonmissing)
python
def destandardize_variables(self, tv, blin, bvar, errBeta, nonmissing): """Destandardize betas and other components.""" return self.test_variables.destandardize(tv, blin, bvar, errBeta, nonmissing)
[ "def", "destandardize_variables", "(", "self", ",", "tv", ",", "blin", ",", "bvar", ",", "errBeta", ",", "nonmissing", ")", ":", "return", "self", ".", "test_variables", ".", "destandardize", "(", "tv", ",", "blin", ",", "bvar", ",", "errBeta", ",", "nonmissing", ")" ]
Destandardize betas and other components.
[ "Destandardize", "betas", "and", "other", "components", "." ]
d68c9a083d443dfa5d7c5112de29010909cfe23f
https://github.com/edwards-lab/libGWAS/blob/d68c9a083d443dfa5d7c5112de29010909cfe23f/libgwas/pheno_covar.py#L89-L91
241,420
edwards-lab/libGWAS
libgwas/pheno_covar.py
PhenoCovar.freeze_subjects
def freeze_subjects(self): """Converts variable data into numpy arrays. This is required after all subjects have been added via the add_subject function, since we don't know ahead of time who is participating in the analysis due to various filtering possibilities. """ self.phenotype_data = numpy.array(self.phenotype_data) self.covariate_data = numpy.array(self.covariate_data)
python
def freeze_subjects(self): """Converts variable data into numpy arrays. This is required after all subjects have been added via the add_subject function, since we don't know ahead of time who is participating in the analysis due to various filtering possibilities. """ self.phenotype_data = numpy.array(self.phenotype_data) self.covariate_data = numpy.array(self.covariate_data)
[ "def", "freeze_subjects", "(", "self", ")", ":", "self", ".", "phenotype_data", "=", "numpy", ".", "array", "(", "self", ".", "phenotype_data", ")", "self", ".", "covariate_data", "=", "numpy", ".", "array", "(", "self", ".", "covariate_data", ")" ]
Converts variable data into numpy arrays. This is required after all subjects have been added via the add_subject function, since we don't know ahead of time who is participating in the analysis due to various filtering possibilities.
[ "Converts", "variable", "data", "into", "numpy", "arrays", "." ]
d68c9a083d443dfa5d7c5112de29010909cfe23f
https://github.com/edwards-lab/libGWAS/blob/d68c9a083d443dfa5d7c5112de29010909cfe23f/libgwas/pheno_covar.py#L94-L102
241,421
edwards-lab/libGWAS
libgwas/pheno_covar.py
PhenoCovar.add_subject
def add_subject(self, ind_id, sex=None, phenotype=None): """Add new subject to study, with optional sex and phenotype Throws MalformedInputFile if sex is can't be converted to int """ self.pedigree_data[ind_id] = len(self.phenotype_data[0]) if phenotype != None: if type(self.phenotype_data) is list: self.phenotype_data[0].append(phenotype) else: self.phenotype_data[-1, len(self.individual_mask)] = phenotype self.individual_mask.append(0) if PhenoCovar.sex_as_covariate: try: self.covariate_data[0].append(float(sex)) except Exception, e: raise MalformedInputFile("Invalid setting, %s, for sex in pedigree" % (sex))
python
def add_subject(self, ind_id, sex=None, phenotype=None): """Add new subject to study, with optional sex and phenotype Throws MalformedInputFile if sex is can't be converted to int """ self.pedigree_data[ind_id] = len(self.phenotype_data[0]) if phenotype != None: if type(self.phenotype_data) is list: self.phenotype_data[0].append(phenotype) else: self.phenotype_data[-1, len(self.individual_mask)] = phenotype self.individual_mask.append(0) if PhenoCovar.sex_as_covariate: try: self.covariate_data[0].append(float(sex)) except Exception, e: raise MalformedInputFile("Invalid setting, %s, for sex in pedigree" % (sex))
[ "def", "add_subject", "(", "self", ",", "ind_id", ",", "sex", "=", "None", ",", "phenotype", "=", "None", ")", ":", "self", ".", "pedigree_data", "[", "ind_id", "]", "=", "len", "(", "self", ".", "phenotype_data", "[", "0", "]", ")", "if", "phenotype", "!=", "None", ":", "if", "type", "(", "self", ".", "phenotype_data", ")", "is", "list", ":", "self", ".", "phenotype_data", "[", "0", "]", ".", "append", "(", "phenotype", ")", "else", ":", "self", ".", "phenotype_data", "[", "-", "1", ",", "len", "(", "self", ".", "individual_mask", ")", "]", "=", "phenotype", "self", ".", "individual_mask", ".", "append", "(", "0", ")", "if", "PhenoCovar", ".", "sex_as_covariate", ":", "try", ":", "self", ".", "covariate_data", "[", "0", "]", ".", "append", "(", "float", "(", "sex", ")", ")", "except", "Exception", ",", "e", ":", "raise", "MalformedInputFile", "(", "\"Invalid setting, %s, for sex in pedigree\"", "%", "(", "sex", ")", ")" ]
Add new subject to study, with optional sex and phenotype Throws MalformedInputFile if sex is can't be converted to int
[ "Add", "new", "subject", "to", "study", "with", "optional", "sex", "and", "phenotype" ]
d68c9a083d443dfa5d7c5112de29010909cfe23f
https://github.com/edwards-lab/libGWAS/blob/d68c9a083d443dfa5d7c5112de29010909cfe23f/libgwas/pheno_covar.py#L106-L124
241,422
tBaxter/tango-shared-core
build/lib/tango_shared/templatetags/tango_time_tags.py
format_time
def format_time(date_obj, time_obj=None, datebox=False, dt_type=None, classes=None): """ Returns formatted HTML5 elements based on given datetime object. By default returns a time element, but will return a .datebox if requested. dt_type allows passing dt_start or dt_end for hcal formatting. link allows passing a url to the datebox. classes allows sending arbitrary classnames. Useful for properly microformatting elements. Usage:: {% format_time obj.pub_date %} {% format_time obj.start_date 'datebox' 'dtstart' %} {% format_time obj.end_date obj.end_time 'datebox' 'dt_end' %} """ if not time_obj: time_obj = getattr(date_obj, 'time', None) if dt_type: classes = '{0} {1}'.format(classes, dt_type) if datebox: classes = '{0} {1}'.format(classes, datebox) return { 'date_obj': date_obj, 'time_obj': time_obj, 'datebox': datebox, 'current_year': datetime.date.today().year, 'classes': classes }
python
def format_time(date_obj, time_obj=None, datebox=False, dt_type=None, classes=None): """ Returns formatted HTML5 elements based on given datetime object. By default returns a time element, but will return a .datebox if requested. dt_type allows passing dt_start or dt_end for hcal formatting. link allows passing a url to the datebox. classes allows sending arbitrary classnames. Useful for properly microformatting elements. Usage:: {% format_time obj.pub_date %} {% format_time obj.start_date 'datebox' 'dtstart' %} {% format_time obj.end_date obj.end_time 'datebox' 'dt_end' %} """ if not time_obj: time_obj = getattr(date_obj, 'time', None) if dt_type: classes = '{0} {1}'.format(classes, dt_type) if datebox: classes = '{0} {1}'.format(classes, datebox) return { 'date_obj': date_obj, 'time_obj': time_obj, 'datebox': datebox, 'current_year': datetime.date.today().year, 'classes': classes }
[ "def", "format_time", "(", "date_obj", ",", "time_obj", "=", "None", ",", "datebox", "=", "False", ",", "dt_type", "=", "None", ",", "classes", "=", "None", ")", ":", "if", "not", "time_obj", ":", "time_obj", "=", "getattr", "(", "date_obj", ",", "'time'", ",", "None", ")", "if", "dt_type", ":", "classes", "=", "'{0} {1}'", ".", "format", "(", "classes", ",", "dt_type", ")", "if", "datebox", ":", "classes", "=", "'{0} {1}'", ".", "format", "(", "classes", ",", "datebox", ")", "return", "{", "'date_obj'", ":", "date_obj", ",", "'time_obj'", ":", "time_obj", ",", "'datebox'", ":", "datebox", ",", "'current_year'", ":", "datetime", ".", "date", ".", "today", "(", ")", ".", "year", ",", "'classes'", ":", "classes", "}" ]
Returns formatted HTML5 elements based on given datetime object. By default returns a time element, but will return a .datebox if requested. dt_type allows passing dt_start or dt_end for hcal formatting. link allows passing a url to the datebox. classes allows sending arbitrary classnames. Useful for properly microformatting elements. Usage:: {% format_time obj.pub_date %} {% format_time obj.start_date 'datebox' 'dtstart' %} {% format_time obj.end_date obj.end_time 'datebox' 'dt_end' %}
[ "Returns", "formatted", "HTML5", "elements", "based", "on", "given", "datetime", "object", ".", "By", "default", "returns", "a", "time", "element", "but", "will", "return", "a", ".", "datebox", "if", "requested", "." ]
35fc10aef1ceedcdb4d6d866d44a22efff718812
https://github.com/tBaxter/tango-shared-core/blob/35fc10aef1ceedcdb4d6d866d44a22efff718812/build/lib/tango_shared/templatetags/tango_time_tags.py#L10-L40
241,423
tBaxter/tango-shared-core
build/lib/tango_shared/templatetags/tango_time_tags.py
short_timesince
def short_timesince(date): """ A shorter version of Django's built-in timesince filter. Selects only the first part of the returned string, splitting on the comma. Falls back on default Django timesince if it fails. Example: 3 days, 20 hours becomes "3 days". """ try: t = timesince(date).split(", ")[0] except IndexError: t = timesince(date) return t
python
def short_timesince(date): """ A shorter version of Django's built-in timesince filter. Selects only the first part of the returned string, splitting on the comma. Falls back on default Django timesince if it fails. Example: 3 days, 20 hours becomes "3 days". """ try: t = timesince(date).split(", ")[0] except IndexError: t = timesince(date) return t
[ "def", "short_timesince", "(", "date", ")", ":", "try", ":", "t", "=", "timesince", "(", "date", ")", ".", "split", "(", "\", \"", ")", "[", "0", "]", "except", "IndexError", ":", "t", "=", "timesince", "(", "date", ")", "return", "t" ]
A shorter version of Django's built-in timesince filter. Selects only the first part of the returned string, splitting on the comma. Falls back on default Django timesince if it fails. Example: 3 days, 20 hours becomes "3 days".
[ "A", "shorter", "version", "of", "Django", "s", "built", "-", "in", "timesince", "filter", ".", "Selects", "only", "the", "first", "part", "of", "the", "returned", "string", "splitting", "on", "the", "comma", "." ]
35fc10aef1ceedcdb4d6d866d44a22efff718812
https://github.com/tBaxter/tango-shared-core/blob/35fc10aef1ceedcdb4d6d866d44a22efff718812/build/lib/tango_shared/templatetags/tango_time_tags.py#L44-L59
241,424
logston/py3s3
py3s3/utils.py
validate_values
def validate_values(func, dic): """ Validate each value in ``dic`` by passing it through ``func``. Raise a ``ValueError`` if ``func`` does not return ``True``. """ for value_name, value in dic.items(): if not func(value): raise ValueError('{} can not be {}'.format(value_name, value))
python
def validate_values(func, dic): """ Validate each value in ``dic`` by passing it through ``func``. Raise a ``ValueError`` if ``func`` does not return ``True``. """ for value_name, value in dic.items(): if not func(value): raise ValueError('{} can not be {}'.format(value_name, value))
[ "def", "validate_values", "(", "func", ",", "dic", ")", ":", "for", "value_name", ",", "value", "in", "dic", ".", "items", "(", ")", ":", "if", "not", "func", "(", "value", ")", ":", "raise", "ValueError", "(", "'{} can not be {}'", ".", "format", "(", "value_name", ",", "value", ")", ")" ]
Validate each value in ``dic`` by passing it through ``func``. Raise a ``ValueError`` if ``func`` does not return ``True``.
[ "Validate", "each", "value", "in", "dic", "by", "passing", "it", "through", "func", ".", "Raise", "a", "ValueError", "if", "func", "does", "not", "return", "True", "." ]
1910ca60c53a53d839d6f7b09c05b555f3bfccf4
https://github.com/logston/py3s3/blob/1910ca60c53a53d839d6f7b09c05b555f3bfccf4/py3s3/utils.py#L46-L53
241,425
jonathansick/paperweight
paperweight/document.py
TexDocument.find_input_documents
def find_input_documents(self): """Find all tex documents input by this root document. Returns ------- paths : list List of filepaths for input documents. Paths are relative to the document (i.e., as written in the latex document). """ paths = [] itr = chain(texutils.input_pattern.finditer(self.text), texutils.input_ifexists_pattern.finditer(self.text)) for match in itr: fname = match.group(1) if not fname.endswith('.tex'): full_fname = ".".join((fname, 'tex')) else: full_fname = fname paths.append(full_fname) return paths
python
def find_input_documents(self): """Find all tex documents input by this root document. Returns ------- paths : list List of filepaths for input documents. Paths are relative to the document (i.e., as written in the latex document). """ paths = [] itr = chain(texutils.input_pattern.finditer(self.text), texutils.input_ifexists_pattern.finditer(self.text)) for match in itr: fname = match.group(1) if not fname.endswith('.tex'): full_fname = ".".join((fname, 'tex')) else: full_fname = fname paths.append(full_fname) return paths
[ "def", "find_input_documents", "(", "self", ")", ":", "paths", "=", "[", "]", "itr", "=", "chain", "(", "texutils", ".", "input_pattern", ".", "finditer", "(", "self", ".", "text", ")", ",", "texutils", ".", "input_ifexists_pattern", ".", "finditer", "(", "self", ".", "text", ")", ")", "for", "match", "in", "itr", ":", "fname", "=", "match", ".", "group", "(", "1", ")", "if", "not", "fname", ".", "endswith", "(", "'.tex'", ")", ":", "full_fname", "=", "\".\"", ".", "join", "(", "(", "fname", ",", "'tex'", ")", ")", "else", ":", "full_fname", "=", "fname", "paths", ".", "append", "(", "full_fname", ")", "return", "paths" ]
Find all tex documents input by this root document. Returns ------- paths : list List of filepaths for input documents. Paths are relative to the document (i.e., as written in the latex document).
[ "Find", "all", "tex", "documents", "input", "by", "this", "root", "document", "." ]
803535b939a56d375967cefecd5fdca81323041e
https://github.com/jonathansick/paperweight/blob/803535b939a56d375967cefecd5fdca81323041e/paperweight/document.py#L54-L73
241,426
jonathansick/paperweight
paperweight/document.py
TexDocument.sections
def sections(self): """List with tuples of section names and positions. Positions of section names are measured by cumulative word count. """ sections = [] for match in texutils.section_pattern.finditer(self.text): textbefore = self.text[0:match.start()] wordsbefore = nlputils.wordify(textbefore) numwordsbefore = len(wordsbefore) sections.append((numwordsbefore, match.group(1))) self._sections = sections return sections
python
def sections(self): """List with tuples of section names and positions. Positions of section names are measured by cumulative word count. """ sections = [] for match in texutils.section_pattern.finditer(self.text): textbefore = self.text[0:match.start()] wordsbefore = nlputils.wordify(textbefore) numwordsbefore = len(wordsbefore) sections.append((numwordsbefore, match.group(1))) self._sections = sections return sections
[ "def", "sections", "(", "self", ")", ":", "sections", "=", "[", "]", "for", "match", "in", "texutils", ".", "section_pattern", ".", "finditer", "(", "self", ".", "text", ")", ":", "textbefore", "=", "self", ".", "text", "[", "0", ":", "match", ".", "start", "(", ")", "]", "wordsbefore", "=", "nlputils", ".", "wordify", "(", "textbefore", ")", "numwordsbefore", "=", "len", "(", "wordsbefore", ")", "sections", ".", "append", "(", "(", "numwordsbefore", ",", "match", ".", "group", "(", "1", ")", ")", ")", "self", ".", "_sections", "=", "sections", "return", "sections" ]
List with tuples of section names and positions. Positions of section names are measured by cumulative word count.
[ "List", "with", "tuples", "of", "section", "names", "and", "positions", ".", "Positions", "of", "section", "names", "are", "measured", "by", "cumulative", "word", "count", "." ]
803535b939a56d375967cefecd5fdca81323041e
https://github.com/jonathansick/paperweight/blob/803535b939a56d375967cefecd5fdca81323041e/paperweight/document.py#L76-L89
241,427
jonathansick/paperweight
paperweight/document.py
TexDocument.bib_path
def bib_path(self): """Absolute file path to the .bib bibliography document.""" bib_name = self.bib_name # FIXME need to bake in search paths for tex documents in all platforms osx_path = os.path.expanduser( "~/Library/texmf/bibtex/bib/{0}".format(bib_name)) if self._file_exists(bib_name): return bib_name # bib is in project directory elif os.path.exists(osx_path): return osx_path else: return None
python
def bib_path(self): """Absolute file path to the .bib bibliography document.""" bib_name = self.bib_name # FIXME need to bake in search paths for tex documents in all platforms osx_path = os.path.expanduser( "~/Library/texmf/bibtex/bib/{0}".format(bib_name)) if self._file_exists(bib_name): return bib_name # bib is in project directory elif os.path.exists(osx_path): return osx_path else: return None
[ "def", "bib_path", "(", "self", ")", ":", "bib_name", "=", "self", ".", "bib_name", "# FIXME need to bake in search paths for tex documents in all platforms", "osx_path", "=", "os", ".", "path", ".", "expanduser", "(", "\"~/Library/texmf/bibtex/bib/{0}\"", ".", "format", "(", "bib_name", ")", ")", "if", "self", ".", "_file_exists", "(", "bib_name", ")", ":", "return", "bib_name", "# bib is in project directory", "elif", "os", ".", "path", ".", "exists", "(", "osx_path", ")", ":", "return", "osx_path", "else", ":", "return", "None" ]
Absolute file path to the .bib bibliography document.
[ "Absolute", "file", "path", "to", "the", ".", "bib", "bibliography", "document", "." ]
803535b939a56d375967cefecd5fdca81323041e
https://github.com/jonathansick/paperweight/blob/803535b939a56d375967cefecd5fdca81323041e/paperweight/document.py#L104-L115
241,428
jonathansick/paperweight
paperweight/document.py
TexDocument.write
def write(self, path): """Write the document's text to a ``path`` on the filesystem.""" with codecs.open(path, 'w', encoding='utf-8') as f: f.write(self.text)
python
def write(self, path): """Write the document's text to a ``path`` on the filesystem.""" with codecs.open(path, 'w', encoding='utf-8') as f: f.write(self.text)
[ "def", "write", "(", "self", ",", "path", ")", ":", "with", "codecs", ".", "open", "(", "path", ",", "'w'", ",", "encoding", "=", "'utf-8'", ")", "as", "f", ":", "f", ".", "write", "(", "self", ".", "text", ")" ]
Write the document's text to a ``path`` on the filesystem.
[ "Write", "the", "document", "s", "text", "to", "a", "path", "on", "the", "filesystem", "." ]
803535b939a56d375967cefecd5fdca81323041e
https://github.com/jonathansick/paperweight/blob/803535b939a56d375967cefecd5fdca81323041e/paperweight/document.py#L212-L215
241,429
jonathansick/paperweight
paperweight/document.py
TexDocument.bibitems
def bibitems(self): """List of bibitem strings appearing in the document.""" bibitems = [] lines = self.text.split('\n') for i, line in enumerate(lines): if line.lstrip().startswith(u'\\bibitem'): # accept this line # check if next line is also part of bibitem # FIXME ugh, re-write j = 1 while True: try: if (lines[i + j].startswith(u'\\bibitem') is False) \ and (lines[i + j] != '\n'): line += lines[i + j] elif "\end{document}" in lines[i + j]: break else: break except IndexError: break else: print line j += 1 print "finished", line bibitems.append(line) return bibitems
python
def bibitems(self): """List of bibitem strings appearing in the document.""" bibitems = [] lines = self.text.split('\n') for i, line in enumerate(lines): if line.lstrip().startswith(u'\\bibitem'): # accept this line # check if next line is also part of bibitem # FIXME ugh, re-write j = 1 while True: try: if (lines[i + j].startswith(u'\\bibitem') is False) \ and (lines[i + j] != '\n'): line += lines[i + j] elif "\end{document}" in lines[i + j]: break else: break except IndexError: break else: print line j += 1 print "finished", line bibitems.append(line) return bibitems
[ "def", "bibitems", "(", "self", ")", ":", "bibitems", "=", "[", "]", "lines", "=", "self", ".", "text", ".", "split", "(", "'\\n'", ")", "for", "i", ",", "line", "in", "enumerate", "(", "lines", ")", ":", "if", "line", ".", "lstrip", "(", ")", ".", "startswith", "(", "u'\\\\bibitem'", ")", ":", "# accept this line", "# check if next line is also part of bibitem", "# FIXME ugh, re-write", "j", "=", "1", "while", "True", ":", "try", ":", "if", "(", "lines", "[", "i", "+", "j", "]", ".", "startswith", "(", "u'\\\\bibitem'", ")", "is", "False", ")", "and", "(", "lines", "[", "i", "+", "j", "]", "!=", "'\\n'", ")", ":", "line", "+=", "lines", "[", "i", "+", "j", "]", "elif", "\"\\end{document}\"", "in", "lines", "[", "i", "+", "j", "]", ":", "break", "else", ":", "break", "except", "IndexError", ":", "break", "else", ":", "print", "line", "j", "+=", "1", "print", "\"finished\"", ",", "line", "bibitems", ".", "append", "(", "line", ")", "return", "bibitems" ]
List of bibitem strings appearing in the document.
[ "List", "of", "bibitem", "strings", "appearing", "in", "the", "document", "." ]
803535b939a56d375967cefecd5fdca81323041e
https://github.com/jonathansick/paperweight/blob/803535b939a56d375967cefecd5fdca81323041e/paperweight/document.py#L218-L244
241,430
jonathansick/paperweight
paperweight/document.py
FilesystemTexDocument.inline_inputs
def inline_inputs(self): """Inline all input latex files references by this document. The inlining is accomplished recursively. The document is modified in place. """ self.text = texutils.inline(self.text, os.path.dirname(self._filepath)) # Remove children self._children = {}
python
def inline_inputs(self): """Inline all input latex files references by this document. The inlining is accomplished recursively. The document is modified in place. """ self.text = texutils.inline(self.text, os.path.dirname(self._filepath)) # Remove children self._children = {}
[ "def", "inline_inputs", "(", "self", ")", ":", "self", ".", "text", "=", "texutils", ".", "inline", "(", "self", ".", "text", ",", "os", ".", "path", ".", "dirname", "(", "self", ".", "_filepath", ")", ")", "# Remove children", "self", ".", "_children", "=", "{", "}" ]
Inline all input latex files references by this document. The inlining is accomplished recursively. The document is modified in place.
[ "Inline", "all", "input", "latex", "files", "references", "by", "this", "document", ".", "The", "inlining", "is", "accomplished", "recursively", ".", "The", "document", "is", "modified", "in", "place", "." ]
803535b939a56d375967cefecd5fdca81323041e
https://github.com/jonathansick/paperweight/blob/803535b939a56d375967cefecd5fdca81323041e/paperweight/document.py#L286-L294
241,431
shreyaspotnis/rampage
rampage/widgets/RampEditor.py
clearLayout
def clearLayout(layout): """Removes all widgets in the layout. Useful when opening a new file, want to clear everything.""" while layout.count(): child = layout.takeAt(0) child.widget().deleteLater()
python
def clearLayout(layout): """Removes all widgets in the layout. Useful when opening a new file, want to clear everything.""" while layout.count(): child = layout.takeAt(0) child.widget().deleteLater()
[ "def", "clearLayout", "(", "layout", ")", ":", "while", "layout", ".", "count", "(", ")", ":", "child", "=", "layout", ".", "takeAt", "(", "0", ")", "child", ".", "widget", "(", ")", ".", "deleteLater", "(", ")" ]
Removes all widgets in the layout. Useful when opening a new file, want to clear everything.
[ "Removes", "all", "widgets", "in", "the", "layout", ".", "Useful", "when", "opening", "a", "new", "file", "want", "to", "clear", "everything", "." ]
e2565aef7ee16ee06523de975e8aa41aca14e3b2
https://github.com/shreyaspotnis/rampage/blob/e2565aef7ee16ee06523de975e8aa41aca14e3b2/rampage/widgets/RampEditor.py#L12-L17
241,432
DallasMorningNews/django-datafreezer
datafreezer/views.py
add_dataset
def add_dataset(request, dataset_id=None): """Handles creation of Dataset models from form POST information. Called by edit_dataset_metadata(...) view between Dataset entry and Data Dictionary entry. If dataset_id is passed as an argument, this function edits a given dataset rather than adding a dataset. Otherwise, a new model is saved to the database. Adds article URLs and scrapes page for headline, saves tags to DB. Returns the same page if validation fails, otherwise returns a redirect to data dictionary creation/edit. """ # Save form to create dataset model # Populate non-form fields if dataset_id: dataset_instance = Dataset.objects.get(pk=dataset_id) metadata_form = DatasetUploadForm( request.POST, request.FILES, instance=dataset_instance ) # metadata_form.base_fields['dataset_file'].required = False else: metadata_form = DatasetUploadForm( request.POST, request.FILES ) if metadata_form.is_valid(): dataset_metadata = metadata_form.save(commit=False) dataset_metadata.uploaded_by = request.user.email dataset_metadata.slug = slugify(dataset_metadata.title) # Find vertical from hub dataset_metadata.vertical_slug = metadata_form.get_vertical_from_hub( dataset_metadata.hub_slug ) dataset_metadata.source_slug = slugify(dataset_metadata.source) # Save to database so that we can add Articles, # DataDictionaries, other foreignkeyed/M2M'd models. dataset_metadata.save() # Create relationships url_list = metadata_form.cleaned_data['appears_in'].split(', ') tag_list = metadata_form.cleaned_data['tags'].split(', ') # print(tag_list) dictionary = DataDictionary() dictionary.author = request.user.email dictionary.save() dataset_metadata.data_dictionary = dictionary dataset_metadata.save() for url in url_list: url = url.strip() if len(url) > 0: article, created = Article.objects.get_or_create(url=url) if created: article_req = requests.get(url) if article_req.status_code == 200: # We good. Get the HTML. page = article_req.content soup = BeautifulSoup(page, 'html.parser') # Looking for <meta ... property="og:title"> meta_title_tag = soup.find( 'meta', attrs={'property': 'og:title'} ) try: # print "Trying og:title..." # print meta_title_tag title = meta_title_tag['content'] except (TypeError, KeyError): # TypeError implies meta_title_tag is None; # KeyError implies that meta_title_tag does not # have a content property. title_tag = soup.find('title') try: # print "Falling back to title..." # print title_tag title = title_tag.text except (TypeError, KeyError): description_tag = soup.find( 'meta', attrs={'property': 'og:description'} ) try: # print "Falling back to description..." # print description_tag title = description_tag['content'] # Fallback value. Display is handled in models. except (TypeError, KeyError): title = None article.title = title article.save() dataset_metadata.appears_in.add(article) for tag in tag_list: if tag: cleanTag = tag.strip().lower() tagToAdd, created = Tag.objects.get_or_create( slug=slugify(cleanTag), defaults={'word': cleanTag} ) dataset_metadata.tags.add(tagToAdd) return redirect( 'datafreezer_datadict_edit', dataset_id=dataset_metadata.id ) return render( request, 'datafreezer/upload.html', { 'fileUploadForm': metadata_form, } )
python
def add_dataset(request, dataset_id=None): """Handles creation of Dataset models from form POST information. Called by edit_dataset_metadata(...) view between Dataset entry and Data Dictionary entry. If dataset_id is passed as an argument, this function edits a given dataset rather than adding a dataset. Otherwise, a new model is saved to the database. Adds article URLs and scrapes page for headline, saves tags to DB. Returns the same page if validation fails, otherwise returns a redirect to data dictionary creation/edit. """ # Save form to create dataset model # Populate non-form fields if dataset_id: dataset_instance = Dataset.objects.get(pk=dataset_id) metadata_form = DatasetUploadForm( request.POST, request.FILES, instance=dataset_instance ) # metadata_form.base_fields['dataset_file'].required = False else: metadata_form = DatasetUploadForm( request.POST, request.FILES ) if metadata_form.is_valid(): dataset_metadata = metadata_form.save(commit=False) dataset_metadata.uploaded_by = request.user.email dataset_metadata.slug = slugify(dataset_metadata.title) # Find vertical from hub dataset_metadata.vertical_slug = metadata_form.get_vertical_from_hub( dataset_metadata.hub_slug ) dataset_metadata.source_slug = slugify(dataset_metadata.source) # Save to database so that we can add Articles, # DataDictionaries, other foreignkeyed/M2M'd models. dataset_metadata.save() # Create relationships url_list = metadata_form.cleaned_data['appears_in'].split(', ') tag_list = metadata_form.cleaned_data['tags'].split(', ') # print(tag_list) dictionary = DataDictionary() dictionary.author = request.user.email dictionary.save() dataset_metadata.data_dictionary = dictionary dataset_metadata.save() for url in url_list: url = url.strip() if len(url) > 0: article, created = Article.objects.get_or_create(url=url) if created: article_req = requests.get(url) if article_req.status_code == 200: # We good. Get the HTML. page = article_req.content soup = BeautifulSoup(page, 'html.parser') # Looking for <meta ... property="og:title"> meta_title_tag = soup.find( 'meta', attrs={'property': 'og:title'} ) try: # print "Trying og:title..." # print meta_title_tag title = meta_title_tag['content'] except (TypeError, KeyError): # TypeError implies meta_title_tag is None; # KeyError implies that meta_title_tag does not # have a content property. title_tag = soup.find('title') try: # print "Falling back to title..." # print title_tag title = title_tag.text except (TypeError, KeyError): description_tag = soup.find( 'meta', attrs={'property': 'og:description'} ) try: # print "Falling back to description..." # print description_tag title = description_tag['content'] # Fallback value. Display is handled in models. except (TypeError, KeyError): title = None article.title = title article.save() dataset_metadata.appears_in.add(article) for tag in tag_list: if tag: cleanTag = tag.strip().lower() tagToAdd, created = Tag.objects.get_or_create( slug=slugify(cleanTag), defaults={'word': cleanTag} ) dataset_metadata.tags.add(tagToAdd) return redirect( 'datafreezer_datadict_edit', dataset_id=dataset_metadata.id ) return render( request, 'datafreezer/upload.html', { 'fileUploadForm': metadata_form, } )
[ "def", "add_dataset", "(", "request", ",", "dataset_id", "=", "None", ")", ":", "# Save form to create dataset model", "# Populate non-form fields", "if", "dataset_id", ":", "dataset_instance", "=", "Dataset", ".", "objects", ".", "get", "(", "pk", "=", "dataset_id", ")", "metadata_form", "=", "DatasetUploadForm", "(", "request", ".", "POST", ",", "request", ".", "FILES", ",", "instance", "=", "dataset_instance", ")", "# metadata_form.base_fields['dataset_file'].required = False", "else", ":", "metadata_form", "=", "DatasetUploadForm", "(", "request", ".", "POST", ",", "request", ".", "FILES", ")", "if", "metadata_form", ".", "is_valid", "(", ")", ":", "dataset_metadata", "=", "metadata_form", ".", "save", "(", "commit", "=", "False", ")", "dataset_metadata", ".", "uploaded_by", "=", "request", ".", "user", ".", "email", "dataset_metadata", ".", "slug", "=", "slugify", "(", "dataset_metadata", ".", "title", ")", "# Find vertical from hub", "dataset_metadata", ".", "vertical_slug", "=", "metadata_form", ".", "get_vertical_from_hub", "(", "dataset_metadata", ".", "hub_slug", ")", "dataset_metadata", ".", "source_slug", "=", "slugify", "(", "dataset_metadata", ".", "source", ")", "# Save to database so that we can add Articles,", "# DataDictionaries, other foreignkeyed/M2M'd models.", "dataset_metadata", ".", "save", "(", ")", "# Create relationships", "url_list", "=", "metadata_form", ".", "cleaned_data", "[", "'appears_in'", "]", ".", "split", "(", "', '", ")", "tag_list", "=", "metadata_form", ".", "cleaned_data", "[", "'tags'", "]", ".", "split", "(", "', '", ")", "# print(tag_list)", "dictionary", "=", "DataDictionary", "(", ")", "dictionary", ".", "author", "=", "request", ".", "user", ".", "email", "dictionary", ".", "save", "(", ")", "dataset_metadata", ".", "data_dictionary", "=", "dictionary", "dataset_metadata", ".", "save", "(", ")", "for", "url", "in", "url_list", ":", "url", "=", "url", ".", "strip", "(", ")", "if", "len", "(", "url", ")", ">", "0", ":", "article", ",", "created", "=", "Article", ".", "objects", ".", "get_or_create", "(", "url", "=", "url", ")", "if", "created", ":", "article_req", "=", "requests", ".", "get", "(", "url", ")", "if", "article_req", ".", "status_code", "==", "200", ":", "# We good. Get the HTML.", "page", "=", "article_req", ".", "content", "soup", "=", "BeautifulSoup", "(", "page", ",", "'html.parser'", ")", "# Looking for <meta ... property=\"og:title\">", "meta_title_tag", "=", "soup", ".", "find", "(", "'meta'", ",", "attrs", "=", "{", "'property'", ":", "'og:title'", "}", ")", "try", ":", "# print \"Trying og:title...\"", "# print meta_title_tag", "title", "=", "meta_title_tag", "[", "'content'", "]", "except", "(", "TypeError", ",", "KeyError", ")", ":", "# TypeError implies meta_title_tag is None;", "# KeyError implies that meta_title_tag does not", "# have a content property.", "title_tag", "=", "soup", ".", "find", "(", "'title'", ")", "try", ":", "# print \"Falling back to title...\"", "# print title_tag", "title", "=", "title_tag", ".", "text", "except", "(", "TypeError", ",", "KeyError", ")", ":", "description_tag", "=", "soup", ".", "find", "(", "'meta'", ",", "attrs", "=", "{", "'property'", ":", "'og:description'", "}", ")", "try", ":", "# print \"Falling back to description...\"", "# print description_tag", "title", "=", "description_tag", "[", "'content'", "]", "# Fallback value. Display is handled in models.", "except", "(", "TypeError", ",", "KeyError", ")", ":", "title", "=", "None", "article", ".", "title", "=", "title", "article", ".", "save", "(", ")", "dataset_metadata", ".", "appears_in", ".", "add", "(", "article", ")", "for", "tag", "in", "tag_list", ":", "if", "tag", ":", "cleanTag", "=", "tag", ".", "strip", "(", ")", ".", "lower", "(", ")", "tagToAdd", ",", "created", "=", "Tag", ".", "objects", ".", "get_or_create", "(", "slug", "=", "slugify", "(", "cleanTag", ")", ",", "defaults", "=", "{", "'word'", ":", "cleanTag", "}", ")", "dataset_metadata", ".", "tags", ".", "add", "(", "tagToAdd", ")", "return", "redirect", "(", "'datafreezer_datadict_edit'", ",", "dataset_id", "=", "dataset_metadata", ".", "id", ")", "return", "render", "(", "request", ",", "'datafreezer/upload.html'", ",", "{", "'fileUploadForm'", ":", "metadata_form", ",", "}", ")" ]
Handles creation of Dataset models from form POST information. Called by edit_dataset_metadata(...) view between Dataset entry and Data Dictionary entry. If dataset_id is passed as an argument, this function edits a given dataset rather than adding a dataset. Otherwise, a new model is saved to the database. Adds article URLs and scrapes page for headline, saves tags to DB. Returns the same page if validation fails, otherwise returns a redirect to data dictionary creation/edit.
[ "Handles", "creation", "of", "Dataset", "models", "from", "form", "POST", "information", "." ]
982dcf2015c80a280f1a093e32977cb71d4ea7aa
https://github.com/DallasMorningNews/django-datafreezer/blob/982dcf2015c80a280f1a093e32977cb71d4ea7aa/datafreezer/views.py#L115-L250
241,433
DallasMorningNews/django-datafreezer
datafreezer/views.py
parse_csv_headers
def parse_csv_headers(dataset_id): """Return the first row of a CSV as a list of headers.""" data = Dataset.objects.get(pk=dataset_id) with open(data.dataset_file.path, 'r') as datasetFile: csvReader = reader(datasetFile, delimiter=',', quotechar='"') headers = next(csvReader) # print headers return headers
python
def parse_csv_headers(dataset_id): """Return the first row of a CSV as a list of headers.""" data = Dataset.objects.get(pk=dataset_id) with open(data.dataset_file.path, 'r') as datasetFile: csvReader = reader(datasetFile, delimiter=',', quotechar='"') headers = next(csvReader) # print headers return headers
[ "def", "parse_csv_headers", "(", "dataset_id", ")", ":", "data", "=", "Dataset", ".", "objects", ".", "get", "(", "pk", "=", "dataset_id", ")", "with", "open", "(", "data", ".", "dataset_file", ".", "path", ",", "'r'", ")", "as", "datasetFile", ":", "csvReader", "=", "reader", "(", "datasetFile", ",", "delimiter", "=", "','", ",", "quotechar", "=", "'\"'", ")", "headers", "=", "next", "(", "csvReader", ")", "# print headers", "return", "headers" ]
Return the first row of a CSV as a list of headers.
[ "Return", "the", "first", "row", "of", "a", "CSV", "as", "a", "list", "of", "headers", "." ]
982dcf2015c80a280f1a093e32977cb71d4ea7aa
https://github.com/DallasMorningNews/django-datafreezer/blob/982dcf2015c80a280f1a093e32977cb71d4ea7aa/datafreezer/views.py#L253-L260
241,434
DallasMorningNews/django-datafreezer
datafreezer/views.py
grab_names_from_emails
def grab_names_from_emails(email_list): """Return a dictionary mapping names to email addresses. Only gives a response if the email is found in the staff API/JSON. Expects an API of the format = [ { 'email': 'foo@bar.net', ... 'fullName': 'Frank Oo' }, ... ] """ all_staff = STAFF_LIST emails_names = {} for email in email_list: for person in all_staff: if email == person['email'] and email not in emails_names: emails_names[email] = person['fullName'] # print emails_names[email] for email in email_list: matched = False for assignment in emails_names: if email == assignment: matched = True if not matched: emails_names[email] = email return emails_names
python
def grab_names_from_emails(email_list): """Return a dictionary mapping names to email addresses. Only gives a response if the email is found in the staff API/JSON. Expects an API of the format = [ { 'email': 'foo@bar.net', ... 'fullName': 'Frank Oo' }, ... ] """ all_staff = STAFF_LIST emails_names = {} for email in email_list: for person in all_staff: if email == person['email'] and email not in emails_names: emails_names[email] = person['fullName'] # print emails_names[email] for email in email_list: matched = False for assignment in emails_names: if email == assignment: matched = True if not matched: emails_names[email] = email return emails_names
[ "def", "grab_names_from_emails", "(", "email_list", ")", ":", "all_staff", "=", "STAFF_LIST", "emails_names", "=", "{", "}", "for", "email", "in", "email_list", ":", "for", "person", "in", "all_staff", ":", "if", "email", "==", "person", "[", "'email'", "]", "and", "email", "not", "in", "emails_names", ":", "emails_names", "[", "email", "]", "=", "person", "[", "'fullName'", "]", "# print emails_names[email]", "for", "email", "in", "email_list", ":", "matched", "=", "False", "for", "assignment", "in", "emails_names", ":", "if", "email", "==", "assignment", ":", "matched", "=", "True", "if", "not", "matched", ":", "emails_names", "[", "email", "]", "=", "email", "return", "emails_names" ]
Return a dictionary mapping names to email addresses. Only gives a response if the email is found in the staff API/JSON. Expects an API of the format = [ { 'email': 'foo@bar.net', ... 'fullName': 'Frank Oo' }, ... ]
[ "Return", "a", "dictionary", "mapping", "names", "to", "email", "addresses", "." ]
982dcf2015c80a280f1a093e32977cb71d4ea7aa
https://github.com/DallasMorningNews/django-datafreezer/blob/982dcf2015c80a280f1a093e32977cb71d4ea7aa/datafreezer/views.py#L264-L299
241,435
DallasMorningNews/django-datafreezer
datafreezer/views.py
tag_lookup
def tag_lookup(request): """JSON endpoint that returns a list of potential tags. Used for upload template autocomplete. """ tag = request.GET['tag'] tagSlug = slugify(tag.strip()) tagCandidates = Tag.objects.values('word').filter(slug__startswith=tagSlug) tags = json.dumps([candidate['word'] for candidate in tagCandidates]) return HttpResponse(tags, content_type='application/json')
python
def tag_lookup(request): """JSON endpoint that returns a list of potential tags. Used for upload template autocomplete. """ tag = request.GET['tag'] tagSlug = slugify(tag.strip()) tagCandidates = Tag.objects.values('word').filter(slug__startswith=tagSlug) tags = json.dumps([candidate['word'] for candidate in tagCandidates]) return HttpResponse(tags, content_type='application/json')
[ "def", "tag_lookup", "(", "request", ")", ":", "tag", "=", "request", ".", "GET", "[", "'tag'", "]", "tagSlug", "=", "slugify", "(", "tag", ".", "strip", "(", ")", ")", "tagCandidates", "=", "Tag", ".", "objects", ".", "values", "(", "'word'", ")", ".", "filter", "(", "slug__startswith", "=", "tagSlug", ")", "tags", "=", "json", ".", "dumps", "(", "[", "candidate", "[", "'word'", "]", "for", "candidate", "in", "tagCandidates", "]", ")", "return", "HttpResponse", "(", "tags", ",", "content_type", "=", "'application/json'", ")" ]
JSON endpoint that returns a list of potential tags. Used for upload template autocomplete.
[ "JSON", "endpoint", "that", "returns", "a", "list", "of", "potential", "tags", "." ]
982dcf2015c80a280f1a093e32977cb71d4ea7aa
https://github.com/DallasMorningNews/django-datafreezer/blob/982dcf2015c80a280f1a093e32977cb71d4ea7aa/datafreezer/views.py#L321-L331
241,436
DallasMorningNews/django-datafreezer
datafreezer/views.py
source_lookup
def source_lookup(request): """JSON endpoint that returns a list of potential sources. Used for upload template autocomplete. """ source = request.GET['source'] source_slug = slugify(source.strip()) source_candidates = Dataset.objects.values('source').filter( source_slug__startswith=source_slug ) sources = json.dumps([cand['source'] for cand in source_candidates]) return HttpResponse(sources, content_type='application/json')
python
def source_lookup(request): """JSON endpoint that returns a list of potential sources. Used for upload template autocomplete. """ source = request.GET['source'] source_slug = slugify(source.strip()) source_candidates = Dataset.objects.values('source').filter( source_slug__startswith=source_slug ) sources = json.dumps([cand['source'] for cand in source_candidates]) return HttpResponse(sources, content_type='application/json')
[ "def", "source_lookup", "(", "request", ")", ":", "source", "=", "request", ".", "GET", "[", "'source'", "]", "source_slug", "=", "slugify", "(", "source", ".", "strip", "(", ")", ")", "source_candidates", "=", "Dataset", ".", "objects", ".", "values", "(", "'source'", ")", ".", "filter", "(", "source_slug__startswith", "=", "source_slug", ")", "sources", "=", "json", ".", "dumps", "(", "[", "cand", "[", "'source'", "]", "for", "cand", "in", "source_candidates", "]", ")", "return", "HttpResponse", "(", "sources", ",", "content_type", "=", "'application/json'", ")" ]
JSON endpoint that returns a list of potential sources. Used for upload template autocomplete.
[ "JSON", "endpoint", "that", "returns", "a", "list", "of", "potential", "sources", "." ]
982dcf2015c80a280f1a093e32977cb71d4ea7aa
https://github.com/DallasMorningNews/django-datafreezer/blob/982dcf2015c80a280f1a093e32977cb71d4ea7aa/datafreezer/views.py#L335-L347
241,437
DallasMorningNews/django-datafreezer
datafreezer/views.py
download_data_dictionary
def download_data_dictionary(request, dataset_id): """Generates and returns compiled data dictionary from database. Returned as a CSV response. """ dataset = Dataset.objects.get(pk=dataset_id) dataDict = dataset.data_dictionary fields = DataDictionaryField.objects.filter( parent_dict=dataDict ).order_by('columnIndex') response = HttpResponse(content_type='text/csv') csvName = slugify(dataset.title + ' data dict') + '.csv' response['Content-Disposition'] = 'attachment; filename=%s' % (csvName) csvWriter = writer(response) metaHeader = [ 'Data Dictionary for {0} prepared by {1}'.format( dataset.title, dataset.uploaded_by ) ] csvWriter.writerow(metaHeader) trueHeader = ['Column Index', 'Heading', 'Description', 'Data Type'] csvWriter.writerow(trueHeader) for field in fields: mappedIndex = field.COLUMN_INDEX_CHOICES[field.columnIndex-1][1] csvWriter.writerow( [mappedIndex, field.heading, field.description, field.dataType] ) return response
python
def download_data_dictionary(request, dataset_id): """Generates and returns compiled data dictionary from database. Returned as a CSV response. """ dataset = Dataset.objects.get(pk=dataset_id) dataDict = dataset.data_dictionary fields = DataDictionaryField.objects.filter( parent_dict=dataDict ).order_by('columnIndex') response = HttpResponse(content_type='text/csv') csvName = slugify(dataset.title + ' data dict') + '.csv' response['Content-Disposition'] = 'attachment; filename=%s' % (csvName) csvWriter = writer(response) metaHeader = [ 'Data Dictionary for {0} prepared by {1}'.format( dataset.title, dataset.uploaded_by ) ] csvWriter.writerow(metaHeader) trueHeader = ['Column Index', 'Heading', 'Description', 'Data Type'] csvWriter.writerow(trueHeader) for field in fields: mappedIndex = field.COLUMN_INDEX_CHOICES[field.columnIndex-1][1] csvWriter.writerow( [mappedIndex, field.heading, field.description, field.dataType] ) return response
[ "def", "download_data_dictionary", "(", "request", ",", "dataset_id", ")", ":", "dataset", "=", "Dataset", ".", "objects", ".", "get", "(", "pk", "=", "dataset_id", ")", "dataDict", "=", "dataset", ".", "data_dictionary", "fields", "=", "DataDictionaryField", ".", "objects", ".", "filter", "(", "parent_dict", "=", "dataDict", ")", ".", "order_by", "(", "'columnIndex'", ")", "response", "=", "HttpResponse", "(", "content_type", "=", "'text/csv'", ")", "csvName", "=", "slugify", "(", "dataset", ".", "title", "+", "' data dict'", ")", "+", "'.csv'", "response", "[", "'Content-Disposition'", "]", "=", "'attachment; filename=%s'", "%", "(", "csvName", ")", "csvWriter", "=", "writer", "(", "response", ")", "metaHeader", "=", "[", "'Data Dictionary for {0} prepared by {1}'", ".", "format", "(", "dataset", ".", "title", ",", "dataset", ".", "uploaded_by", ")", "]", "csvWriter", ".", "writerow", "(", "metaHeader", ")", "trueHeader", "=", "[", "'Column Index'", ",", "'Heading'", ",", "'Description'", ",", "'Data Type'", "]", "csvWriter", ".", "writerow", "(", "trueHeader", ")", "for", "field", "in", "fields", ":", "mappedIndex", "=", "field", ".", "COLUMN_INDEX_CHOICES", "[", "field", ".", "columnIndex", "-", "1", "]", "[", "1", "]", "csvWriter", ".", "writerow", "(", "[", "mappedIndex", ",", "field", ".", "heading", ",", "field", ".", "description", ",", "field", ".", "dataType", "]", ")", "return", "response" ]
Generates and returns compiled data dictionary from database. Returned as a CSV response.
[ "Generates", "and", "returns", "compiled", "data", "dictionary", "from", "database", "." ]
982dcf2015c80a280f1a093e32977cb71d4ea7aa
https://github.com/DallasMorningNews/django-datafreezer/blob/982dcf2015c80a280f1a093e32977cb71d4ea7aa/datafreezer/views.py#L351-L383
241,438
DallasMorningNews/django-datafreezer
datafreezer/views.py
home
def home(request): """Renders Datafreezer homepage. Includes recent uploads.""" recent_uploads = Dataset.objects.order_by('-date_uploaded')[:11] email_list = [upload.uploaded_by.strip() for upload in recent_uploads] # print all_staff emails_names = grab_names_from_emails(email_list) # print emails_names for upload in recent_uploads: for item in emails_names: if upload.uploaded_by == item: upload.fullName = emails_names[item] for upload in recent_uploads: if not hasattr(upload, 'fullName'): upload.fullName = upload.uploaded_by return render( request, 'datafreezer/home.html', { 'recent_uploads': recent_uploads, 'heading': 'Most Recent Uploads' } )
python
def home(request): """Renders Datafreezer homepage. Includes recent uploads.""" recent_uploads = Dataset.objects.order_by('-date_uploaded')[:11] email_list = [upload.uploaded_by.strip() for upload in recent_uploads] # print all_staff emails_names = grab_names_from_emails(email_list) # print emails_names for upload in recent_uploads: for item in emails_names: if upload.uploaded_by == item: upload.fullName = emails_names[item] for upload in recent_uploads: if not hasattr(upload, 'fullName'): upload.fullName = upload.uploaded_by return render( request, 'datafreezer/home.html', { 'recent_uploads': recent_uploads, 'heading': 'Most Recent Uploads' } )
[ "def", "home", "(", "request", ")", ":", "recent_uploads", "=", "Dataset", ".", "objects", ".", "order_by", "(", "'-date_uploaded'", ")", "[", ":", "11", "]", "email_list", "=", "[", "upload", ".", "uploaded_by", ".", "strip", "(", ")", "for", "upload", "in", "recent_uploads", "]", "# print all_staff", "emails_names", "=", "grab_names_from_emails", "(", "email_list", ")", "# print emails_names", "for", "upload", "in", "recent_uploads", ":", "for", "item", "in", "emails_names", ":", "if", "upload", ".", "uploaded_by", "==", "item", ":", "upload", ".", "fullName", "=", "emails_names", "[", "item", "]", "for", "upload", "in", "recent_uploads", ":", "if", "not", "hasattr", "(", "upload", ",", "'fullName'", ")", ":", "upload", ".", "fullName", "=", "upload", ".", "uploaded_by", "return", "render", "(", "request", ",", "'datafreezer/home.html'", ",", "{", "'recent_uploads'", ":", "recent_uploads", ",", "'heading'", ":", "'Most Recent Uploads'", "}", ")" ]
Renders Datafreezer homepage. Includes recent uploads.
[ "Renders", "Datafreezer", "homepage", ".", "Includes", "recent", "uploads", "." ]
982dcf2015c80a280f1a093e32977cb71d4ea7aa
https://github.com/DallasMorningNews/django-datafreezer/blob/982dcf2015c80a280f1a093e32977cb71d4ea7aa/datafreezer/views.py#L388-L414
241,439
DallasMorningNews/django-datafreezer
datafreezer/views.py
edit_dataset_metadata
def edit_dataset_metadata(request, dataset_id=None): """Renders a template to upload or edit a Dataset. Most of the heavy lifting is done by add_dataset(...). """ if request.method == 'POST': return add_dataset(request, dataset_id) elif request.method == 'GET': # create a blank form # Edit if dataset_id: metadata_form = DatasetUploadForm( instance=get_object_or_404(Dataset, pk=dataset_id) ) # Upload else: metadata_form = DatasetUploadForm() return render( request, 'datafreezer/upload.html', { 'fileUploadForm': metadata_form, } )
python
def edit_dataset_metadata(request, dataset_id=None): """Renders a template to upload or edit a Dataset. Most of the heavy lifting is done by add_dataset(...). """ if request.method == 'POST': return add_dataset(request, dataset_id) elif request.method == 'GET': # create a blank form # Edit if dataset_id: metadata_form = DatasetUploadForm( instance=get_object_or_404(Dataset, pk=dataset_id) ) # Upload else: metadata_form = DatasetUploadForm() return render( request, 'datafreezer/upload.html', { 'fileUploadForm': metadata_form, } )
[ "def", "edit_dataset_metadata", "(", "request", ",", "dataset_id", "=", "None", ")", ":", "if", "request", ".", "method", "==", "'POST'", ":", "return", "add_dataset", "(", "request", ",", "dataset_id", ")", "elif", "request", ".", "method", "==", "'GET'", ":", "# create a blank form", "# Edit", "if", "dataset_id", ":", "metadata_form", "=", "DatasetUploadForm", "(", "instance", "=", "get_object_or_404", "(", "Dataset", ",", "pk", "=", "dataset_id", ")", ")", "# Upload", "else", ":", "metadata_form", "=", "DatasetUploadForm", "(", ")", "return", "render", "(", "request", ",", "'datafreezer/upload.html'", ",", "{", "'fileUploadForm'", ":", "metadata_form", ",", "}", ")" ]
Renders a template to upload or edit a Dataset. Most of the heavy lifting is done by add_dataset(...).
[ "Renders", "a", "template", "to", "upload", "or", "edit", "a", "Dataset", "." ]
982dcf2015c80a280f1a093e32977cb71d4ea7aa
https://github.com/DallasMorningNews/django-datafreezer/blob/982dcf2015c80a280f1a093e32977cb71d4ea7aa/datafreezer/views.py#L419-L445
241,440
DallasMorningNews/django-datafreezer
datafreezer/views.py
dataset_detail
def dataset_detail(request, dataset_id): """Renders individual dataset detail page.""" active_dataset = get_object_or_404(Dataset, pk=dataset_id) datadict_id = active_dataset.data_dictionary_id datadict = DataDictionaryField.objects.filter( parent_dict=datadict_id ).order_by('columnIndex') uploader_name = grab_names_from_emails([active_dataset.uploaded_by]) tags = Tag.objects.filter(dataset=dataset_id) articles = Article.objects.filter(dataset=dataset_id) for hub in HUBS_LIST: if hub['slug'] == active_dataset.hub_slug: active_dataset.hub = hub['name'] active_dataset.vertical = hub['vertical']['name'] if len(uploader_name) == 0: uploader_name = active_dataset.uploaded_by else: uploader_name = uploader_name[active_dataset.uploaded_by] return render( request, 'datafreezer/dataset_details.html', { 'dataset': active_dataset, 'datadict': datadict, 'uploader_name': uploader_name, 'tags': tags, 'articles': articles, } )
python
def dataset_detail(request, dataset_id): """Renders individual dataset detail page.""" active_dataset = get_object_or_404(Dataset, pk=dataset_id) datadict_id = active_dataset.data_dictionary_id datadict = DataDictionaryField.objects.filter( parent_dict=datadict_id ).order_by('columnIndex') uploader_name = grab_names_from_emails([active_dataset.uploaded_by]) tags = Tag.objects.filter(dataset=dataset_id) articles = Article.objects.filter(dataset=dataset_id) for hub in HUBS_LIST: if hub['slug'] == active_dataset.hub_slug: active_dataset.hub = hub['name'] active_dataset.vertical = hub['vertical']['name'] if len(uploader_name) == 0: uploader_name = active_dataset.uploaded_by else: uploader_name = uploader_name[active_dataset.uploaded_by] return render( request, 'datafreezer/dataset_details.html', { 'dataset': active_dataset, 'datadict': datadict, 'uploader_name': uploader_name, 'tags': tags, 'articles': articles, } )
[ "def", "dataset_detail", "(", "request", ",", "dataset_id", ")", ":", "active_dataset", "=", "get_object_or_404", "(", "Dataset", ",", "pk", "=", "dataset_id", ")", "datadict_id", "=", "active_dataset", ".", "data_dictionary_id", "datadict", "=", "DataDictionaryField", ".", "objects", ".", "filter", "(", "parent_dict", "=", "datadict_id", ")", ".", "order_by", "(", "'columnIndex'", ")", "uploader_name", "=", "grab_names_from_emails", "(", "[", "active_dataset", ".", "uploaded_by", "]", ")", "tags", "=", "Tag", ".", "objects", ".", "filter", "(", "dataset", "=", "dataset_id", ")", "articles", "=", "Article", ".", "objects", ".", "filter", "(", "dataset", "=", "dataset_id", ")", "for", "hub", "in", "HUBS_LIST", ":", "if", "hub", "[", "'slug'", "]", "==", "active_dataset", ".", "hub_slug", ":", "active_dataset", ".", "hub", "=", "hub", "[", "'name'", "]", "active_dataset", ".", "vertical", "=", "hub", "[", "'vertical'", "]", "[", "'name'", "]", "if", "len", "(", "uploader_name", ")", "==", "0", ":", "uploader_name", "=", "active_dataset", ".", "uploaded_by", "else", ":", "uploader_name", "=", "uploader_name", "[", "active_dataset", ".", "uploaded_by", "]", "return", "render", "(", "request", ",", "'datafreezer/dataset_details.html'", ",", "{", "'dataset'", ":", "active_dataset", ",", "'datadict'", ":", "datadict", ",", "'uploader_name'", ":", "uploader_name", ",", "'tags'", ":", "tags", ",", "'articles'", ":", "articles", ",", "}", ")" ]
Renders individual dataset detail page.
[ "Renders", "individual", "dataset", "detail", "page", "." ]
982dcf2015c80a280f1a093e32977cb71d4ea7aa
https://github.com/DallasMorningNews/django-datafreezer/blob/982dcf2015c80a280f1a093e32977cb71d4ea7aa/datafreezer/views.py#L535-L566
241,441
DallasMorningNews/django-datafreezer
datafreezer/views.py
PaginatedBrowseAll.get
def get(self, request): """Handle HTTP GET request. Returns template and context from generate_page_title and generate_sections to populate template. """ sections_list = self.generate_sections() p = Paginator(sections_list, 25) page = request.GET.get('page') try: sections = p.page(page) except PageNotAnInteger: # If page is not an integer, deliver first page. sections = p.page(1) except EmptyPage: # If page is out of range (e.g. 9999), return last page of results. sections = p.page(p.num_pages) context = { 'sections': sections, 'page_title': self.generate_page_title(), 'browse_type': self.browse_type } return render( request, self.template_path, context )
python
def get(self, request): """Handle HTTP GET request. Returns template and context from generate_page_title and generate_sections to populate template. """ sections_list = self.generate_sections() p = Paginator(sections_list, 25) page = request.GET.get('page') try: sections = p.page(page) except PageNotAnInteger: # If page is not an integer, deliver first page. sections = p.page(1) except EmptyPage: # If page is out of range (e.g. 9999), return last page of results. sections = p.page(p.num_pages) context = { 'sections': sections, 'page_title': self.generate_page_title(), 'browse_type': self.browse_type } return render( request, self.template_path, context )
[ "def", "get", "(", "self", ",", "request", ")", ":", "sections_list", "=", "self", ".", "generate_sections", "(", ")", "p", "=", "Paginator", "(", "sections_list", ",", "25", ")", "page", "=", "request", ".", "GET", ".", "get", "(", "'page'", ")", "try", ":", "sections", "=", "p", ".", "page", "(", "page", ")", "except", "PageNotAnInteger", ":", "# If page is not an integer, deliver first page.", "sections", "=", "p", ".", "page", "(", "1", ")", "except", "EmptyPage", ":", "# If page is out of range (e.g. 9999), return last page of results.", "sections", "=", "p", ".", "page", "(", "p", ".", "num_pages", ")", "context", "=", "{", "'sections'", ":", "sections", ",", "'page_title'", ":", "self", ".", "generate_page_title", "(", ")", ",", "'browse_type'", ":", "self", ".", "browse_type", "}", "return", "render", "(", "request", ",", "self", ".", "template_path", ",", "context", ")" ]
Handle HTTP GET request. Returns template and context from generate_page_title and generate_sections to populate template.
[ "Handle", "HTTP", "GET", "request", "." ]
982dcf2015c80a280f1a093e32977cb71d4ea7aa
https://github.com/DallasMorningNews/django-datafreezer/blob/982dcf2015c80a280f1a093e32977cb71d4ea7aa/datafreezer/views.py#L628-L659
241,442
DallasMorningNews/django-datafreezer
datafreezer/views.py
BrowseBase.get
def get(self, request): """View for HTTP GET method. Returns template and context from generate_page_title and generate_sections to populate template. """ sections = self.generate_sections() if self.paginated: p = Paginator(sections, 25) page = request.GET.get('page') try: sections = p.page(page) except PageNotAnInteger: # If page is not an integer, deliver first page. sections = p.page(1) except EmptyPage: # If page is out of range (e.g. 9999), return last page # of results. sections = p.page(p.num_pages) pageUpper = int(p.num_pages) / 2 try: pageLower = int(page) / 2 except TypeError: pageLower = -999 else: pageUpper = None pageLower = None context = { 'sections': sections, 'page_title': self.generate_page_title(), 'browse_type': self.browse_type, 'pageUpper': pageUpper, 'pageLower': pageLower } return render( request, self.template_path, context )
python
def get(self, request): """View for HTTP GET method. Returns template and context from generate_page_title and generate_sections to populate template. """ sections = self.generate_sections() if self.paginated: p = Paginator(sections, 25) page = request.GET.get('page') try: sections = p.page(page) except PageNotAnInteger: # If page is not an integer, deliver first page. sections = p.page(1) except EmptyPage: # If page is out of range (e.g. 9999), return last page # of results. sections = p.page(p.num_pages) pageUpper = int(p.num_pages) / 2 try: pageLower = int(page) / 2 except TypeError: pageLower = -999 else: pageUpper = None pageLower = None context = { 'sections': sections, 'page_title': self.generate_page_title(), 'browse_type': self.browse_type, 'pageUpper': pageUpper, 'pageLower': pageLower } return render( request, self.template_path, context )
[ "def", "get", "(", "self", ",", "request", ")", ":", "sections", "=", "self", ".", "generate_sections", "(", ")", "if", "self", ".", "paginated", ":", "p", "=", "Paginator", "(", "sections", ",", "25", ")", "page", "=", "request", ".", "GET", ".", "get", "(", "'page'", ")", "try", ":", "sections", "=", "p", ".", "page", "(", "page", ")", "except", "PageNotAnInteger", ":", "# If page is not an integer, deliver first page.", "sections", "=", "p", ".", "page", "(", "1", ")", "except", "EmptyPage", ":", "# If page is out of range (e.g. 9999), return last page", "# of results.", "sections", "=", "p", ".", "page", "(", "p", ".", "num_pages", ")", "pageUpper", "=", "int", "(", "p", ".", "num_pages", ")", "/", "2", "try", ":", "pageLower", "=", "int", "(", "page", ")", "/", "2", "except", "TypeError", ":", "pageLower", "=", "-", "999", "else", ":", "pageUpper", "=", "None", "pageLower", "=", "None", "context", "=", "{", "'sections'", ":", "sections", ",", "'page_title'", ":", "self", ".", "generate_page_title", "(", ")", ",", "'browse_type'", ":", "self", ".", "browse_type", ",", "'pageUpper'", ":", "pageUpper", ",", "'pageLower'", ":", "pageLower", "}", "return", "render", "(", "request", ",", "self", ".", "template_path", ",", "context", ")" ]
View for HTTP GET method. Returns template and context from generate_page_title and generate_sections to populate template.
[ "View", "for", "HTTP", "GET", "method", "." ]
982dcf2015c80a280f1a093e32977cb71d4ea7aa
https://github.com/DallasMorningNews/django-datafreezer/blob/982dcf2015c80a280f1a093e32977cb71d4ea7aa/datafreezer/views.py#L690-L735
241,443
DallasMorningNews/django-datafreezer
datafreezer/views.py
BrowseHubs.generate_sections
def generate_sections(self): """Return all hubs, slugs, and upload counts.""" datasets = Dataset.objects.values( 'hub_slug' ).annotate( upload_count=Count( 'hub_slug' ) ).order_by('-upload_count') return [ { 'count': dataset['upload_count'], 'name': get_hub_name_from_slug(dataset['hub_slug']), 'slug': dataset['hub_slug'] } for dataset in datasets ]
python
def generate_sections(self): """Return all hubs, slugs, and upload counts.""" datasets = Dataset.objects.values( 'hub_slug' ).annotate( upload_count=Count( 'hub_slug' ) ).order_by('-upload_count') return [ { 'count': dataset['upload_count'], 'name': get_hub_name_from_slug(dataset['hub_slug']), 'slug': dataset['hub_slug'] } for dataset in datasets ]
[ "def", "generate_sections", "(", "self", ")", ":", "datasets", "=", "Dataset", ".", "objects", ".", "values", "(", "'hub_slug'", ")", ".", "annotate", "(", "upload_count", "=", "Count", "(", "'hub_slug'", ")", ")", ".", "order_by", "(", "'-upload_count'", ")", "return", "[", "{", "'count'", ":", "dataset", "[", "'upload_count'", "]", ",", "'name'", ":", "get_hub_name_from_slug", "(", "dataset", "[", "'hub_slug'", "]", ")", ",", "'slug'", ":", "dataset", "[", "'hub_slug'", "]", "}", "for", "dataset", "in", "datasets", "]" ]
Return all hubs, slugs, and upload counts.
[ "Return", "all", "hubs", "slugs", "and", "upload", "counts", "." ]
982dcf2015c80a280f1a093e32977cb71d4ea7aa
https://github.com/DallasMorningNews/django-datafreezer/blob/982dcf2015c80a280f1a093e32977cb71d4ea7aa/datafreezer/views.py#L777-L794
241,444
DallasMorningNews/django-datafreezer
datafreezer/views.py
BrowseAuthors.generate_sections
def generate_sections(self): """Return all authors to which datasets have been attributed.""" authors = Dataset.objects.values( 'uploaded_by' ).annotate( upload_count=Count( 'uploaded_by' ) ).order_by('-upload_count') email_name_map = grab_names_from_emails( [row['uploaded_by'] for row in authors] ) for author in authors: for emailKey in email_name_map: if author['uploaded_by'] == emailKey: author['name'] = email_name_map[emailKey] return [ { 'slug': author['uploaded_by'], 'name': author['name'], 'count': author['upload_count'] } for author in authors ]
python
def generate_sections(self): """Return all authors to which datasets have been attributed.""" authors = Dataset.objects.values( 'uploaded_by' ).annotate( upload_count=Count( 'uploaded_by' ) ).order_by('-upload_count') email_name_map = grab_names_from_emails( [row['uploaded_by'] for row in authors] ) for author in authors: for emailKey in email_name_map: if author['uploaded_by'] == emailKey: author['name'] = email_name_map[emailKey] return [ { 'slug': author['uploaded_by'], 'name': author['name'], 'count': author['upload_count'] } for author in authors ]
[ "def", "generate_sections", "(", "self", ")", ":", "authors", "=", "Dataset", ".", "objects", ".", "values", "(", "'uploaded_by'", ")", ".", "annotate", "(", "upload_count", "=", "Count", "(", "'uploaded_by'", ")", ")", ".", "order_by", "(", "'-upload_count'", ")", "email_name_map", "=", "grab_names_from_emails", "(", "[", "row", "[", "'uploaded_by'", "]", "for", "row", "in", "authors", "]", ")", "for", "author", "in", "authors", ":", "for", "emailKey", "in", "email_name_map", ":", "if", "author", "[", "'uploaded_by'", "]", "==", "emailKey", ":", "author", "[", "'name'", "]", "=", "email_name_map", "[", "emailKey", "]", "return", "[", "{", "'slug'", ":", "author", "[", "'uploaded_by'", "]", ",", "'name'", ":", "author", "[", "'name'", "]", ",", "'count'", ":", "author", "[", "'upload_count'", "]", "}", "for", "author", "in", "authors", "]" ]
Return all authors to which datasets have been attributed.
[ "Return", "all", "authors", "to", "which", "datasets", "have", "been", "attributed", "." ]
982dcf2015c80a280f1a093e32977cb71d4ea7aa
https://github.com/DallasMorningNews/django-datafreezer/blob/982dcf2015c80a280f1a093e32977cb71d4ea7aa/datafreezer/views.py#L813-L840
241,445
DallasMorningNews/django-datafreezer
datafreezer/views.py
BrowseSources.generate_sections
def generate_sections(self): """Return dictionary of source section slugs, name, and counts.""" sources = Dataset.objects.values( 'source', 'source_slug' ).annotate(source_count=Count('source_slug')) return sorted([ { 'slug': source['source_slug'], 'name': source['source'], 'count': source['source_count'] } for source in sources ], key=lambda k: k['count'], reverse=True)
python
def generate_sections(self): """Return dictionary of source section slugs, name, and counts.""" sources = Dataset.objects.values( 'source', 'source_slug' ).annotate(source_count=Count('source_slug')) return sorted([ { 'slug': source['source_slug'], 'name': source['source'], 'count': source['source_count'] } for source in sources ], key=lambda k: k['count'], reverse=True)
[ "def", "generate_sections", "(", "self", ")", ":", "sources", "=", "Dataset", ".", "objects", ".", "values", "(", "'source'", ",", "'source_slug'", ")", ".", "annotate", "(", "source_count", "=", "Count", "(", "'source_slug'", ")", ")", "return", "sorted", "(", "[", "{", "'slug'", ":", "source", "[", "'source_slug'", "]", ",", "'name'", ":", "source", "[", "'source'", "]", ",", "'count'", ":", "source", "[", "'source_count'", "]", "}", "for", "source", "in", "sources", "]", ",", "key", "=", "lambda", "k", ":", "k", "[", "'count'", "]", ",", "reverse", "=", "True", ")" ]
Return dictionary of source section slugs, name, and counts.
[ "Return", "dictionary", "of", "source", "section", "slugs", "name", "and", "counts", "." ]
982dcf2015c80a280f1a093e32977cb71d4ea7aa
https://github.com/DallasMorningNews/django-datafreezer/blob/982dcf2015c80a280f1a093e32977cb71d4ea7aa/datafreezer/views.py#L920-L933
241,446
DallasMorningNews/django-datafreezer
datafreezer/views.py
DetailBase.get
def get(self, request, slug): """Basic functionality for GET request to view. """ matching_datasets = self.generate_matching_datasets(slug) if matching_datasets is None: raise Http404("Datasets meeting these criteria do not exist.") base_context = { 'datasets': matching_datasets, 'num_datasets': matching_datasets.count(), 'page_title': self.generate_page_title(slug), } additional_context = self.generate_additional_context( matching_datasets ) base_context.update(additional_context) context = base_context return render( request, self.template_path, context )
python
def get(self, request, slug): """Basic functionality for GET request to view. """ matching_datasets = self.generate_matching_datasets(slug) if matching_datasets is None: raise Http404("Datasets meeting these criteria do not exist.") base_context = { 'datasets': matching_datasets, 'num_datasets': matching_datasets.count(), 'page_title': self.generate_page_title(slug), } additional_context = self.generate_additional_context( matching_datasets ) base_context.update(additional_context) context = base_context return render( request, self.template_path, context )
[ "def", "get", "(", "self", ",", "request", ",", "slug", ")", ":", "matching_datasets", "=", "self", ".", "generate_matching_datasets", "(", "slug", ")", "if", "matching_datasets", "is", "None", ":", "raise", "Http404", "(", "\"Datasets meeting these criteria do not exist.\"", ")", "base_context", "=", "{", "'datasets'", ":", "matching_datasets", ",", "'num_datasets'", ":", "matching_datasets", ".", "count", "(", ")", ",", "'page_title'", ":", "self", ".", "generate_page_title", "(", "slug", ")", ",", "}", "additional_context", "=", "self", ".", "generate_additional_context", "(", "matching_datasets", ")", "base_context", ".", "update", "(", "additional_context", ")", "context", "=", "base_context", "return", "render", "(", "request", ",", "self", ".", "template_path", ",", "context", ")" ]
Basic functionality for GET request to view.
[ "Basic", "functionality", "for", "GET", "request", "to", "view", "." ]
982dcf2015c80a280f1a093e32977cb71d4ea7aa
https://github.com/DallasMorningNews/django-datafreezer/blob/982dcf2015c80a280f1a093e32977cb71d4ea7aa/datafreezer/views.py#L962-L988
241,447
DallasMorningNews/django-datafreezer
datafreezer/views.py
AuthorDetail.generate_additional_context
def generate_additional_context(self, matching_datasets): """Return additional information about matching datasets. Includes upload counts, related hubs, related tags. """ dataset_ids = [upload.id for upload in matching_datasets] tags = Tag.objects.filter( dataset__in=dataset_ids ).distinct().annotate( Count('word') ).order_by('-word__count')[:5] hubs = matching_datasets.values("hub_slug").annotate( Count('hub_slug') ).order_by('-hub_slug__count') if hubs: most_used_hub = get_hub_name_from_slug(hubs[0]['hub_slug']) hub_slug = hubs[0]['hub_slug'] else: most_used_hub = None hub_slug = None return { 'tags': tags, 'hub': most_used_hub, 'hub_slug': hub_slug, }
python
def generate_additional_context(self, matching_datasets): """Return additional information about matching datasets. Includes upload counts, related hubs, related tags. """ dataset_ids = [upload.id for upload in matching_datasets] tags = Tag.objects.filter( dataset__in=dataset_ids ).distinct().annotate( Count('word') ).order_by('-word__count')[:5] hubs = matching_datasets.values("hub_slug").annotate( Count('hub_slug') ).order_by('-hub_slug__count') if hubs: most_used_hub = get_hub_name_from_slug(hubs[0]['hub_slug']) hub_slug = hubs[0]['hub_slug'] else: most_used_hub = None hub_slug = None return { 'tags': tags, 'hub': most_used_hub, 'hub_slug': hub_slug, }
[ "def", "generate_additional_context", "(", "self", ",", "matching_datasets", ")", ":", "dataset_ids", "=", "[", "upload", ".", "id", "for", "upload", "in", "matching_datasets", "]", "tags", "=", "Tag", ".", "objects", ".", "filter", "(", "dataset__in", "=", "dataset_ids", ")", ".", "distinct", "(", ")", ".", "annotate", "(", "Count", "(", "'word'", ")", ")", ".", "order_by", "(", "'-word__count'", ")", "[", ":", "5", "]", "hubs", "=", "matching_datasets", ".", "values", "(", "\"hub_slug\"", ")", ".", "annotate", "(", "Count", "(", "'hub_slug'", ")", ")", ".", "order_by", "(", "'-hub_slug__count'", ")", "if", "hubs", ":", "most_used_hub", "=", "get_hub_name_from_slug", "(", "hubs", "[", "0", "]", "[", "'hub_slug'", "]", ")", "hub_slug", "=", "hubs", "[", "0", "]", "[", "'hub_slug'", "]", "else", ":", "most_used_hub", "=", "None", "hub_slug", "=", "None", "return", "{", "'tags'", ":", "tags", ",", "'hub'", ":", "most_used_hub", ",", "'hub_slug'", ":", "hub_slug", ",", "}" ]
Return additional information about matching datasets. Includes upload counts, related hubs, related tags.
[ "Return", "additional", "information", "about", "matching", "datasets", "." ]
982dcf2015c80a280f1a093e32977cb71d4ea7aa
https://github.com/DallasMorningNews/django-datafreezer/blob/982dcf2015c80a280f1a093e32977cb71d4ea7aa/datafreezer/views.py#L1012-L1039
241,448
DallasMorningNews/django-datafreezer
datafreezer/views.py
TagDetail.generate_additional_context
def generate_additional_context(self, matching_datasets): """Return context about matching datasets.""" related_tags = Tag.objects.filter( dataset__in=matching_datasets ).distinct().annotate( Count('word') ).order_by('-word__count')[:5] return { 'related_tags': related_tags }
python
def generate_additional_context(self, matching_datasets): """Return context about matching datasets.""" related_tags = Tag.objects.filter( dataset__in=matching_datasets ).distinct().annotate( Count('word') ).order_by('-word__count')[:5] return { 'related_tags': related_tags }
[ "def", "generate_additional_context", "(", "self", ",", "matching_datasets", ")", ":", "related_tags", "=", "Tag", ".", "objects", ".", "filter", "(", "dataset__in", "=", "matching_datasets", ")", ".", "distinct", "(", ")", ".", "annotate", "(", "Count", "(", "'word'", ")", ")", ".", "order_by", "(", "'-word__count'", ")", "[", ":", "5", "]", "return", "{", "'related_tags'", ":", "related_tags", "}" ]
Return context about matching datasets.
[ "Return", "context", "about", "matching", "datasets", "." ]
982dcf2015c80a280f1a093e32977cb71d4ea7aa
https://github.com/DallasMorningNews/django-datafreezer/blob/982dcf2015c80a280f1a093e32977cb71d4ea7aa/datafreezer/views.py#L1062-L1072
241,449
DallasMorningNews/django-datafreezer
datafreezer/views.py
VerticalDetail.generate_matching_datasets
def generate_matching_datasets(self, data_slug): """Return datasets that belong to a vertical by querying hubs. """ matching_hubs = VERTICAL_HUB_MAP[data_slug]['hubs'] return Dataset.objects.filter(hub_slug__in=matching_hubs)
python
def generate_matching_datasets(self, data_slug): """Return datasets that belong to a vertical by querying hubs. """ matching_hubs = VERTICAL_HUB_MAP[data_slug]['hubs'] return Dataset.objects.filter(hub_slug__in=matching_hubs)
[ "def", "generate_matching_datasets", "(", "self", ",", "data_slug", ")", ":", "matching_hubs", "=", "VERTICAL_HUB_MAP", "[", "data_slug", "]", "[", "'hubs'", "]", "return", "Dataset", ".", "objects", ".", "filter", "(", "hub_slug__in", "=", "matching_hubs", ")" ]
Return datasets that belong to a vertical by querying hubs.
[ "Return", "datasets", "that", "belong", "to", "a", "vertical", "by", "querying", "hubs", "." ]
982dcf2015c80a280f1a093e32977cb71d4ea7aa
https://github.com/DallasMorningNews/django-datafreezer/blob/982dcf2015c80a280f1a093e32977cb71d4ea7aa/datafreezer/views.py#L1138-L1143
241,450
DallasMorningNews/django-datafreezer
datafreezer/views.py
VerticalDetail.generate_additional_context
def generate_additional_context(self, matching_datasets): """Generate top tags and authors for a given Vertical.""" top_tags = Tag.objects.filter( dataset__in=matching_datasets ).annotate( tag_count=Count('word') ).order_by('-tag_count')[:3] top_authors = Dataset.objects.filter( id__in=matching_datasets ).values('uploaded_by').annotate( author_count=Count('uploaded_by') ).order_by('-author_count')[:3] for author in top_authors: author['fullName'] = grab_names_from_emails([ author['uploaded_by'] ])[author['uploaded_by']] return { 'top_tags': top_tags, 'top_authors': top_authors }
python
def generate_additional_context(self, matching_datasets): """Generate top tags and authors for a given Vertical.""" top_tags = Tag.objects.filter( dataset__in=matching_datasets ).annotate( tag_count=Count('word') ).order_by('-tag_count')[:3] top_authors = Dataset.objects.filter( id__in=matching_datasets ).values('uploaded_by').annotate( author_count=Count('uploaded_by') ).order_by('-author_count')[:3] for author in top_authors: author['fullName'] = grab_names_from_emails([ author['uploaded_by'] ])[author['uploaded_by']] return { 'top_tags': top_tags, 'top_authors': top_authors }
[ "def", "generate_additional_context", "(", "self", ",", "matching_datasets", ")", ":", "top_tags", "=", "Tag", ".", "objects", ".", "filter", "(", "dataset__in", "=", "matching_datasets", ")", ".", "annotate", "(", "tag_count", "=", "Count", "(", "'word'", ")", ")", ".", "order_by", "(", "'-tag_count'", ")", "[", ":", "3", "]", "top_authors", "=", "Dataset", ".", "objects", ".", "filter", "(", "id__in", "=", "matching_datasets", ")", ".", "values", "(", "'uploaded_by'", ")", ".", "annotate", "(", "author_count", "=", "Count", "(", "'uploaded_by'", ")", ")", ".", "order_by", "(", "'-author_count'", ")", "[", ":", "3", "]", "for", "author", "in", "top_authors", ":", "author", "[", "'fullName'", "]", "=", "grab_names_from_emails", "(", "[", "author", "[", "'uploaded_by'", "]", "]", ")", "[", "author", "[", "'uploaded_by'", "]", "]", "return", "{", "'top_tags'", ":", "top_tags", ",", "'top_authors'", ":", "top_authors", "}" ]
Generate top tags and authors for a given Vertical.
[ "Generate", "top", "tags", "and", "authors", "for", "a", "given", "Vertical", "." ]
982dcf2015c80a280f1a093e32977cb71d4ea7aa
https://github.com/DallasMorningNews/django-datafreezer/blob/982dcf2015c80a280f1a093e32977cb71d4ea7aa/datafreezer/views.py#L1145-L1167
241,451
DallasMorningNews/django-datafreezer
datafreezer/views.py
SourceDetail.generate_additional_context
def generate_additional_context(self, matching_datasets): """Return top tags for a source.""" top_tags = Tag.objects.filter( dataset__in=matching_datasets ).annotate( tag_count=Count('word') ).order_by('-tag_count')[:3] return { 'top_tags': top_tags }
python
def generate_additional_context(self, matching_datasets): """Return top tags for a source.""" top_tags = Tag.objects.filter( dataset__in=matching_datasets ).annotate( tag_count=Count('word') ).order_by('-tag_count')[:3] return { 'top_tags': top_tags }
[ "def", "generate_additional_context", "(", "self", ",", "matching_datasets", ")", ":", "top_tags", "=", "Tag", ".", "objects", ".", "filter", "(", "dataset__in", "=", "matching_datasets", ")", ".", "annotate", "(", "tag_count", "=", "Count", "(", "'word'", ")", ")", ".", "order_by", "(", "'-tag_count'", ")", "[", ":", "3", "]", "return", "{", "'top_tags'", ":", "top_tags", "}" ]
Return top tags for a source.
[ "Return", "top", "tags", "for", "a", "source", "." ]
982dcf2015c80a280f1a093e32977cb71d4ea7aa
https://github.com/DallasMorningNews/django-datafreezer/blob/982dcf2015c80a280f1a093e32977cb71d4ea7aa/datafreezer/views.py#L1186-L1196
241,452
pablorecio/Cobaya
src/cobaya/hamster_db.py
HamsterDB.get_fact_by_id
def get_fact_by_id(self, fact_id): """ Obtains fact data by it's id. As the fact is unique, it returns a tuple like: (activity_id, start_time, end_time, description). If there is no fact with id == fact_id, a NoHamsterData exception will be raise """ columns = 'activity_id, start_time, end_time, description' query = "SELECT %s FROM facts WHERE id = %s" result = self._query(query % (columns, fact_id)) if result: return result[0] # there only one fact with the id else: raise NoHamsterData('facts', fact_id)
python
def get_fact_by_id(self, fact_id): """ Obtains fact data by it's id. As the fact is unique, it returns a tuple like: (activity_id, start_time, end_time, description). If there is no fact with id == fact_id, a NoHamsterData exception will be raise """ columns = 'activity_id, start_time, end_time, description' query = "SELECT %s FROM facts WHERE id = %s" result = self._query(query % (columns, fact_id)) if result: return result[0] # there only one fact with the id else: raise NoHamsterData('facts', fact_id)
[ "def", "get_fact_by_id", "(", "self", ",", "fact_id", ")", ":", "columns", "=", "'activity_id, start_time, end_time, description'", "query", "=", "\"SELECT %s FROM facts WHERE id = %s\"", "result", "=", "self", ".", "_query", "(", "query", "%", "(", "columns", ",", "fact_id", ")", ")", "if", "result", ":", "return", "result", "[", "0", "]", "# there only one fact with the id", "else", ":", "raise", "NoHamsterData", "(", "'facts'", ",", "fact_id", ")" ]
Obtains fact data by it's id. As the fact is unique, it returns a tuple like: (activity_id, start_time, end_time, description). If there is no fact with id == fact_id, a NoHamsterData exception will be raise
[ "Obtains", "fact", "data", "by", "it", "s", "id", "." ]
70b107dea5f31f51e7b6738da3c2a1df5b9f3f20
https://github.com/pablorecio/Cobaya/blob/70b107dea5f31f51e7b6738da3c2a1df5b9f3f20/src/cobaya/hamster_db.py#L55-L72
241,453
pablorecio/Cobaya
src/cobaya/hamster_db.py
HamsterDB.get_activity_by_id
def get_activity_by_id(self, activity_id): """ Obtains activity data by it's id. As the activity is unique, it returns a tuple like: (name, category_id). If there is no activity with id == activity_id, a NoHamsterData exception will be raise """ columns = 'name, category_id' query = "SELECT %s FROM activities WHERE id = %s" result = self._query(query % (columns, activity_id)) if result: return result[0] # there only one fact with the id else: raise NoHamsterData('activities', activity_id)
python
def get_activity_by_id(self, activity_id): """ Obtains activity data by it's id. As the activity is unique, it returns a tuple like: (name, category_id). If there is no activity with id == activity_id, a NoHamsterData exception will be raise """ columns = 'name, category_id' query = "SELECT %s FROM activities WHERE id = %s" result = self._query(query % (columns, activity_id)) if result: return result[0] # there only one fact with the id else: raise NoHamsterData('activities', activity_id)
[ "def", "get_activity_by_id", "(", "self", ",", "activity_id", ")", ":", "columns", "=", "'name, category_id'", "query", "=", "\"SELECT %s FROM activities WHERE id = %s\"", "result", "=", "self", ".", "_query", "(", "query", "%", "(", "columns", ",", "activity_id", ")", ")", "if", "result", ":", "return", "result", "[", "0", "]", "# there only one fact with the id", "else", ":", "raise", "NoHamsterData", "(", "'activities'", ",", "activity_id", ")" ]
Obtains activity data by it's id. As the activity is unique, it returns a tuple like: (name, category_id). If there is no activity with id == activity_id, a NoHamsterData exception will be raise
[ "Obtains", "activity", "data", "by", "it", "s", "id", "." ]
70b107dea5f31f51e7b6738da3c2a1df5b9f3f20
https://github.com/pablorecio/Cobaya/blob/70b107dea5f31f51e7b6738da3c2a1df5b9f3f20/src/cobaya/hamster_db.py#L74-L90
241,454
pablorecio/Cobaya
src/cobaya/hamster_db.py
HamsterDB.get_tags_by_fact_id
def get_tags_by_fact_id(self, fact_id): """ Obtains the tags associated by a fact_id. This function returns a list of the tags name associated to a fact, such as ['foo', 'bar', 'eggs']. If the fact has no tags, it will return a empty list. If there are no fact with id == fact_id, a NoHamsterData exception will be raise """ if not fact_id in self.all_facts_id: raise NoHamsterData('facts', fact_id) query = "SELECT tag_id FROM fact_tags WHERE fact_id = %s" return [self.tags[row[0]] for row in self._query(query % fact_id)]
python
def get_tags_by_fact_id(self, fact_id): """ Obtains the tags associated by a fact_id. This function returns a list of the tags name associated to a fact, such as ['foo', 'bar', 'eggs']. If the fact has no tags, it will return a empty list. If there are no fact with id == fact_id, a NoHamsterData exception will be raise """ if not fact_id in self.all_facts_id: raise NoHamsterData('facts', fact_id) query = "SELECT tag_id FROM fact_tags WHERE fact_id = %s" return [self.tags[row[0]] for row in self._query(query % fact_id)]
[ "def", "get_tags_by_fact_id", "(", "self", ",", "fact_id", ")", ":", "if", "not", "fact_id", "in", "self", ".", "all_facts_id", ":", "raise", "NoHamsterData", "(", "'facts'", ",", "fact_id", ")", "query", "=", "\"SELECT tag_id FROM fact_tags WHERE fact_id = %s\"", "return", "[", "self", ".", "tags", "[", "row", "[", "0", "]", "]", "for", "row", "in", "self", ".", "_query", "(", "query", "%", "fact_id", ")", "]" ]
Obtains the tags associated by a fact_id. This function returns a list of the tags name associated to a fact, such as ['foo', 'bar', 'eggs']. If the fact has no tags, it will return a empty list. If there are no fact with id == fact_id, a NoHamsterData exception will be raise
[ "Obtains", "the", "tags", "associated", "by", "a", "fact_id", "." ]
70b107dea5f31f51e7b6738da3c2a1df5b9f3f20
https://github.com/pablorecio/Cobaya/blob/70b107dea5f31f51e7b6738da3c2a1df5b9f3f20/src/cobaya/hamster_db.py#L92-L105
241,455
renzon/pswdclient
src/pswdclient/facade.py
log_user_in
def log_user_in(app_id, token, ticket, response, cookie_name='user', url_detail='https://pswdless.appspot.com/rest/detail'): ''' Log the user in setting the user data dictionary in cookie Returns a command that execute the logic ''' return LogUserIn(app_id, token, ticket, response, cookie_name, url_detail)
python
def log_user_in(app_id, token, ticket, response, cookie_name='user', url_detail='https://pswdless.appspot.com/rest/detail'): ''' Log the user in setting the user data dictionary in cookie Returns a command that execute the logic ''' return LogUserIn(app_id, token, ticket, response, cookie_name, url_detail)
[ "def", "log_user_in", "(", "app_id", ",", "token", ",", "ticket", ",", "response", ",", "cookie_name", "=", "'user'", ",", "url_detail", "=", "'https://pswdless.appspot.com/rest/detail'", ")", ":", "return", "LogUserIn", "(", "app_id", ",", "token", ",", "ticket", ",", "response", ",", "cookie_name", ",", "url_detail", ")" ]
Log the user in setting the user data dictionary in cookie Returns a command that execute the logic
[ "Log", "the", "user", "in", "setting", "the", "user", "data", "dictionary", "in", "cookie", "Returns", "a", "command", "that", "execute", "the", "logic" ]
1036b9a26da876c936e5b397046440b1b98aedbb
https://github.com/renzon/pswdclient/blob/1036b9a26da876c936e5b397046440b1b98aedbb/src/pswdclient/facade.py#L30-L36
241,456
renzon/pswdclient
src/pswdclient/facade.py
fetch_user
def fetch_user(app_id, token, ticket, url_detail='https://pswdless.appspot.com/rest/detail'): ''' Fetch the user deatil from Passwordless ''' return FetchUserWithValidation(app_id, token, ticket, url_detail)
python
def fetch_user(app_id, token, ticket, url_detail='https://pswdless.appspot.com/rest/detail'): ''' Fetch the user deatil from Passwordless ''' return FetchUserWithValidation(app_id, token, ticket, url_detail)
[ "def", "fetch_user", "(", "app_id", ",", "token", ",", "ticket", ",", "url_detail", "=", "'https://pswdless.appspot.com/rest/detail'", ")", ":", "return", "FetchUserWithValidation", "(", "app_id", ",", "token", ",", "ticket", ",", "url_detail", ")" ]
Fetch the user deatil from Passwordless
[ "Fetch", "the", "user", "deatil", "from", "Passwordless" ]
1036b9a26da876c936e5b397046440b1b98aedbb
https://github.com/renzon/pswdclient/blob/1036b9a26da876c936e5b397046440b1b98aedbb/src/pswdclient/facade.py#L39-L43
241,457
renzon/pswdclient
src/pswdclient/facade.py
send_login_email
def send_login_email(app_id, token, hook, email=None, user_id=None, lang="en_US", url_login='https://pswdless.appspot.com/rest/login'): ''' Contact password-less server to send user a email containing the login link ''' return SendLoginEmail(app_id, token, hook, email, user_id, lang, url_login)
python
def send_login_email(app_id, token, hook, email=None, user_id=None, lang="en_US", url_login='https://pswdless.appspot.com/rest/login'): ''' Contact password-less server to send user a email containing the login link ''' return SendLoginEmail(app_id, token, hook, email, user_id, lang, url_login)
[ "def", "send_login_email", "(", "app_id", ",", "token", ",", "hook", ",", "email", "=", "None", ",", "user_id", "=", "None", ",", "lang", "=", "\"en_US\"", ",", "url_login", "=", "'https://pswdless.appspot.com/rest/login'", ")", ":", "return", "SendLoginEmail", "(", "app_id", ",", "token", ",", "hook", ",", "email", ",", "user_id", ",", "lang", ",", "url_login", ")" ]
Contact password-less server to send user a email containing the login link
[ "Contact", "password", "-", "less", "server", "to", "send", "user", "a", "email", "containing", "the", "login", "link" ]
1036b9a26da876c936e5b397046440b1b98aedbb
https://github.com/renzon/pswdclient/blob/1036b9a26da876c936e5b397046440b1b98aedbb/src/pswdclient/facade.py#L46-L51
241,458
jlesquembre/jlle
jlle/releaser/vcs.py
BaseVersionControl.history_file
def history_file(self, location=None): """Return history file location. """ if location: # Hardcoded location passed from the config file. if os.path.exists(location): return location else: logger.warn("The specified history file %s doesn't exist", location) filenames = [] for base in ['CHANGES', 'HISTORY', 'CHANGELOG']: filenames.append(base) for extension in ['rst', 'txt', 'markdown']: filenames.append('.'.join([base, extension])) history = self.filefind(filenames) if history: return history
python
def history_file(self, location=None): """Return history file location. """ if location: # Hardcoded location passed from the config file. if os.path.exists(location): return location else: logger.warn("The specified history file %s doesn't exist", location) filenames = [] for base in ['CHANGES', 'HISTORY', 'CHANGELOG']: filenames.append(base) for extension in ['rst', 'txt', 'markdown']: filenames.append('.'.join([base, extension])) history = self.filefind(filenames) if history: return history
[ "def", "history_file", "(", "self", ",", "location", "=", "None", ")", ":", "if", "location", ":", "# Hardcoded location passed from the config file.", "if", "os", ".", "path", ".", "exists", "(", "location", ")", ":", "return", "location", "else", ":", "logger", ".", "warn", "(", "\"The specified history file %s doesn't exist\"", ",", "location", ")", "filenames", "=", "[", "]", "for", "base", "in", "[", "'CHANGES'", ",", "'HISTORY'", ",", "'CHANGELOG'", "]", ":", "filenames", ".", "append", "(", "base", ")", "for", "extension", "in", "[", "'rst'", ",", "'txt'", ",", "'markdown'", "]", ":", "filenames", ".", "append", "(", "'.'", ".", "join", "(", "[", "base", ",", "extension", "]", ")", ")", "history", "=", "self", ".", "filefind", "(", "filenames", ")", "if", "history", ":", "return", "history" ]
Return history file location.
[ "Return", "history", "file", "location", "." ]
3645d8f203708355853ef911f4b887ae4d794826
https://github.com/jlesquembre/jlle/blob/3645d8f203708355853ef911f4b887ae4d794826/jlle/releaser/vcs.py#L121-L138
241,459
jlesquembre/jlle
jlle/releaser/vcs.py
BaseVersionControl.tag_exists
def tag_exists(self, version): """Check if a tag has already been created with the name of the version. """ for tag in self.available_tags(): if tag == version: return True return False
python
def tag_exists(self, version): """Check if a tag has already been created with the name of the version. """ for tag in self.available_tags(): if tag == version: return True return False
[ "def", "tag_exists", "(", "self", ",", "version", ")", ":", "for", "tag", "in", "self", ".", "available_tags", "(", ")", ":", "if", "tag", "==", "version", ":", "return", "True", "return", "False" ]
Check if a tag has already been created with the name of the version.
[ "Check", "if", "a", "tag", "has", "already", "been", "created", "with", "the", "name", "of", "the", "version", "." ]
3645d8f203708355853ef911f4b887ae4d794826
https://github.com/jlesquembre/jlle/blob/3645d8f203708355853ef911f4b887ae4d794826/jlle/releaser/vcs.py#L140-L147
241,460
jlesquembre/jlle
jlle/releaser/vcs.py
BaseVersionControl._update_version
def _update_version(self, version): """Find out where to change the version and change it. There are three places where the version can be defined. The first one is an explicitly defined Python file with a ``__version__`` attribute. The second one is some version.txt that gets read by setup.py. The third is directly in setup.py. """ if self.get_python_file_version(): setup_cfg = pypi.SetupConfig() filename = setup_cfg.python_file_with_version() lines = open(filename).read().split('\n') for index, line in enumerate(lines): match = UNDERSCORED_VERSION_PATTERN.search(line) if match: lines[index] = "__version__ = '%s'" % version contents = '\n'.join(lines) open(filename, 'w').write(contents) logger.info("Set __version__ in %s to %r", filename, version) return versionfile = self.filefind(['version.txt', 'version']) if versionfile: # We have a version.txt file but does it match the setup.py # version (if any)? setup_version = self.get_setup_py_version() if not setup_version or (setup_version == self.get_version_txt_version()): open(versionfile, 'w').write(version + '\n') logger.info("Changed %s to %r", versionfile, version) return good_version = "version = '%s'" % version line_number = 0 setup_lines = open('setup.py').read().split('\n') for line in setup_lines: match = VERSION_PATTERN.search(line) if match: logger.debug("Matching version line found: %r", line) if line.startswith(' '): # oh, probably ' version = 1.0,' line. indentation = line.split('version')[0] # Note: no spaces around the '='. good_version = indentation + "version='%s'," % version setup_lines[line_number] = good_version break line_number += 1 contents = '\n'.join(setup_lines) open('setup.py', 'w').write(contents) logger.info("Set setup.py's version to %r", version)
python
def _update_version(self, version): """Find out where to change the version and change it. There are three places where the version can be defined. The first one is an explicitly defined Python file with a ``__version__`` attribute. The second one is some version.txt that gets read by setup.py. The third is directly in setup.py. """ if self.get_python_file_version(): setup_cfg = pypi.SetupConfig() filename = setup_cfg.python_file_with_version() lines = open(filename).read().split('\n') for index, line in enumerate(lines): match = UNDERSCORED_VERSION_PATTERN.search(line) if match: lines[index] = "__version__ = '%s'" % version contents = '\n'.join(lines) open(filename, 'w').write(contents) logger.info("Set __version__ in %s to %r", filename, version) return versionfile = self.filefind(['version.txt', 'version']) if versionfile: # We have a version.txt file but does it match the setup.py # version (if any)? setup_version = self.get_setup_py_version() if not setup_version or (setup_version == self.get_version_txt_version()): open(versionfile, 'w').write(version + '\n') logger.info("Changed %s to %r", versionfile, version) return good_version = "version = '%s'" % version line_number = 0 setup_lines = open('setup.py').read().split('\n') for line in setup_lines: match = VERSION_PATTERN.search(line) if match: logger.debug("Matching version line found: %r", line) if line.startswith(' '): # oh, probably ' version = 1.0,' line. indentation = line.split('version')[0] # Note: no spaces around the '='. good_version = indentation + "version='%s'," % version setup_lines[line_number] = good_version break line_number += 1 contents = '\n'.join(setup_lines) open('setup.py', 'w').write(contents) logger.info("Set setup.py's version to %r", version)
[ "def", "_update_version", "(", "self", ",", "version", ")", ":", "if", "self", ".", "get_python_file_version", "(", ")", ":", "setup_cfg", "=", "pypi", ".", "SetupConfig", "(", ")", "filename", "=", "setup_cfg", ".", "python_file_with_version", "(", ")", "lines", "=", "open", "(", "filename", ")", ".", "read", "(", ")", ".", "split", "(", "'\\n'", ")", "for", "index", ",", "line", "in", "enumerate", "(", "lines", ")", ":", "match", "=", "UNDERSCORED_VERSION_PATTERN", ".", "search", "(", "line", ")", "if", "match", ":", "lines", "[", "index", "]", "=", "\"__version__ = '%s'\"", "%", "version", "contents", "=", "'\\n'", ".", "join", "(", "lines", ")", "open", "(", "filename", ",", "'w'", ")", ".", "write", "(", "contents", ")", "logger", ".", "info", "(", "\"Set __version__ in %s to %r\"", ",", "filename", ",", "version", ")", "return", "versionfile", "=", "self", ".", "filefind", "(", "[", "'version.txt'", ",", "'version'", "]", ")", "if", "versionfile", ":", "# We have a version.txt file but does it match the setup.py", "# version (if any)?", "setup_version", "=", "self", ".", "get_setup_py_version", "(", ")", "if", "not", "setup_version", "or", "(", "setup_version", "==", "self", ".", "get_version_txt_version", "(", ")", ")", ":", "open", "(", "versionfile", ",", "'w'", ")", ".", "write", "(", "version", "+", "'\\n'", ")", "logger", ".", "info", "(", "\"Changed %s to %r\"", ",", "versionfile", ",", "version", ")", "return", "good_version", "=", "\"version = '%s'\"", "%", "version", "line_number", "=", "0", "setup_lines", "=", "open", "(", "'setup.py'", ")", ".", "read", "(", ")", ".", "split", "(", "'\\n'", ")", "for", "line", "in", "setup_lines", ":", "match", "=", "VERSION_PATTERN", ".", "search", "(", "line", ")", "if", "match", ":", "logger", ".", "debug", "(", "\"Matching version line found: %r\"", ",", "line", ")", "if", "line", ".", "startswith", "(", "' '", ")", ":", "# oh, probably ' version = 1.0,' line.", "indentation", "=", "line", ".", "split", "(", "'version'", ")", "[", "0", "]", "# Note: no spaces around the '='.", "good_version", "=", "indentation", "+", "\"version='%s',\"", "%", "version", "setup_lines", "[", "line_number", "]", "=", "good_version", "break", "line_number", "+=", "1", "contents", "=", "'\\n'", ".", "join", "(", "setup_lines", ")", "open", "(", "'setup.py'", ",", "'w'", ")", ".", "write", "(", "contents", ")", "logger", ".", "info", "(", "\"Set setup.py's version to %r\"", ",", "version", ")" ]
Find out where to change the version and change it. There are three places where the version can be defined. The first one is an explicitly defined Python file with a ``__version__`` attribute. The second one is some version.txt that gets read by setup.py. The third is directly in setup.py.
[ "Find", "out", "where", "to", "change", "the", "version", "and", "change", "it", "." ]
3645d8f203708355853ef911f4b887ae4d794826
https://github.com/jlesquembre/jlle/blob/3645d8f203708355853ef911f4b887ae4d794826/jlle/releaser/vcs.py#L167-L216
241,461
honzamach/pydgets
pydgets/widgets.py
terminal_size
def terminal_size(): """ Detect the current size of terminal window as a numer of rows and columns. """ try: (rows, columns) = os.popen('stty size', 'r').read().split() rows = int(rows) columns = int(columns) return (columns, rows) # Currently ignore any errors and return some reasonable default values. # Errors may occur, when the library is used in non-terminal application # like daemon. except: pass return (80, 24)
python
def terminal_size(): """ Detect the current size of terminal window as a numer of rows and columns. """ try: (rows, columns) = os.popen('stty size', 'r').read().split() rows = int(rows) columns = int(columns) return (columns, rows) # Currently ignore any errors and return some reasonable default values. # Errors may occur, when the library is used in non-terminal application # like daemon. except: pass return (80, 24)
[ "def", "terminal_size", "(", ")", ":", "try", ":", "(", "rows", ",", "columns", ")", "=", "os", ".", "popen", "(", "'stty size'", ",", "'r'", ")", ".", "read", "(", ")", ".", "split", "(", ")", "rows", "=", "int", "(", "rows", ")", "columns", "=", "int", "(", "columns", ")", "return", "(", "columns", ",", "rows", ")", "# Currently ignore any errors and return some reasonable default values.", "# Errors may occur, when the library is used in non-terminal application", "# like daemon.", "except", ":", "pass", "return", "(", "80", ",", "24", ")" ]
Detect the current size of terminal window as a numer of rows and columns.
[ "Detect", "the", "current", "size", "of", "terminal", "window", "as", "a", "numer", "of", "rows", "and", "columns", "." ]
5ca4ce19fc2d9b5f41441fb9163810f8ca502e79
https://github.com/honzamach/pydgets/blob/5ca4ce19fc2d9b5f41441fb9163810f8ca502e79/pydgets/widgets.py#L291-L306
241,462
honzamach/pydgets
pydgets/widgets.py
ConsoleWidget.get_setup
def get_setup(self, content = None, **kwargs): """ Get current setup by combining internal settings with the ones given. """ if content is None: content = self.content if content is None: raise Exception("No content given to be displayed") setup = {} for setting in self.list_settings(): if setting[0] in kwargs: setup[setting[0]] = kwargs.get(setting[0]) else: setup[setting[0]] = self._settings.get(setting[0]) return (content, setup)
python
def get_setup(self, content = None, **kwargs): """ Get current setup by combining internal settings with the ones given. """ if content is None: content = self.content if content is None: raise Exception("No content given to be displayed") setup = {} for setting in self.list_settings(): if setting[0] in kwargs: setup[setting[0]] = kwargs.get(setting[0]) else: setup[setting[0]] = self._settings.get(setting[0]) return (content, setup)
[ "def", "get_setup", "(", "self", ",", "content", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "content", "is", "None", ":", "content", "=", "self", ".", "content", "if", "content", "is", "None", ":", "raise", "Exception", "(", "\"No content given to be displayed\"", ")", "setup", "=", "{", "}", "for", "setting", "in", "self", ".", "list_settings", "(", ")", ":", "if", "setting", "[", "0", "]", "in", "kwargs", ":", "setup", "[", "setting", "[", "0", "]", "]", "=", "kwargs", ".", "get", "(", "setting", "[", "0", "]", ")", "else", ":", "setup", "[", "setting", "[", "0", "]", "]", "=", "self", ".", "_settings", ".", "get", "(", "setting", "[", "0", "]", ")", "return", "(", "content", ",", "setup", ")" ]
Get current setup by combining internal settings with the ones given.
[ "Get", "current", "setup", "by", "combining", "internal", "settings", "with", "the", "ones", "given", "." ]
5ca4ce19fc2d9b5f41441fb9163810f8ca502e79
https://github.com/honzamach/pydgets/blob/5ca4ce19fc2d9b5f41441fb9163810f8ca502e79/pydgets/widgets.py#L404-L420
241,463
honzamach/pydgets
pydgets/widgets.py
ConsoleWidget._es_data
def _es_data(settings): """ Extract data formating related subset of widget settings. """ return {k: settings[k] for k in (ConsoleWidget.SETTING_DATA_FORMATING, ConsoleWidget.SETTING_DATA_TYPE)}
python
def _es_data(settings): """ Extract data formating related subset of widget settings. """ return {k: settings[k] for k in (ConsoleWidget.SETTING_DATA_FORMATING, ConsoleWidget.SETTING_DATA_TYPE)}
[ "def", "_es_data", "(", "settings", ")", ":", "return", "{", "k", ":", "settings", "[", "k", "]", "for", "k", "in", "(", "ConsoleWidget", ".", "SETTING_DATA_FORMATING", ",", "ConsoleWidget", ".", "SETTING_DATA_TYPE", ")", "}" ]
Extract data formating related subset of widget settings.
[ "Extract", "data", "formating", "related", "subset", "of", "widget", "settings", "." ]
5ca4ce19fc2d9b5f41441fb9163810f8ca502e79
https://github.com/honzamach/pydgets/blob/5ca4ce19fc2d9b5f41441fb9163810f8ca502e79/pydgets/widgets.py#L432-L437
241,464
honzamach/pydgets
pydgets/widgets.py
ConsoleWidget._es_content
def _es_content(settings): """ Extract content formating related subset of widget settings. """ return {k: settings[k] for k in (ConsoleWidget.SETTING_WIDTH, ConsoleWidget.SETTING_ALIGN, ConsoleWidget.SETTING_PADDING, ConsoleWidget.SETTING_PADDING_LEFT, ConsoleWidget.SETTING_PADDING_RIGHT, ConsoleWidget.SETTING_PADDING_CHAR)}
python
def _es_content(settings): """ Extract content formating related subset of widget settings. """ return {k: settings[k] for k in (ConsoleWidget.SETTING_WIDTH, ConsoleWidget.SETTING_ALIGN, ConsoleWidget.SETTING_PADDING, ConsoleWidget.SETTING_PADDING_LEFT, ConsoleWidget.SETTING_PADDING_RIGHT, ConsoleWidget.SETTING_PADDING_CHAR)}
[ "def", "_es_content", "(", "settings", ")", ":", "return", "{", "k", ":", "settings", "[", "k", "]", "for", "k", "in", "(", "ConsoleWidget", ".", "SETTING_WIDTH", ",", "ConsoleWidget", ".", "SETTING_ALIGN", ",", "ConsoleWidget", ".", "SETTING_PADDING", ",", "ConsoleWidget", ".", "SETTING_PADDING_LEFT", ",", "ConsoleWidget", ".", "SETTING_PADDING_RIGHT", ",", "ConsoleWidget", ".", "SETTING_PADDING_CHAR", ")", "}" ]
Extract content formating related subset of widget settings.
[ "Extract", "content", "formating", "related", "subset", "of", "widget", "settings", "." ]
5ca4ce19fc2d9b5f41441fb9163810f8ca502e79
https://github.com/honzamach/pydgets/blob/5ca4ce19fc2d9b5f41441fb9163810f8ca502e79/pydgets/widgets.py#L440-L449
241,465
honzamach/pydgets
pydgets/widgets.py
ConsoleWidget._es_text
def _es_text(settings, text_formating = {}): """ Extract text formating related subset of widget settings. """ s = {k: settings[k] for k in (ConsoleWidget.SETTING_FLAG_PLAIN,)} s.update(text_formating) return s
python
def _es_text(settings, text_formating = {}): """ Extract text formating related subset of widget settings. """ s = {k: settings[k] for k in (ConsoleWidget.SETTING_FLAG_PLAIN,)} s.update(text_formating) return s
[ "def", "_es_text", "(", "settings", ",", "text_formating", "=", "{", "}", ")", ":", "s", "=", "{", "k", ":", "settings", "[", "k", "]", "for", "k", "in", "(", "ConsoleWidget", ".", "SETTING_FLAG_PLAIN", ",", ")", "}", "s", ".", "update", "(", "text_formating", ")", "return", "s" ]
Extract text formating related subset of widget settings.
[ "Extract", "text", "formating", "related", "subset", "of", "widget", "settings", "." ]
5ca4ce19fc2d9b5f41441fb9163810f8ca502e79
https://github.com/honzamach/pydgets/blob/5ca4ce19fc2d9b5f41441fb9163810f8ca502e79/pydgets/widgets.py#L452-L458
241,466
honzamach/pydgets
pydgets/widgets.py
ConsoleWidget._es_margin
def _es_margin(settings): """ Extract margin formating related subset of widget settings. """ return {k: settings[k] for k in (ConsoleWidget.SETTING_MARGIN, ConsoleWidget.SETTING_MARGIN_LEFT, ConsoleWidget.SETTING_MARGIN_RIGHT, ConsoleWidget.SETTING_MARGIN_CHAR)}
python
def _es_margin(settings): """ Extract margin formating related subset of widget settings. """ return {k: settings[k] for k in (ConsoleWidget.SETTING_MARGIN, ConsoleWidget.SETTING_MARGIN_LEFT, ConsoleWidget.SETTING_MARGIN_RIGHT, ConsoleWidget.SETTING_MARGIN_CHAR)}
[ "def", "_es_margin", "(", "settings", ")", ":", "return", "{", "k", ":", "settings", "[", "k", "]", "for", "k", "in", "(", "ConsoleWidget", ".", "SETTING_MARGIN", ",", "ConsoleWidget", ".", "SETTING_MARGIN_LEFT", ",", "ConsoleWidget", ".", "SETTING_MARGIN_RIGHT", ",", "ConsoleWidget", ".", "SETTING_MARGIN_CHAR", ")", "}" ]
Extract margin formating related subset of widget settings.
[ "Extract", "margin", "formating", "related", "subset", "of", "widget", "settings", "." ]
5ca4ce19fc2d9b5f41441fb9163810f8ca502e79
https://github.com/honzamach/pydgets/blob/5ca4ce19fc2d9b5f41441fb9163810f8ca502e79/pydgets/widgets.py#L461-L468
241,467
honzamach/pydgets
pydgets/widgets.py
ConsoleWidget.calculate_width_widget
def calculate_width_widget(width, margin = None, margin_left = None, margin_right = None): """ Calculate actual widget width based on given margins. """ if margin_left is None: margin_left = margin if margin_right is None: margin_right = margin if margin_left is not None: width -= int(margin_left) if margin_right is not None: width -= int(margin_right) return width if width > 0 else None
python
def calculate_width_widget(width, margin = None, margin_left = None, margin_right = None): """ Calculate actual widget width based on given margins. """ if margin_left is None: margin_left = margin if margin_right is None: margin_right = margin if margin_left is not None: width -= int(margin_left) if margin_right is not None: width -= int(margin_right) return width if width > 0 else None
[ "def", "calculate_width_widget", "(", "width", ",", "margin", "=", "None", ",", "margin_left", "=", "None", ",", "margin_right", "=", "None", ")", ":", "if", "margin_left", "is", "None", ":", "margin_left", "=", "margin", "if", "margin_right", "is", "None", ":", "margin_right", "=", "margin", "if", "margin_left", "is", "not", "None", ":", "width", "-=", "int", "(", "margin_left", ")", "if", "margin_right", "is", "not", "None", ":", "width", "-=", "int", "(", "margin_right", ")", "return", "width", "if", "width", ">", "0", "else", "None" ]
Calculate actual widget width based on given margins.
[ "Calculate", "actual", "widget", "width", "based", "on", "given", "margins", "." ]
5ca4ce19fc2d9b5f41441fb9163810f8ca502e79
https://github.com/honzamach/pydgets/blob/5ca4ce19fc2d9b5f41441fb9163810f8ca502e79/pydgets/widgets.py#L473-L485
241,468
honzamach/pydgets
pydgets/widgets.py
ConsoleWidget.fmt_data
def fmt_data(text, data_formating = None, data_type = None): """ Format given text according to given data formating pattern or data type. """ if data_type: return DATA_TYPES[data_type](text) elif data_formating: return str(data_formating).format(text) return str(text)
python
def fmt_data(text, data_formating = None, data_type = None): """ Format given text according to given data formating pattern or data type. """ if data_type: return DATA_TYPES[data_type](text) elif data_formating: return str(data_formating).format(text) return str(text)
[ "def", "fmt_data", "(", "text", ",", "data_formating", "=", "None", ",", "data_type", "=", "None", ")", ":", "if", "data_type", ":", "return", "DATA_TYPES", "[", "data_type", "]", "(", "text", ")", "elif", "data_formating", ":", "return", "str", "(", "data_formating", ")", ".", "format", "(", "text", ")", "return", "str", "(", "text", ")" ]
Format given text according to given data formating pattern or data type.
[ "Format", "given", "text", "according", "to", "given", "data", "formating", "pattern", "or", "data", "type", "." ]
5ca4ce19fc2d9b5f41441fb9163810f8ca502e79
https://github.com/honzamach/pydgets/blob/5ca4ce19fc2d9b5f41441fb9163810f8ca502e79/pydgets/widgets.py#L511-L519
241,469
honzamach/pydgets
pydgets/widgets.py
ConsoleWidget.fmt_content
def fmt_content(text, width = 0, align = '<', padding = None, padding_left = None, padding_right = None, padding_char = ' '): """ Pad given text with given padding characters, inflate it to given width and perform horizontal aligning. """ if padding_left is None: padding_left = padding if padding_right is None: padding_right = padding if padding_left is not None: text = '{}{}'.format(str(padding_char)[0] * int(padding_left), text) if padding_right is not None: text = '{}{}'.format(text, str(padding_char)[0] * int(padding_right)) if width: strptrn = '{:' + ('{}{}{}'.format(str(padding_char)[0], str(TEXT_ALIGNMENT[align]), str(width))) + 's}' text = strptrn.format(text) return text
python
def fmt_content(text, width = 0, align = '<', padding = None, padding_left = None, padding_right = None, padding_char = ' '): """ Pad given text with given padding characters, inflate it to given width and perform horizontal aligning. """ if padding_left is None: padding_left = padding if padding_right is None: padding_right = padding if padding_left is not None: text = '{}{}'.format(str(padding_char)[0] * int(padding_left), text) if padding_right is not None: text = '{}{}'.format(text, str(padding_char)[0] * int(padding_right)) if width: strptrn = '{:' + ('{}{}{}'.format(str(padding_char)[0], str(TEXT_ALIGNMENT[align]), str(width))) + 's}' text = strptrn.format(text) return text
[ "def", "fmt_content", "(", "text", ",", "width", "=", "0", ",", "align", "=", "'<'", ",", "padding", "=", "None", ",", "padding_left", "=", "None", ",", "padding_right", "=", "None", ",", "padding_char", "=", "' '", ")", ":", "if", "padding_left", "is", "None", ":", "padding_left", "=", "padding", "if", "padding_right", "is", "None", ":", "padding_right", "=", "padding", "if", "padding_left", "is", "not", "None", ":", "text", "=", "'{}{}'", ".", "format", "(", "str", "(", "padding_char", ")", "[", "0", "]", "*", "int", "(", "padding_left", ")", ",", "text", ")", "if", "padding_right", "is", "not", "None", ":", "text", "=", "'{}{}'", ".", "format", "(", "text", ",", "str", "(", "padding_char", ")", "[", "0", "]", "*", "int", "(", "padding_right", ")", ")", "if", "width", ":", "strptrn", "=", "'{:'", "+", "(", "'{}{}{}'", ".", "format", "(", "str", "(", "padding_char", ")", "[", "0", "]", ",", "str", "(", "TEXT_ALIGNMENT", "[", "align", "]", ")", ",", "str", "(", "width", ")", ")", ")", "+", "'s}'", "text", "=", "strptrn", ".", "format", "(", "text", ")", "return", "text" ]
Pad given text with given padding characters, inflate it to given width and perform horizontal aligning.
[ "Pad", "given", "text", "with", "given", "padding", "characters", "inflate", "it", "to", "given", "width", "and", "perform", "horizontal", "aligning", "." ]
5ca4ce19fc2d9b5f41441fb9163810f8ca502e79
https://github.com/honzamach/pydgets/blob/5ca4ce19fc2d9b5f41441fb9163810f8ca502e79/pydgets/widgets.py#L522-L538
241,470
honzamach/pydgets
pydgets/widgets.py
ConsoleWidget.fmt_text
def fmt_text(text, bg = None, fg = None, attr = None, plain = False): """ Apply given console formating around given text. """ if not plain: if fg is not None: text = TEXT_FORMATING['fg'][fg] + text if bg is not None: text = TEXT_FORMATING['bg'][bg] + text if attr is not None: text = TEXT_FORMATING['attr'][attr] + text if (fg is not None) or (bg is not None) or (attr is not None): text += TEXT_FORMATING['rst'] return text
python
def fmt_text(text, bg = None, fg = None, attr = None, plain = False): """ Apply given console formating around given text. """ if not plain: if fg is not None: text = TEXT_FORMATING['fg'][fg] + text if bg is not None: text = TEXT_FORMATING['bg'][bg] + text if attr is not None: text = TEXT_FORMATING['attr'][attr] + text if (fg is not None) or (bg is not None) or (attr is not None): text += TEXT_FORMATING['rst'] return text
[ "def", "fmt_text", "(", "text", ",", "bg", "=", "None", ",", "fg", "=", "None", ",", "attr", "=", "None", ",", "plain", "=", "False", ")", ":", "if", "not", "plain", ":", "if", "fg", "is", "not", "None", ":", "text", "=", "TEXT_FORMATING", "[", "'fg'", "]", "[", "fg", "]", "+", "text", "if", "bg", "is", "not", "None", ":", "text", "=", "TEXT_FORMATING", "[", "'bg'", "]", "[", "bg", "]", "+", "text", "if", "attr", "is", "not", "None", ":", "text", "=", "TEXT_FORMATING", "[", "'attr'", "]", "[", "attr", "]", "+", "text", "if", "(", "fg", "is", "not", "None", ")", "or", "(", "bg", "is", "not", "None", ")", "or", "(", "attr", "is", "not", "None", ")", ":", "text", "+=", "TEXT_FORMATING", "[", "'rst'", "]", "return", "text" ]
Apply given console formating around given text.
[ "Apply", "given", "console", "formating", "around", "given", "text", "." ]
5ca4ce19fc2d9b5f41441fb9163810f8ca502e79
https://github.com/honzamach/pydgets/blob/5ca4ce19fc2d9b5f41441fb9163810f8ca502e79/pydgets/widgets.py#L541-L554
241,471
honzamach/pydgets
pydgets/widgets.py
ConsoleWidget.fmt_margin
def fmt_margin(text, margin = None, margin_left = None, margin_right = None, margin_char = ' '): """ Surround given text with given margin characters. """ if margin_left is None: margin_left = margin if margin_right is None: margin_right = margin if margin_left is not None: text = '{}{}'.format(str(margin_char)[0] * int(margin_left), text) if margin_right is not None: text = '{}{}'.format(text, str(margin_char)[0] * int(margin_right)) return text
python
def fmt_margin(text, margin = None, margin_left = None, margin_right = None, margin_char = ' '): """ Surround given text with given margin characters. """ if margin_left is None: margin_left = margin if margin_right is None: margin_right = margin if margin_left is not None: text = '{}{}'.format(str(margin_char)[0] * int(margin_left), text) if margin_right is not None: text = '{}{}'.format(text, str(margin_char)[0] * int(margin_right)) return text
[ "def", "fmt_margin", "(", "text", ",", "margin", "=", "None", ",", "margin_left", "=", "None", ",", "margin_right", "=", "None", ",", "margin_char", "=", "' '", ")", ":", "if", "margin_left", "is", "None", ":", "margin_left", "=", "margin", "if", "margin_right", "is", "None", ":", "margin_right", "=", "margin", "if", "margin_left", "is", "not", "None", ":", "text", "=", "'{}{}'", ".", "format", "(", "str", "(", "margin_char", ")", "[", "0", "]", "*", "int", "(", "margin_left", ")", ",", "text", ")", "if", "margin_right", "is", "not", "None", ":", "text", "=", "'{}{}'", ".", "format", "(", "text", ",", "str", "(", "margin_char", ")", "[", "0", "]", "*", "int", "(", "margin_right", ")", ")", "return", "text" ]
Surround given text with given margin characters.
[ "Surround", "given", "text", "with", "given", "margin", "characters", "." ]
5ca4ce19fc2d9b5f41441fb9163810f8ca502e79
https://github.com/honzamach/pydgets/blob/5ca4ce19fc2d9b5f41441fb9163810f8ca502e79/pydgets/widgets.py#L557-L569
241,472
honzamach/pydgets
pydgets/widgets.py
BorderedMultiLineWidget.bchar
def bchar(posh, posv, border_style): """ Retrieve table border style for particular box border piece. """ index = '{}{}'.format(posv, posh).lower() return BORDER_STYLES[border_style][index]
python
def bchar(posh, posv, border_style): """ Retrieve table border style for particular box border piece. """ index = '{}{}'.format(posv, posh).lower() return BORDER_STYLES[border_style][index]
[ "def", "bchar", "(", "posh", ",", "posv", ",", "border_style", ")", ":", "index", "=", "'{}{}'", ".", "format", "(", "posv", ",", "posh", ")", ".", "lower", "(", ")", "return", "BORDER_STYLES", "[", "border_style", "]", "[", "index", "]" ]
Retrieve table border style for particular box border piece.
[ "Retrieve", "table", "border", "style", "for", "particular", "box", "border", "piece", "." ]
5ca4ce19fc2d9b5f41441fb9163810f8ca502e79
https://github.com/honzamach/pydgets/blob/5ca4ce19fc2d9b5f41441fb9163810f8ca502e79/pydgets/widgets.py#L672-L677
241,473
honzamach/pydgets
pydgets/widgets.py
ListWidget._render_item
def _render_item(self, depth, key, value = None, **settings): """ Format single list item. """ strptrn = self.INDENT * depth lchar = self.lchar(settings[self.SETTING_LIST_STYLE]) s = self._es_text(settings, settings[self.SETTING_LIST_FORMATING]) lchar = self.fmt_text(lchar, **s) strptrn = "{}" if value is not None: strptrn += ": {}" s = self._es_text(settings, settings[self.SETTING_TEXT_FORMATING]) strptrn = self.fmt_text(strptrn.format(key, value), **s) return '{} {} {}'.format(self.INDENT * depth, lchar, strptrn)
python
def _render_item(self, depth, key, value = None, **settings): """ Format single list item. """ strptrn = self.INDENT * depth lchar = self.lchar(settings[self.SETTING_LIST_STYLE]) s = self._es_text(settings, settings[self.SETTING_LIST_FORMATING]) lchar = self.fmt_text(lchar, **s) strptrn = "{}" if value is not None: strptrn += ": {}" s = self._es_text(settings, settings[self.SETTING_TEXT_FORMATING]) strptrn = self.fmt_text(strptrn.format(key, value), **s) return '{} {} {}'.format(self.INDENT * depth, lchar, strptrn)
[ "def", "_render_item", "(", "self", ",", "depth", ",", "key", ",", "value", "=", "None", ",", "*", "*", "settings", ")", ":", "strptrn", "=", "self", ".", "INDENT", "*", "depth", "lchar", "=", "self", ".", "lchar", "(", "settings", "[", "self", ".", "SETTING_LIST_STYLE", "]", ")", "s", "=", "self", ".", "_es_text", "(", "settings", ",", "settings", "[", "self", ".", "SETTING_LIST_FORMATING", "]", ")", "lchar", "=", "self", ".", "fmt_text", "(", "lchar", ",", "*", "*", "s", ")", "strptrn", "=", "\"{}\"", "if", "value", "is", "not", "None", ":", "strptrn", "+=", "\": {}\"", "s", "=", "self", ".", "_es_text", "(", "settings", ",", "settings", "[", "self", ".", "SETTING_TEXT_FORMATING", "]", ")", "strptrn", "=", "self", ".", "fmt_text", "(", "strptrn", ".", "format", "(", "key", ",", "value", ")", ",", "*", "*", "s", ")", "return", "'{} {} {}'", ".", "format", "(", "self", ".", "INDENT", "*", "depth", ",", "lchar", ",", "strptrn", ")" ]
Format single list item.
[ "Format", "single", "list", "item", "." ]
5ca4ce19fc2d9b5f41441fb9163810f8ca502e79
https://github.com/honzamach/pydgets/blob/5ca4ce19fc2d9b5f41441fb9163810f8ca502e79/pydgets/widgets.py#L813-L829
241,474
honzamach/pydgets
pydgets/widgets.py
TreeWidget.tchar
def tchar(tree_style, cur_level, level, item, size): """ Retrieve tree character for particular tree node. """ if (cur_level == level): i1 = '1' if level == 0 else 'x' i2 = '1' if item == 0 else 'x' i3 = 'x' if size == 1: i3 = '1' elif item == (size - 1): i3 = 'l' index = '{}{}{}'.format(i1, i2, i3) else: index = 'non' if item == (size - 1) else 'ver' return TREE_STYLES[tree_style][index]
python
def tchar(tree_style, cur_level, level, item, size): """ Retrieve tree character for particular tree node. """ if (cur_level == level): i1 = '1' if level == 0 else 'x' i2 = '1' if item == 0 else 'x' i3 = 'x' if size == 1: i3 = '1' elif item == (size - 1): i3 = 'l' index = '{}{}{}'.format(i1, i2, i3) else: index = 'non' if item == (size - 1) else 'ver' return TREE_STYLES[tree_style][index]
[ "def", "tchar", "(", "tree_style", ",", "cur_level", ",", "level", ",", "item", ",", "size", ")", ":", "if", "(", "cur_level", "==", "level", ")", ":", "i1", "=", "'1'", "if", "level", "==", "0", "else", "'x'", "i2", "=", "'1'", "if", "item", "==", "0", "else", "'x'", "i3", "=", "'x'", "if", "size", "==", "1", ":", "i3", "=", "'1'", "elif", "item", "==", "(", "size", "-", "1", ")", ":", "i3", "=", "'l'", "index", "=", "'{}{}{}'", ".", "format", "(", "i1", ",", "i2", ",", "i3", ")", "else", ":", "index", "=", "'non'", "if", "item", "==", "(", "size", "-", "1", ")", "else", "'ver'", "return", "TREE_STYLES", "[", "tree_style", "]", "[", "index", "]" ]
Retrieve tree character for particular tree node.
[ "Retrieve", "tree", "character", "for", "particular", "tree", "node", "." ]
5ca4ce19fc2d9b5f41441fb9163810f8ca502e79
https://github.com/honzamach/pydgets/blob/5ca4ce19fc2d9b5f41441fb9163810f8ca502e79/pydgets/widgets.py#L904-L919
241,475
honzamach/pydgets
pydgets/widgets.py
TreeWidget._render_item
def _render_item(self, dstack, key, value = None, **settings): """ Format single tree line. """ cur_depth = len(dstack) - 1 treeptrn = '' s = self._es_text(settings, settings[self.SETTING_TREE_FORMATING]) for ds in dstack: treeptrn += ' ' + self.fmt_text(self.tchar(settings[self.SETTING_TREE_STYLE], cur_depth, *ds), **s) + '' strptrn = "{}" if value is not None: strptrn += ": {}" s = self._es_text(settings, settings[self.SETTING_TEXT_FORMATING]) strptrn = self.fmt_text(strptrn.format(key, value), **s) return '{} {}'.format(treeptrn, strptrn)
python
def _render_item(self, dstack, key, value = None, **settings): """ Format single tree line. """ cur_depth = len(dstack) - 1 treeptrn = '' s = self._es_text(settings, settings[self.SETTING_TREE_FORMATING]) for ds in dstack: treeptrn += ' ' + self.fmt_text(self.tchar(settings[self.SETTING_TREE_STYLE], cur_depth, *ds), **s) + '' strptrn = "{}" if value is not None: strptrn += ": {}" s = self._es_text(settings, settings[self.SETTING_TEXT_FORMATING]) strptrn = self.fmt_text(strptrn.format(key, value), **s) return '{} {}'.format(treeptrn, strptrn)
[ "def", "_render_item", "(", "self", ",", "dstack", ",", "key", ",", "value", "=", "None", ",", "*", "*", "settings", ")", ":", "cur_depth", "=", "len", "(", "dstack", ")", "-", "1", "treeptrn", "=", "''", "s", "=", "self", ".", "_es_text", "(", "settings", ",", "settings", "[", "self", ".", "SETTING_TREE_FORMATING", "]", ")", "for", "ds", "in", "dstack", ":", "treeptrn", "+=", "' '", "+", "self", ".", "fmt_text", "(", "self", ".", "tchar", "(", "settings", "[", "self", ".", "SETTING_TREE_STYLE", "]", ",", "cur_depth", ",", "*", "ds", ")", ",", "*", "*", "s", ")", "+", "''", "strptrn", "=", "\"{}\"", "if", "value", "is", "not", "None", ":", "strptrn", "+=", "\": {}\"", "s", "=", "self", ".", "_es_text", "(", "settings", ",", "settings", "[", "self", ".", "SETTING_TEXT_FORMATING", "]", ")", "strptrn", "=", "self", ".", "fmt_text", "(", "strptrn", ".", "format", "(", "key", ",", "value", ")", ",", "*", "*", "s", ")", "return", "'{} {}'", ".", "format", "(", "treeptrn", ",", "strptrn", ")" ]
Format single tree line.
[ "Format", "single", "tree", "line", "." ]
5ca4ce19fc2d9b5f41441fb9163810f8ca502e79
https://github.com/honzamach/pydgets/blob/5ca4ce19fc2d9b5f41441fb9163810f8ca502e79/pydgets/widgets.py#L923-L940
241,476
honzamach/pydgets
pydgets/widgets.py
TreeWidget._render_content_list
def _render_content_list(self, content, depth, dstack, **settings): """ Render the list. """ result = [] i = 0 size = len(content) for value in content: ds = [(depth, i, size)] ds = dstack + ds if isinstance(value, dict): result.append(self._render_item(ds, "[{}]".format(i), **settings)) result += self._render_content_dict(value, depth + 1, ds, **settings) elif isinstance(value, list): result.append(self._render_item(ds, "[{}]".format(i), **settings)) result += self._render_content_list(value, depth + 1, ds, **settings) else: result.append(self._render_item(ds, value, **settings)) i += 1 return result
python
def _render_content_list(self, content, depth, dstack, **settings): """ Render the list. """ result = [] i = 0 size = len(content) for value in content: ds = [(depth, i, size)] ds = dstack + ds if isinstance(value, dict): result.append(self._render_item(ds, "[{}]".format(i), **settings)) result += self._render_content_dict(value, depth + 1, ds, **settings) elif isinstance(value, list): result.append(self._render_item(ds, "[{}]".format(i), **settings)) result += self._render_content_list(value, depth + 1, ds, **settings) else: result.append(self._render_item(ds, value, **settings)) i += 1 return result
[ "def", "_render_content_list", "(", "self", ",", "content", ",", "depth", ",", "dstack", ",", "*", "*", "settings", ")", ":", "result", "=", "[", "]", "i", "=", "0", "size", "=", "len", "(", "content", ")", "for", "value", "in", "content", ":", "ds", "=", "[", "(", "depth", ",", "i", ",", "size", ")", "]", "ds", "=", "dstack", "+", "ds", "if", "isinstance", "(", "value", ",", "dict", ")", ":", "result", ".", "append", "(", "self", ".", "_render_item", "(", "ds", ",", "\"[{}]\"", ".", "format", "(", "i", ")", ",", "*", "*", "settings", ")", ")", "result", "+=", "self", ".", "_render_content_dict", "(", "value", ",", "depth", "+", "1", ",", "ds", ",", "*", "*", "settings", ")", "elif", "isinstance", "(", "value", ",", "list", ")", ":", "result", ".", "append", "(", "self", ".", "_render_item", "(", "ds", ",", "\"[{}]\"", ".", "format", "(", "i", ")", ",", "*", "*", "settings", ")", ")", "result", "+=", "self", ".", "_render_content_list", "(", "value", ",", "depth", "+", "1", ",", "ds", ",", "*", "*", "settings", ")", "else", ":", "result", ".", "append", "(", "self", ".", "_render_item", "(", "ds", ",", "value", ",", "*", "*", "settings", ")", ")", "i", "+=", "1", "return", "result" ]
Render the list.
[ "Render", "the", "list", "." ]
5ca4ce19fc2d9b5f41441fb9163810f8ca502e79
https://github.com/honzamach/pydgets/blob/5ca4ce19fc2d9b5f41441fb9163810f8ca502e79/pydgets/widgets.py#L942-L961
241,477
honzamach/pydgets
pydgets/widgets.py
TreeWidget._render_content_dict
def _render_content_dict(self, content, depth, dstack, **settings): """ Render the dict. """ result = [] i = 0 size = len(content) for key in sorted(content): ds = [(depth, i, size)] ds = dstack + ds if isinstance(content[key], dict): result.append(self._render_item(ds, key, **settings)) result += self._render_content_dict(content[key], depth + 1, ds, **settings) elif isinstance(content[key], list): result.append(self._render_item(ds, key, **settings)) result += self._render_content_list(content[key], depth + 1, ds, **settings) else: result.append(self._render_item(ds, key, content[key], **settings)) i += 1 return result
python
def _render_content_dict(self, content, depth, dstack, **settings): """ Render the dict. """ result = [] i = 0 size = len(content) for key in sorted(content): ds = [(depth, i, size)] ds = dstack + ds if isinstance(content[key], dict): result.append(self._render_item(ds, key, **settings)) result += self._render_content_dict(content[key], depth + 1, ds, **settings) elif isinstance(content[key], list): result.append(self._render_item(ds, key, **settings)) result += self._render_content_list(content[key], depth + 1, ds, **settings) else: result.append(self._render_item(ds, key, content[key], **settings)) i += 1 return result
[ "def", "_render_content_dict", "(", "self", ",", "content", ",", "depth", ",", "dstack", ",", "*", "*", "settings", ")", ":", "result", "=", "[", "]", "i", "=", "0", "size", "=", "len", "(", "content", ")", "for", "key", "in", "sorted", "(", "content", ")", ":", "ds", "=", "[", "(", "depth", ",", "i", ",", "size", ")", "]", "ds", "=", "dstack", "+", "ds", "if", "isinstance", "(", "content", "[", "key", "]", ",", "dict", ")", ":", "result", ".", "append", "(", "self", ".", "_render_item", "(", "ds", ",", "key", ",", "*", "*", "settings", ")", ")", "result", "+=", "self", ".", "_render_content_dict", "(", "content", "[", "key", "]", ",", "depth", "+", "1", ",", "ds", ",", "*", "*", "settings", ")", "elif", "isinstance", "(", "content", "[", "key", "]", ",", "list", ")", ":", "result", ".", "append", "(", "self", ".", "_render_item", "(", "ds", ",", "key", ",", "*", "*", "settings", ")", ")", "result", "+=", "self", ".", "_render_content_list", "(", "content", "[", "key", "]", ",", "depth", "+", "1", ",", "ds", ",", "*", "*", "settings", ")", "else", ":", "result", ".", "append", "(", "self", ".", "_render_item", "(", "ds", ",", "key", ",", "content", "[", "key", "]", ",", "*", "*", "settings", ")", ")", "i", "+=", "1", "return", "result" ]
Render the dict.
[ "Render", "the", "dict", "." ]
5ca4ce19fc2d9b5f41441fb9163810f8ca502e79
https://github.com/honzamach/pydgets/blob/5ca4ce19fc2d9b5f41441fb9163810f8ca502e79/pydgets/widgets.py#L963-L982
241,478
honzamach/pydgets
pydgets/widgets.py
TreeWidget._render_content
def _render_content(self, content, **settings): """ Render the tree widget. """ if isinstance(content, dict): return self._render_content_dict(content, 0, [], **settings) elif isinstance(content, list): return self._render_content_list(content, 0, [], **settings) else: raise Exception("Received invalid data tree for rendering.")
python
def _render_content(self, content, **settings): """ Render the tree widget. """ if isinstance(content, dict): return self._render_content_dict(content, 0, [], **settings) elif isinstance(content, list): return self._render_content_list(content, 0, [], **settings) else: raise Exception("Received invalid data tree for rendering.")
[ "def", "_render_content", "(", "self", ",", "content", ",", "*", "*", "settings", ")", ":", "if", "isinstance", "(", "content", ",", "dict", ")", ":", "return", "self", ".", "_render_content_dict", "(", "content", ",", "0", ",", "[", "]", ",", "*", "*", "settings", ")", "elif", "isinstance", "(", "content", ",", "list", ")", ":", "return", "self", ".", "_render_content_list", "(", "content", ",", "0", ",", "[", "]", ",", "*", "*", "settings", ")", "else", ":", "raise", "Exception", "(", "\"Received invalid data tree for rendering.\"", ")" ]
Render the tree widget.
[ "Render", "the", "tree", "widget", "." ]
5ca4ce19fc2d9b5f41441fb9163810f8ca502e79
https://github.com/honzamach/pydgets/blob/5ca4ce19fc2d9b5f41441fb9163810f8ca502e79/pydgets/widgets.py#L986-L995
241,479
honzamach/pydgets
pydgets/widgets.py
BoxWidget.fmt_border
def fmt_border(self, width, t = 'm', border_style = 'utf8.a', border_formating = {}): """ Format box separator line. """ border = self.bchar('l', t, border_style) + (self.bchar('h', t, border_style) * (width-2)) + self.bchar('r', t, border_style) return self.fmt_text(border, **border_formating)
python
def fmt_border(self, width, t = 'm', border_style = 'utf8.a', border_formating = {}): """ Format box separator line. """ border = self.bchar('l', t, border_style) + (self.bchar('h', t, border_style) * (width-2)) + self.bchar('r', t, border_style) return self.fmt_text(border, **border_formating)
[ "def", "fmt_border", "(", "self", ",", "width", ",", "t", "=", "'m'", ",", "border_style", "=", "'utf8.a'", ",", "border_formating", "=", "{", "}", ")", ":", "border", "=", "self", ".", "bchar", "(", "'l'", ",", "t", ",", "border_style", ")", "+", "(", "self", ".", "bchar", "(", "'h'", ",", "t", ",", "border_style", ")", "*", "(", "width", "-", "2", ")", ")", "+", "self", ".", "bchar", "(", "'r'", ",", "t", ",", "border_style", ")", "return", "self", ".", "fmt_text", "(", "border", ",", "*", "*", "border_formating", ")" ]
Format box separator line.
[ "Format", "box", "separator", "line", "." ]
5ca4ce19fc2d9b5f41441fb9163810f8ca502e79
https://github.com/honzamach/pydgets/blob/5ca4ce19fc2d9b5f41441fb9163810f8ca502e79/pydgets/widgets.py#L1020-L1025
241,480
honzamach/pydgets
pydgets/widgets.py
BoxWidget._wrap_content
def _wrap_content(content, width): """ Wrap given content into lines of given width. """ data = [] if isinstance(content, list): data += content else: data.append(content) lines = [] for d in data: l = textwrap.wrap(d, width) lines += l return lines
python
def _wrap_content(content, width): """ Wrap given content into lines of given width. """ data = [] if isinstance(content, list): data += content else: data.append(content) lines = [] for d in data: l = textwrap.wrap(d, width) lines += l return lines
[ "def", "_wrap_content", "(", "content", ",", "width", ")", ":", "data", "=", "[", "]", "if", "isinstance", "(", "content", ",", "list", ")", ":", "data", "+=", "content", "else", ":", "data", ".", "append", "(", "content", ")", "lines", "=", "[", "]", "for", "d", "in", "data", ":", "l", "=", "textwrap", ".", "wrap", "(", "d", ",", "width", ")", "lines", "+=", "l", "return", "lines" ]
Wrap given content into lines of given width.
[ "Wrap", "given", "content", "into", "lines", "of", "given", "width", "." ]
5ca4ce19fc2d9b5f41441fb9163810f8ca502e79
https://github.com/honzamach/pydgets/blob/5ca4ce19fc2d9b5f41441fb9163810f8ca502e79/pydgets/widgets.py#L1030-L1044
241,481
honzamach/pydgets
pydgets/widgets.py
BoxWidget._render_border_line
def _render_border_line(self, t, settings): """ Render box border line. """ s = self._es(settings, self.SETTING_WIDTH, self.SETTING_MARGIN, self.SETTING_MARGIN_LEFT, self.SETTING_MARGIN_RIGHT) w = self.calculate_width_widget(**s) s = self._es(settings, self.SETTING_BORDER_STYLE, self.SETTING_BORDER_FORMATING) border_line = self.fmt_border(w, t, **s) s = self._es(settings, self.SETTING_MARGIN, self.SETTING_MARGIN_LEFT, self.SETTING_MARGIN_RIGHT, self.SETTING_MARGIN_CHAR) border_line = self.fmt_margin(border_line, **s) return border_line
python
def _render_border_line(self, t, settings): """ Render box border line. """ s = self._es(settings, self.SETTING_WIDTH, self.SETTING_MARGIN, self.SETTING_MARGIN_LEFT, self.SETTING_MARGIN_RIGHT) w = self.calculate_width_widget(**s) s = self._es(settings, self.SETTING_BORDER_STYLE, self.SETTING_BORDER_FORMATING) border_line = self.fmt_border(w, t, **s) s = self._es(settings, self.SETTING_MARGIN, self.SETTING_MARGIN_LEFT, self.SETTING_MARGIN_RIGHT, self.SETTING_MARGIN_CHAR) border_line = self.fmt_margin(border_line, **s) return border_line
[ "def", "_render_border_line", "(", "self", ",", "t", ",", "settings", ")", ":", "s", "=", "self", ".", "_es", "(", "settings", ",", "self", ".", "SETTING_WIDTH", ",", "self", ".", "SETTING_MARGIN", ",", "self", ".", "SETTING_MARGIN_LEFT", ",", "self", ".", "SETTING_MARGIN_RIGHT", ")", "w", "=", "self", ".", "calculate_width_widget", "(", "*", "*", "s", ")", "s", "=", "self", ".", "_es", "(", "settings", ",", "self", ".", "SETTING_BORDER_STYLE", ",", "self", ".", "SETTING_BORDER_FORMATING", ")", "border_line", "=", "self", ".", "fmt_border", "(", "w", ",", "t", ",", "*", "*", "s", ")", "s", "=", "self", ".", "_es", "(", "settings", ",", "self", ".", "SETTING_MARGIN", ",", "self", ".", "SETTING_MARGIN_LEFT", ",", "self", ".", "SETTING_MARGIN_RIGHT", ",", "self", ".", "SETTING_MARGIN_CHAR", ")", "border_line", "=", "self", ".", "fmt_margin", "(", "border_line", ",", "*", "*", "s", ")", "return", "border_line" ]
Render box border line.
[ "Render", "box", "border", "line", "." ]
5ca4ce19fc2d9b5f41441fb9163810f8ca502e79
https://github.com/honzamach/pydgets/blob/5ca4ce19fc2d9b5f41441fb9163810f8ca502e79/pydgets/widgets.py#L1048-L1058
241,482
honzamach/pydgets
pydgets/widgets.py
BoxWidget._render_line
def _render_line(self, line, settings): """ Render single box line. """ s = self._es(settings, self.SETTING_WIDTH, self.SETTING_FLAG_BORDER, self.SETTING_MARGIN, self.SETTING_MARGIN_LEFT, self.SETTING_MARGIN_RIGHT) width_content = self.calculate_width_widget_int(**s) s = self._es_content(settings) s[self.SETTING_WIDTH] = width_content line = self.fmt_content(line, **s) s = self._es_text(settings, settings[self.SETTING_TEXT_FORMATING]) line = self.fmt_text(line, **s) s = self._es(settings, self.SETTING_BORDER_STYLE) bchar = self.bchar('v', 'm', **s) s = self._es_text(settings, settings[self.SETTING_BORDER_FORMATING]) bchar = self.fmt_text(bchar, **s) line = '{}{}{}'.format(bchar, line, bchar) s = self._es_margin(settings) line = self.fmt_margin(line, **s) return line
python
def _render_line(self, line, settings): """ Render single box line. """ s = self._es(settings, self.SETTING_WIDTH, self.SETTING_FLAG_BORDER, self.SETTING_MARGIN, self.SETTING_MARGIN_LEFT, self.SETTING_MARGIN_RIGHT) width_content = self.calculate_width_widget_int(**s) s = self._es_content(settings) s[self.SETTING_WIDTH] = width_content line = self.fmt_content(line, **s) s = self._es_text(settings, settings[self.SETTING_TEXT_FORMATING]) line = self.fmt_text(line, **s) s = self._es(settings, self.SETTING_BORDER_STYLE) bchar = self.bchar('v', 'm', **s) s = self._es_text(settings, settings[self.SETTING_BORDER_FORMATING]) bchar = self.fmt_text(bchar, **s) line = '{}{}{}'.format(bchar, line, bchar) s = self._es_margin(settings) line = self.fmt_margin(line, **s) return line
[ "def", "_render_line", "(", "self", ",", "line", ",", "settings", ")", ":", "s", "=", "self", ".", "_es", "(", "settings", ",", "self", ".", "SETTING_WIDTH", ",", "self", ".", "SETTING_FLAG_BORDER", ",", "self", ".", "SETTING_MARGIN", ",", "self", ".", "SETTING_MARGIN_LEFT", ",", "self", ".", "SETTING_MARGIN_RIGHT", ")", "width_content", "=", "self", ".", "calculate_width_widget_int", "(", "*", "*", "s", ")", "s", "=", "self", ".", "_es_content", "(", "settings", ")", "s", "[", "self", ".", "SETTING_WIDTH", "]", "=", "width_content", "line", "=", "self", ".", "fmt_content", "(", "line", ",", "*", "*", "s", ")", "s", "=", "self", ".", "_es_text", "(", "settings", ",", "settings", "[", "self", ".", "SETTING_TEXT_FORMATING", "]", ")", "line", "=", "self", ".", "fmt_text", "(", "line", ",", "*", "*", "s", ")", "s", "=", "self", ".", "_es", "(", "settings", ",", "self", ".", "SETTING_BORDER_STYLE", ")", "bchar", "=", "self", ".", "bchar", "(", "'v'", ",", "'m'", ",", "*", "*", "s", ")", "s", "=", "self", ".", "_es_text", "(", "settings", ",", "settings", "[", "self", ".", "SETTING_BORDER_FORMATING", "]", ")", "bchar", "=", "self", ".", "fmt_text", "(", "bchar", ",", "*", "*", "s", ")", "line", "=", "'{}{}{}'", ".", "format", "(", "bchar", ",", "line", ",", "bchar", ")", "s", "=", "self", ".", "_es_margin", "(", "settings", ")", "line", "=", "self", ".", "fmt_margin", "(", "line", ",", "*", "*", "s", ")", "return", "line" ]
Render single box line.
[ "Render", "single", "box", "line", "." ]
5ca4ce19fc2d9b5f41441fb9163810f8ca502e79
https://github.com/honzamach/pydgets/blob/5ca4ce19fc2d9b5f41441fb9163810f8ca502e79/pydgets/widgets.py#L1060-L1083
241,483
honzamach/pydgets
pydgets/widgets.py
TableWidget.fmt_border
def fmt_border(self, dimensions, t = 'm', border_style = 'utf8.a', border_formating = {}): """ Format table separator line. """ cells = [] for column in dimensions: cells.append(self.bchar('h', t, border_style) * (dimensions[column] + 2)) border = '{}{}{}'.format(self.bchar('l', t, border_style), self.bchar('m', t, border_style).join(cells), self.bchar('r', t, border_style)) return self.fmt_text(border, **border_formating)
python
def fmt_border(self, dimensions, t = 'm', border_style = 'utf8.a', border_formating = {}): """ Format table separator line. """ cells = [] for column in dimensions: cells.append(self.bchar('h', t, border_style) * (dimensions[column] + 2)) border = '{}{}{}'.format(self.bchar('l', t, border_style), self.bchar('m', t, border_style).join(cells), self.bchar('r', t, border_style)) return self.fmt_text(border, **border_formating)
[ "def", "fmt_border", "(", "self", ",", "dimensions", ",", "t", "=", "'m'", ",", "border_style", "=", "'utf8.a'", ",", "border_formating", "=", "{", "}", ")", ":", "cells", "=", "[", "]", "for", "column", "in", "dimensions", ":", "cells", ".", "append", "(", "self", ".", "bchar", "(", "'h'", ",", "t", ",", "border_style", ")", "*", "(", "dimensions", "[", "column", "]", "+", "2", ")", ")", "border", "=", "'{}{}{}'", ".", "format", "(", "self", ".", "bchar", "(", "'l'", ",", "t", ",", "border_style", ")", ",", "self", ".", "bchar", "(", "'m'", ",", "t", ",", "border_style", ")", ".", "join", "(", "cells", ")", ",", "self", ".", "bchar", "(", "'r'", ",", "t", ",", "border_style", ")", ")", "return", "self", ".", "fmt_text", "(", "border", ",", "*", "*", "border_formating", ")" ]
Format table separator line.
[ "Format", "table", "separator", "line", "." ]
5ca4ce19fc2d9b5f41441fb9163810f8ca502e79
https://github.com/honzamach/pydgets/blob/5ca4ce19fc2d9b5f41441fb9163810f8ca502e79/pydgets/widgets.py#L1140-L1149
241,484
honzamach/pydgets
pydgets/widgets.py
TableWidget.fmt_cell
def fmt_cell(self, value, width, cell_formating, **text_formating): """ Format sigle table cell. """ strptrn = " {:" + '{:s}{:d}'.format(cell_formating.get('align', '<'), width) + "s} " strptrn = self.fmt_text(strptrn, **text_formating) return strptrn.format(value)
python
def fmt_cell(self, value, width, cell_formating, **text_formating): """ Format sigle table cell. """ strptrn = " {:" + '{:s}{:d}'.format(cell_formating.get('align', '<'), width) + "s} " strptrn = self.fmt_text(strptrn, **text_formating) return strptrn.format(value)
[ "def", "fmt_cell", "(", "self", ",", "value", ",", "width", ",", "cell_formating", ",", "*", "*", "text_formating", ")", ":", "strptrn", "=", "\" {:\"", "+", "'{:s}{:d}'", ".", "format", "(", "cell_formating", ".", "get", "(", "'align'", ",", "'<'", ")", ",", "width", ")", "+", "\"s} \"", "strptrn", "=", "self", ".", "fmt_text", "(", "strptrn", ",", "*", "*", "text_formating", ")", "return", "strptrn", ".", "format", "(", "value", ")" ]
Format sigle table cell.
[ "Format", "sigle", "table", "cell", "." ]
5ca4ce19fc2d9b5f41441fb9163810f8ca502e79
https://github.com/honzamach/pydgets/blob/5ca4ce19fc2d9b5f41441fb9163810f8ca502e79/pydgets/widgets.py#L1151-L1157
241,485
honzamach/pydgets
pydgets/widgets.py
TableWidget.fmt_row
def fmt_row(self, columns, dimensions, row, **settings): """ Format single table row. """ cells = [] i = 0 for column in columns: cells.append(self.fmt_cell( row[i], dimensions[i], column, **settings[self.SETTING_TEXT_FORMATING] ) ) i += 1 return self.bchar('v', 'm', settings[self.SETTING_BORDER_STYLE], **settings[self.SETTING_BORDER_FORMATING]) + \ self.bchar('v', 'm', settings[self.SETTING_BORDER_STYLE], **settings[self.SETTING_BORDER_FORMATING]).join(cells) + \ self.bchar('v', 'm', settings[self.SETTING_BORDER_STYLE], **settings[self.SETTING_BORDER_FORMATING])
python
def fmt_row(self, columns, dimensions, row, **settings): """ Format single table row. """ cells = [] i = 0 for column in columns: cells.append(self.fmt_cell( row[i], dimensions[i], column, **settings[self.SETTING_TEXT_FORMATING] ) ) i += 1 return self.bchar('v', 'm', settings[self.SETTING_BORDER_STYLE], **settings[self.SETTING_BORDER_FORMATING]) + \ self.bchar('v', 'm', settings[self.SETTING_BORDER_STYLE], **settings[self.SETTING_BORDER_FORMATING]).join(cells) + \ self.bchar('v', 'm', settings[self.SETTING_BORDER_STYLE], **settings[self.SETTING_BORDER_FORMATING])
[ "def", "fmt_row", "(", "self", ",", "columns", ",", "dimensions", ",", "row", ",", "*", "*", "settings", ")", ":", "cells", "=", "[", "]", "i", "=", "0", "for", "column", "in", "columns", ":", "cells", ".", "append", "(", "self", ".", "fmt_cell", "(", "row", "[", "i", "]", ",", "dimensions", "[", "i", "]", ",", "column", ",", "*", "*", "settings", "[", "self", ".", "SETTING_TEXT_FORMATING", "]", ")", ")", "i", "+=", "1", "return", "self", ".", "bchar", "(", "'v'", ",", "'m'", ",", "settings", "[", "self", ".", "SETTING_BORDER_STYLE", "]", ",", "*", "*", "settings", "[", "self", ".", "SETTING_BORDER_FORMATING", "]", ")", "+", "self", ".", "bchar", "(", "'v'", ",", "'m'", ",", "settings", "[", "self", ".", "SETTING_BORDER_STYLE", "]", ",", "*", "*", "settings", "[", "self", ".", "SETTING_BORDER_FORMATING", "]", ")", ".", "join", "(", "cells", ")", "+", "self", ".", "bchar", "(", "'v'", ",", "'m'", ",", "settings", "[", "self", ".", "SETTING_BORDER_STYLE", "]", ",", "*", "*", "settings", "[", "self", ".", "SETTING_BORDER_FORMATING", "]", ")" ]
Format single table row.
[ "Format", "single", "table", "row", "." ]
5ca4ce19fc2d9b5f41441fb9163810f8ca502e79
https://github.com/honzamach/pydgets/blob/5ca4ce19fc2d9b5f41441fb9163810f8ca502e79/pydgets/widgets.py#L1159-L1176
241,486
honzamach/pydgets
pydgets/widgets.py
TableWidget.fmt_row_header
def fmt_row_header(self, columns, dimensions, **settings): """ Format table header row. """ row = list(map(lambda x: x['label'], columns)) return self.fmt_row(columns, dimensions, row, **settings)
python
def fmt_row_header(self, columns, dimensions, **settings): """ Format table header row. """ row = list(map(lambda x: x['label'], columns)) return self.fmt_row(columns, dimensions, row, **settings)
[ "def", "fmt_row_header", "(", "self", ",", "columns", ",", "dimensions", ",", "*", "*", "settings", ")", ":", "row", "=", "list", "(", "map", "(", "lambda", "x", ":", "x", "[", "'label'", "]", ",", "columns", ")", ")", "return", "self", ".", "fmt_row", "(", "columns", ",", "dimensions", ",", "row", ",", "*", "*", "settings", ")" ]
Format table header row.
[ "Format", "table", "header", "row", "." ]
5ca4ce19fc2d9b5f41441fb9163810f8ca502e79
https://github.com/honzamach/pydgets/blob/5ca4ce19fc2d9b5f41441fb9163810f8ca502e79/pydgets/widgets.py#L1178-L1183
241,487
honzamach/pydgets
pydgets/widgets.py
BarChartWidget._render_bar
def _render_bar(self, bar, value, max_value, label_width, bar_width, **settings): """ Render single chart bar. """ percent = value / max_value barstr = "" barstr += str(settings[self.SETTING_BAR_CHAR]) * int(bar_width * percent) s = {k: settings[k] for k in (self.SETTING_FLAG_PLAIN,)} s.update(settings[self.SETTING_BAR_FORMATING]) barstr = self.fmt_text(barstr, **s) barstr += ' ' * int(bar_width - int(bar_width * percent)) strptrn = "{:"+str(label_width)+"s} [{:s}]" return strptrn.format(bar.get('label'), barstr)
python
def _render_bar(self, bar, value, max_value, label_width, bar_width, **settings): """ Render single chart bar. """ percent = value / max_value barstr = "" barstr += str(settings[self.SETTING_BAR_CHAR]) * int(bar_width * percent) s = {k: settings[k] for k in (self.SETTING_FLAG_PLAIN,)} s.update(settings[self.SETTING_BAR_FORMATING]) barstr = self.fmt_text(barstr, **s) barstr += ' ' * int(bar_width - int(bar_width * percent)) strptrn = "{:"+str(label_width)+"s} [{:s}]" return strptrn.format(bar.get('label'), barstr)
[ "def", "_render_bar", "(", "self", ",", "bar", ",", "value", ",", "max_value", ",", "label_width", ",", "bar_width", ",", "*", "*", "settings", ")", ":", "percent", "=", "value", "/", "max_value", "barstr", "=", "\"\"", "barstr", "+=", "str", "(", "settings", "[", "self", ".", "SETTING_BAR_CHAR", "]", ")", "*", "int", "(", "bar_width", "*", "percent", ")", "s", "=", "{", "k", ":", "settings", "[", "k", "]", "for", "k", "in", "(", "self", ".", "SETTING_FLAG_PLAIN", ",", ")", "}", "s", ".", "update", "(", "settings", "[", "self", ".", "SETTING_BAR_FORMATING", "]", ")", "barstr", "=", "self", ".", "fmt_text", "(", "barstr", ",", "*", "*", "s", ")", "barstr", "+=", "' '", "*", "int", "(", "bar_width", "-", "int", "(", "bar_width", "*", "percent", ")", ")", "strptrn", "=", "\"{:\"", "+", "str", "(", "label_width", ")", "+", "\"s} [{:s}]\"", "return", "strptrn", ".", "format", "(", "bar", ".", "get", "(", "'label'", ")", ",", "barstr", ")" ]
Render single chart bar.
[ "Render", "single", "chart", "bar", "." ]
5ca4ce19fc2d9b5f41441fb9163810f8ca502e79
https://github.com/honzamach/pydgets/blob/5ca4ce19fc2d9b5f41441fb9163810f8ca502e79/pydgets/widgets.py#L1359-L1371
241,488
firstprayer/monsql
monsql/sql.py
build_select
def build_select(query_obj): """ Given a Query obj, return the corresponding sql """ return build_select_query(query_obj.source, query_obj.fields, query_obj.filter, skip=query_obj.skip, \ limit=query_obj.limit, sort=query_obj.sort, distinct=query_obj.distinct)
python
def build_select(query_obj): """ Given a Query obj, return the corresponding sql """ return build_select_query(query_obj.source, query_obj.fields, query_obj.filter, skip=query_obj.skip, \ limit=query_obj.limit, sort=query_obj.sort, distinct=query_obj.distinct)
[ "def", "build_select", "(", "query_obj", ")", ":", "return", "build_select_query", "(", "query_obj", ".", "source", ",", "query_obj", ".", "fields", ",", "query_obj", ".", "filter", ",", "skip", "=", "query_obj", ".", "skip", ",", "limit", "=", "query_obj", ".", "limit", ",", "sort", "=", "query_obj", ".", "sort", ",", "distinct", "=", "query_obj", ".", "distinct", ")" ]
Given a Query obj, return the corresponding sql
[ "Given", "a", "Query", "obj", "return", "the", "corresponding", "sql" ]
6285c15b574c8664046eae2edfeb548c7b173efd
https://github.com/firstprayer/monsql/blob/6285c15b574c8664046eae2edfeb548c7b173efd/monsql/sql.py#L62-L67
241,489
firstprayer/monsql
monsql/sql.py
build_insert
def build_insert(table_name, attributes): """ Given the table_name and the data, return the sql to insert the data """ sql = "INSERT INTO %s" %(table_name) column_str = u"" value_str = u"" for index, (key, value) in enumerate(attributes.items()): if index > 0: column_str += u"," value_str += u"," column_str += key value_str += value_to_sql_str(value) sql = sql + u"(%s) VALUES(%s)" %(column_str, value_str) return sql
python
def build_insert(table_name, attributes): """ Given the table_name and the data, return the sql to insert the data """ sql = "INSERT INTO %s" %(table_name) column_str = u"" value_str = u"" for index, (key, value) in enumerate(attributes.items()): if index > 0: column_str += u"," value_str += u"," column_str += key value_str += value_to_sql_str(value) sql = sql + u"(%s) VALUES(%s)" %(column_str, value_str) return sql
[ "def", "build_insert", "(", "table_name", ",", "attributes", ")", ":", "sql", "=", "\"INSERT INTO %s\"", "%", "(", "table_name", ")", "column_str", "=", "u\"\"", "value_str", "=", "u\"\"", "for", "index", ",", "(", "key", ",", "value", ")", "in", "enumerate", "(", "attributes", ".", "items", "(", ")", ")", ":", "if", "index", ">", "0", ":", "column_str", "+=", "u\",\"", "value_str", "+=", "u\",\"", "column_str", "+=", "key", "value_str", "+=", "value_to_sql_str", "(", "value", ")", "sql", "=", "sql", "+", "u\"(%s) VALUES(%s)\"", "%", "(", "column_str", ",", "value_str", ")", "return", "sql" ]
Given the table_name and the data, return the sql to insert the data
[ "Given", "the", "table_name", "and", "the", "data", "return", "the", "sql", "to", "insert", "the", "data" ]
6285c15b574c8664046eae2edfeb548c7b173efd
https://github.com/firstprayer/monsql/blob/6285c15b574c8664046eae2edfeb548c7b173efd/monsql/sql.py#L70-L84
241,490
mayfield/cellulario
cellulario/tier.py
Tier.make_gatherer
def make_gatherer(cls, cell, source_tiers, gatherby): """ Produce a single source tier that gathers from a set of tiers when the key function returns a unique result for each tier. """ pending = collections.defaultdict(dict) tier_hashes = [hash(x) for x in source_tiers] @asyncio.coroutine def organize(route, *args): srchash = hash(route.source) key = gatherby(*args) group = pending[key] assert srchash not in group group[srchash] = args if len(group) == len(tier_hashes): del pending[key] yield from route.emit(*[group[x] for x in tier_hashes]) return cls(cell, organize)
python
def make_gatherer(cls, cell, source_tiers, gatherby): """ Produce a single source tier that gathers from a set of tiers when the key function returns a unique result for each tier. """ pending = collections.defaultdict(dict) tier_hashes = [hash(x) for x in source_tiers] @asyncio.coroutine def organize(route, *args): srchash = hash(route.source) key = gatherby(*args) group = pending[key] assert srchash not in group group[srchash] = args if len(group) == len(tier_hashes): del pending[key] yield from route.emit(*[group[x] for x in tier_hashes]) return cls(cell, organize)
[ "def", "make_gatherer", "(", "cls", ",", "cell", ",", "source_tiers", ",", "gatherby", ")", ":", "pending", "=", "collections", ".", "defaultdict", "(", "dict", ")", "tier_hashes", "=", "[", "hash", "(", "x", ")", "for", "x", "in", "source_tiers", "]", "@", "asyncio", ".", "coroutine", "def", "organize", "(", "route", ",", "*", "args", ")", ":", "srchash", "=", "hash", "(", "route", ".", "source", ")", "key", "=", "gatherby", "(", "*", "args", ")", "group", "=", "pending", "[", "key", "]", "assert", "srchash", "not", "in", "group", "group", "[", "srchash", "]", "=", "args", "if", "len", "(", "group", ")", "==", "len", "(", "tier_hashes", ")", ":", "del", "pending", "[", "key", "]", "yield", "from", "route", ".", "emit", "(", "*", "[", "group", "[", "x", "]", "for", "x", "in", "tier_hashes", "]", ")", "return", "cls", "(", "cell", ",", "organize", ")" ]
Produce a single source tier that gathers from a set of tiers when the key function returns a unique result for each tier.
[ "Produce", "a", "single", "source", "tier", "that", "gathers", "from", "a", "set", "of", "tiers", "when", "the", "key", "function", "returns", "a", "unique", "result", "for", "each", "tier", "." ]
e9dc10532a0357bc90ebaa2655b36822f9249673
https://github.com/mayfield/cellulario/blob/e9dc10532a0357bc90ebaa2655b36822f9249673/cellulario/tier.py#L77-L93
241,491
mayfield/cellulario
cellulario/tier.py
Tier.enqueue_task
def enqueue_task(self, source, *args): """ Enqueue a task execution. It will run in the background as soon as the coordinator clears it to do so. """ yield from self.cell.coord.enqueue(self) route = Route(source, self.cell, self.spec, self.emit) self.cell.loop.create_task(self.coord_wrap(route, *args)) # To guarantee that the event loop works fluidly, we manually yield # once. The coordinator enqueue coroutine is not required to yield so # this ensures we avoid various forms of event starvation regardless. yield
python
def enqueue_task(self, source, *args): """ Enqueue a task execution. It will run in the background as soon as the coordinator clears it to do so. """ yield from self.cell.coord.enqueue(self) route = Route(source, self.cell, self.spec, self.emit) self.cell.loop.create_task(self.coord_wrap(route, *args)) # To guarantee that the event loop works fluidly, we manually yield # once. The coordinator enqueue coroutine is not required to yield so # this ensures we avoid various forms of event starvation regardless. yield
[ "def", "enqueue_task", "(", "self", ",", "source", ",", "*", "args", ")", ":", "yield", "from", "self", ".", "cell", ".", "coord", ".", "enqueue", "(", "self", ")", "route", "=", "Route", "(", "source", ",", "self", ".", "cell", ",", "self", ".", "spec", ",", "self", ".", "emit", ")", "self", ".", "cell", ".", "loop", ".", "create_task", "(", "self", ".", "coord_wrap", "(", "route", ",", "*", "args", ")", ")", "# To guarantee that the event loop works fluidly, we manually yield", "# once. The coordinator enqueue coroutine is not required to yield so", "# this ensures we avoid various forms of event starvation regardless.", "yield" ]
Enqueue a task execution. It will run in the background as soon as the coordinator clears it to do so.
[ "Enqueue", "a", "task", "execution", ".", "It", "will", "run", "in", "the", "background", "as", "soon", "as", "the", "coordinator", "clears", "it", "to", "do", "so", "." ]
e9dc10532a0357bc90ebaa2655b36822f9249673
https://github.com/mayfield/cellulario/blob/e9dc10532a0357bc90ebaa2655b36822f9249673/cellulario/tier.py#L132-L141
241,492
mayfield/cellulario
cellulario/tier.py
Tier.coord_wrap
def coord_wrap(self, *args): """ Wrap the coroutine with coordination throttles. """ yield from self.cell.coord.start(self) yield from self.coro(*args) yield from self.cell.coord.finish(self)
python
def coord_wrap(self, *args): """ Wrap the coroutine with coordination throttles. """ yield from self.cell.coord.start(self) yield from self.coro(*args) yield from self.cell.coord.finish(self)
[ "def", "coord_wrap", "(", "self", ",", "*", "args", ")", ":", "yield", "from", "self", ".", "cell", ".", "coord", ".", "start", "(", "self", ")", "yield", "from", "self", ".", "coro", "(", "*", "args", ")", "yield", "from", "self", ".", "cell", ".", "coord", ".", "finish", "(", "self", ")" ]
Wrap the coroutine with coordination throttles.
[ "Wrap", "the", "coroutine", "with", "coordination", "throttles", "." ]
e9dc10532a0357bc90ebaa2655b36822f9249673
https://github.com/mayfield/cellulario/blob/e9dc10532a0357bc90ebaa2655b36822f9249673/cellulario/tier.py#L144-L148
241,493
mayfield/cellulario
cellulario/tier.py
Tier.flush
def flush(self): """ Flush the buffer of buffered tiers to our destination tiers. """ if self.buffer is None: return data = self.buffer self.buffer = [] for x in self.dests: yield from x.enqueue_task(self, *data)
python
def flush(self): """ Flush the buffer of buffered tiers to our destination tiers. """ if self.buffer is None: return data = self.buffer self.buffer = [] for x in self.dests: yield from x.enqueue_task(self, *data)
[ "def", "flush", "(", "self", ")", ":", "if", "self", ".", "buffer", "is", "None", ":", "return", "data", "=", "self", ".", "buffer", "self", ".", "buffer", "=", "[", "]", "for", "x", "in", "self", ".", "dests", ":", "yield", "from", "x", ".", "enqueue_task", "(", "self", ",", "*", "data", ")" ]
Flush the buffer of buffered tiers to our destination tiers.
[ "Flush", "the", "buffer", "of", "buffered", "tiers", "to", "our", "destination", "tiers", "." ]
e9dc10532a0357bc90ebaa2655b36822f9249673
https://github.com/mayfield/cellulario/blob/e9dc10532a0357bc90ebaa2655b36822f9249673/cellulario/tier.py#L171-L178
241,494
mayfield/cellulario
cellulario/tier.py
Tier.add_source
def add_source(self, tier): """ Schedule this tier to be called when another tier emits. """ tier.add_dest(self) self.sources.append(tier)
python
def add_source(self, tier): """ Schedule this tier to be called when another tier emits. """ tier.add_dest(self) self.sources.append(tier)
[ "def", "add_source", "(", "self", ",", "tier", ")", ":", "tier", ".", "add_dest", "(", "self", ")", "self", ".", "sources", ".", "append", "(", "tier", ")" ]
Schedule this tier to be called when another tier emits.
[ "Schedule", "this", "tier", "to", "be", "called", "when", "another", "tier", "emits", "." ]
e9dc10532a0357bc90ebaa2655b36822f9249673
https://github.com/mayfield/cellulario/blob/e9dc10532a0357bc90ebaa2655b36822f9249673/cellulario/tier.py#L180-L183
241,495
mayfield/cellulario
cellulario/tier.py
Tier.close
def close(self): """ Free any potential cycles. """ self.cell = None self.coro = None self.buffer = None del self.dests[:] del self.sources[:]
python
def close(self): """ Free any potential cycles. """ self.cell = None self.coro = None self.buffer = None del self.dests[:] del self.sources[:]
[ "def", "close", "(", "self", ")", ":", "self", ".", "cell", "=", "None", "self", ".", "coro", "=", "None", "self", ".", "buffer", "=", "None", "del", "self", ".", "dests", "[", ":", "]", "del", "self", ".", "sources", "[", ":", "]" ]
Free any potential cycles.
[ "Free", "any", "potential", "cycles", "." ]
e9dc10532a0357bc90ebaa2655b36822f9249673
https://github.com/mayfield/cellulario/blob/e9dc10532a0357bc90ebaa2655b36822f9249673/cellulario/tier.py#L189-L195
241,496
diffeo/yakonfig
yakonfig/toplevel.py
add_arguments
def add_arguments(parser): '''Add command-line arguments for yakonfig proper. This is part of the :class:`~yakonfig.Configurable` interface, and is usually run by including :mod:`yakonfig` in the :func:`parse_args()` module list. :param argparse.ArgumentParser parser: command-line argument parser ''' parser.add_argument('--config', '-c', metavar='FILE', help='read configuration from FILE') parser.add_argument('--dump-config', metavar='WHAT', nargs='?', help='dump out configuration then stop ' '(default, effective, full)')
python
def add_arguments(parser): '''Add command-line arguments for yakonfig proper. This is part of the :class:`~yakonfig.Configurable` interface, and is usually run by including :mod:`yakonfig` in the :func:`parse_args()` module list. :param argparse.ArgumentParser parser: command-line argument parser ''' parser.add_argument('--config', '-c', metavar='FILE', help='read configuration from FILE') parser.add_argument('--dump-config', metavar='WHAT', nargs='?', help='dump out configuration then stop ' '(default, effective, full)')
[ "def", "add_arguments", "(", "parser", ")", ":", "parser", ".", "add_argument", "(", "'--config'", ",", "'-c'", ",", "metavar", "=", "'FILE'", ",", "help", "=", "'read configuration from FILE'", ")", "parser", ".", "add_argument", "(", "'--dump-config'", ",", "metavar", "=", "'WHAT'", ",", "nargs", "=", "'?'", ",", "help", "=", "'dump out configuration then stop '", "'(default, effective, full)'", ")" ]
Add command-line arguments for yakonfig proper. This is part of the :class:`~yakonfig.Configurable` interface, and is usually run by including :mod:`yakonfig` in the :func:`parse_args()` module list. :param argparse.ArgumentParser parser: command-line argument parser
[ "Add", "command", "-", "line", "arguments", "for", "yakonfig", "proper", "." ]
412e195da29b4f4fc7b72967c192714a6f5eaeb5
https://github.com/diffeo/yakonfig/blob/412e195da29b4f4fc7b72967c192714a6f5eaeb5/yakonfig/toplevel.py#L50-L65
241,497
diffeo/yakonfig
yakonfig/toplevel.py
parse_args
def parse_args(parser, modules, args=None): """Set up global configuration for command-line tools. `modules` is an iterable of :class:`yakonfig.Configurable` objects, or anything equivalently typed. This function iterates through those objects and calls :meth:`~yakonfig.Configurable.add_arguments` on each to build up a complete list of command-line arguments, then calls :meth:`argparse.ArgumentParser.parse_args` to actually process the command line. This produces a configuration that is a combination of all default values declared by all modules; configuration specified in ``--config`` arguments; and overriding configuration values specified in command-line arguments. This returns the :class:`argparse.Namespace` object, in case the application has defined its own command-line parameters and needs to process them. The new global configuration can be obtained via :func:`yakonfig.get_global_config`. :param argparse.ArgumentParser parser: application-provided argument parser :param modules: modules or Configurable instances to use :type modules: iterable of :class:`~yakonfig.Configurable` :param args: command-line options, or `None` to use `sys.argv` :return: the new global configuration """ collect_add_argparse(parser, modules) namespace = parser.parse_args(args) try: do_dump_config = getattr(namespace, 'dump_config', None) set_default_config(modules, params=vars(namespace), validate=not do_dump_config) if do_dump_config: if namespace.dump_config == 'full': to_dump = get_global_config() elif namespace.dump_config == 'default': to_dump = assemble_default_config(modules) else: # 'effective' to_dump = diff_config(assemble_default_config(modules), get_global_config()) yaml_mod.dump(to_dump, sys.stdout) parser.exit() except ConfigurationError as e: parser.error(e) return namespace
python
def parse_args(parser, modules, args=None): """Set up global configuration for command-line tools. `modules` is an iterable of :class:`yakonfig.Configurable` objects, or anything equivalently typed. This function iterates through those objects and calls :meth:`~yakonfig.Configurable.add_arguments` on each to build up a complete list of command-line arguments, then calls :meth:`argparse.ArgumentParser.parse_args` to actually process the command line. This produces a configuration that is a combination of all default values declared by all modules; configuration specified in ``--config`` arguments; and overriding configuration values specified in command-line arguments. This returns the :class:`argparse.Namespace` object, in case the application has defined its own command-line parameters and needs to process them. The new global configuration can be obtained via :func:`yakonfig.get_global_config`. :param argparse.ArgumentParser parser: application-provided argument parser :param modules: modules or Configurable instances to use :type modules: iterable of :class:`~yakonfig.Configurable` :param args: command-line options, or `None` to use `sys.argv` :return: the new global configuration """ collect_add_argparse(parser, modules) namespace = parser.parse_args(args) try: do_dump_config = getattr(namespace, 'dump_config', None) set_default_config(modules, params=vars(namespace), validate=not do_dump_config) if do_dump_config: if namespace.dump_config == 'full': to_dump = get_global_config() elif namespace.dump_config == 'default': to_dump = assemble_default_config(modules) else: # 'effective' to_dump = diff_config(assemble_default_config(modules), get_global_config()) yaml_mod.dump(to_dump, sys.stdout) parser.exit() except ConfigurationError as e: parser.error(e) return namespace
[ "def", "parse_args", "(", "parser", ",", "modules", ",", "args", "=", "None", ")", ":", "collect_add_argparse", "(", "parser", ",", "modules", ")", "namespace", "=", "parser", ".", "parse_args", "(", "args", ")", "try", ":", "do_dump_config", "=", "getattr", "(", "namespace", ",", "'dump_config'", ",", "None", ")", "set_default_config", "(", "modules", ",", "params", "=", "vars", "(", "namespace", ")", ",", "validate", "=", "not", "do_dump_config", ")", "if", "do_dump_config", ":", "if", "namespace", ".", "dump_config", "==", "'full'", ":", "to_dump", "=", "get_global_config", "(", ")", "elif", "namespace", ".", "dump_config", "==", "'default'", ":", "to_dump", "=", "assemble_default_config", "(", "modules", ")", "else", ":", "# 'effective'", "to_dump", "=", "diff_config", "(", "assemble_default_config", "(", "modules", ")", ",", "get_global_config", "(", ")", ")", "yaml_mod", ".", "dump", "(", "to_dump", ",", "sys", ".", "stdout", ")", "parser", ".", "exit", "(", ")", "except", "ConfigurationError", "as", "e", ":", "parser", ".", "error", "(", "e", ")", "return", "namespace" ]
Set up global configuration for command-line tools. `modules` is an iterable of :class:`yakonfig.Configurable` objects, or anything equivalently typed. This function iterates through those objects and calls :meth:`~yakonfig.Configurable.add_arguments` on each to build up a complete list of command-line arguments, then calls :meth:`argparse.ArgumentParser.parse_args` to actually process the command line. This produces a configuration that is a combination of all default values declared by all modules; configuration specified in ``--config`` arguments; and overriding configuration values specified in command-line arguments. This returns the :class:`argparse.Namespace` object, in case the application has defined its own command-line parameters and needs to process them. The new global configuration can be obtained via :func:`yakonfig.get_global_config`. :param argparse.ArgumentParser parser: application-provided argument parser :param modules: modules or Configurable instances to use :type modules: iterable of :class:`~yakonfig.Configurable` :param args: command-line options, or `None` to use `sys.argv` :return: the new global configuration
[ "Set", "up", "global", "configuration", "for", "command", "-", "line", "tools", "." ]
412e195da29b4f4fc7b72967c192714a6f5eaeb5
https://github.com/diffeo/yakonfig/blob/412e195da29b4f4fc7b72967c192714a6f5eaeb5/yakonfig/toplevel.py#L69-L115
241,498
diffeo/yakonfig
yakonfig/toplevel.py
set_default_config
def set_default_config(modules, params=None, yaml=None, filename=None, config=None, validate=True): """Set up global configuration for tests and noninteractive tools. `modules` is an iterable of :class:`yakonfig.Configurable` objects, or anything equivalently typed. This function iterates through those objects to produce a default configuration, reads `yaml` as though it were the configuration file, and fills in any values from `params` as though they were command-line arguments. The resulting configuration is set as the global configuration. :param modules: modules or Configurable instances to use :type modules: iterable of :class:`~yakonfig.Configurable` :param dict params: dictionary of command-line argument key to values :param str yaml: global configuration file :param str filename: location of global configuration file :param dict config: global configuration object :param bool validate: check configuration after creating :return: the new global configuration :returntype: dict """ if params is None: params = {} # Get the configuration from the file, or from params['config'] file_config = {} if yaml is None and filename is None and config is None: if 'config' in params and params['config'] is not None: filename = params['config'] if yaml is not None or filename is not None or config is not None: if yaml is not None: file_config = yaml_mod.load(StringIO(yaml)) elif filename is not None: with open(filename, 'r') as f: file_config = yaml_mod.load(f) elif config is not None: file_config = config # First pass: set up to call replace_config() # Assemble the configuration from defaults + file + arguments base_config = copy.deepcopy(file_config) create_config_tree(base_config, modules) fill_in_arguments(base_config, modules, params) default_config = assemble_default_config(modules) base_config = overlay_config(default_config, base_config) # Replace the modules list (accommodate external modules) def replace_module(config, m): name = getattr(m, 'config_name') c = config.get(name, {}) if hasattr(m, 'replace_config'): return getattr(m, 'replace_config')(c, name) return m modules = [replace_module(base_config, m) for m in modules] # Reassemble the configuration again, this time reaching out to # the environment base_config = file_config create_config_tree(base_config, modules) fill_in_arguments(base_config, modules, params) do_config_discovery(base_config, modules) default_config = assemble_default_config(modules) base_config = overlay_config(default_config, file_config) fill_in_arguments(base_config, modules, params) # Validate the configuration if validate and len(modules) > 0: mod = modules[-1] checker = getattr(mod, 'check_config', None) if checker is not None: with _temporary_config(): set_global_config(base_config) checker(base_config[mod.config_name], mod.config_name) # All done, normalize and set the global configuration normalize_config(base_config, modules) set_global_config(base_config) return base_config
python
def set_default_config(modules, params=None, yaml=None, filename=None, config=None, validate=True): """Set up global configuration for tests and noninteractive tools. `modules` is an iterable of :class:`yakonfig.Configurable` objects, or anything equivalently typed. This function iterates through those objects to produce a default configuration, reads `yaml` as though it were the configuration file, and fills in any values from `params` as though they were command-line arguments. The resulting configuration is set as the global configuration. :param modules: modules or Configurable instances to use :type modules: iterable of :class:`~yakonfig.Configurable` :param dict params: dictionary of command-line argument key to values :param str yaml: global configuration file :param str filename: location of global configuration file :param dict config: global configuration object :param bool validate: check configuration after creating :return: the new global configuration :returntype: dict """ if params is None: params = {} # Get the configuration from the file, or from params['config'] file_config = {} if yaml is None and filename is None and config is None: if 'config' in params and params['config'] is not None: filename = params['config'] if yaml is not None or filename is not None or config is not None: if yaml is not None: file_config = yaml_mod.load(StringIO(yaml)) elif filename is not None: with open(filename, 'r') as f: file_config = yaml_mod.load(f) elif config is not None: file_config = config # First pass: set up to call replace_config() # Assemble the configuration from defaults + file + arguments base_config = copy.deepcopy(file_config) create_config_tree(base_config, modules) fill_in_arguments(base_config, modules, params) default_config = assemble_default_config(modules) base_config = overlay_config(default_config, base_config) # Replace the modules list (accommodate external modules) def replace_module(config, m): name = getattr(m, 'config_name') c = config.get(name, {}) if hasattr(m, 'replace_config'): return getattr(m, 'replace_config')(c, name) return m modules = [replace_module(base_config, m) for m in modules] # Reassemble the configuration again, this time reaching out to # the environment base_config = file_config create_config_tree(base_config, modules) fill_in_arguments(base_config, modules, params) do_config_discovery(base_config, modules) default_config = assemble_default_config(modules) base_config = overlay_config(default_config, file_config) fill_in_arguments(base_config, modules, params) # Validate the configuration if validate and len(modules) > 0: mod = modules[-1] checker = getattr(mod, 'check_config', None) if checker is not None: with _temporary_config(): set_global_config(base_config) checker(base_config[mod.config_name], mod.config_name) # All done, normalize and set the global configuration normalize_config(base_config, modules) set_global_config(base_config) return base_config
[ "def", "set_default_config", "(", "modules", ",", "params", "=", "None", ",", "yaml", "=", "None", ",", "filename", "=", "None", ",", "config", "=", "None", ",", "validate", "=", "True", ")", ":", "if", "params", "is", "None", ":", "params", "=", "{", "}", "# Get the configuration from the file, or from params['config']", "file_config", "=", "{", "}", "if", "yaml", "is", "None", "and", "filename", "is", "None", "and", "config", "is", "None", ":", "if", "'config'", "in", "params", "and", "params", "[", "'config'", "]", "is", "not", "None", ":", "filename", "=", "params", "[", "'config'", "]", "if", "yaml", "is", "not", "None", "or", "filename", "is", "not", "None", "or", "config", "is", "not", "None", ":", "if", "yaml", "is", "not", "None", ":", "file_config", "=", "yaml_mod", ".", "load", "(", "StringIO", "(", "yaml", ")", ")", "elif", "filename", "is", "not", "None", ":", "with", "open", "(", "filename", ",", "'r'", ")", "as", "f", ":", "file_config", "=", "yaml_mod", ".", "load", "(", "f", ")", "elif", "config", "is", "not", "None", ":", "file_config", "=", "config", "# First pass: set up to call replace_config()", "# Assemble the configuration from defaults + file + arguments", "base_config", "=", "copy", ".", "deepcopy", "(", "file_config", ")", "create_config_tree", "(", "base_config", ",", "modules", ")", "fill_in_arguments", "(", "base_config", ",", "modules", ",", "params", ")", "default_config", "=", "assemble_default_config", "(", "modules", ")", "base_config", "=", "overlay_config", "(", "default_config", ",", "base_config", ")", "# Replace the modules list (accommodate external modules)", "def", "replace_module", "(", "config", ",", "m", ")", ":", "name", "=", "getattr", "(", "m", ",", "'config_name'", ")", "c", "=", "config", ".", "get", "(", "name", ",", "{", "}", ")", "if", "hasattr", "(", "m", ",", "'replace_config'", ")", ":", "return", "getattr", "(", "m", ",", "'replace_config'", ")", "(", "c", ",", "name", ")", "return", "m", "modules", "=", "[", "replace_module", "(", "base_config", ",", "m", ")", "for", "m", "in", "modules", "]", "# Reassemble the configuration again, this time reaching out to", "# the environment", "base_config", "=", "file_config", "create_config_tree", "(", "base_config", ",", "modules", ")", "fill_in_arguments", "(", "base_config", ",", "modules", ",", "params", ")", "do_config_discovery", "(", "base_config", ",", "modules", ")", "default_config", "=", "assemble_default_config", "(", "modules", ")", "base_config", "=", "overlay_config", "(", "default_config", ",", "file_config", ")", "fill_in_arguments", "(", "base_config", ",", "modules", ",", "params", ")", "# Validate the configuration", "if", "validate", "and", "len", "(", "modules", ")", ">", "0", ":", "mod", "=", "modules", "[", "-", "1", "]", "checker", "=", "getattr", "(", "mod", ",", "'check_config'", ",", "None", ")", "if", "checker", "is", "not", "None", ":", "with", "_temporary_config", "(", ")", ":", "set_global_config", "(", "base_config", ")", "checker", "(", "base_config", "[", "mod", ".", "config_name", "]", ",", "mod", ".", "config_name", ")", "# All done, normalize and set the global configuration", "normalize_config", "(", "base_config", ",", "modules", ")", "set_global_config", "(", "base_config", ")", "return", "base_config" ]
Set up global configuration for tests and noninteractive tools. `modules` is an iterable of :class:`yakonfig.Configurable` objects, or anything equivalently typed. This function iterates through those objects to produce a default configuration, reads `yaml` as though it were the configuration file, and fills in any values from `params` as though they were command-line arguments. The resulting configuration is set as the global configuration. :param modules: modules or Configurable instances to use :type modules: iterable of :class:`~yakonfig.Configurable` :param dict params: dictionary of command-line argument key to values :param str yaml: global configuration file :param str filename: location of global configuration file :param dict config: global configuration object :param bool validate: check configuration after creating :return: the new global configuration :returntype: dict
[ "Set", "up", "global", "configuration", "for", "tests", "and", "noninteractive", "tools", "." ]
412e195da29b4f4fc7b72967c192714a6f5eaeb5
https://github.com/diffeo/yakonfig/blob/412e195da29b4f4fc7b72967c192714a6f5eaeb5/yakonfig/toplevel.py#L118-L197
241,499
diffeo/yakonfig
yakonfig/toplevel.py
check_toplevel_config
def check_toplevel_config(what, who): """Verify that some dependent configuration is present and correct. This will generally be called from a :meth:`~yakonfig.Configurable.check_config` implementation. `what` is a :class:`~yakonfig.Configurable`-like object. If the corresponding configuration isn't present in the global configuration, raise a :exc:`yakonfig.ConfigurationError` explaining that `who` required it. Otherwise call that module's :meth:`~yakonfig.Configurable.check_config` (if any). :param yakonfig.Configurable what: top-level module to require :param str who: name of the requiring module :raise yakonfig.ConfigurationError: if configuration for `what` is missing or incorrect """ config_name = what.config_name config = get_global_config() if config_name not in config: raise ConfigurationError( '{0} requires top-level configuration for {1}' .format(who, config_name)) checker = getattr(what, 'check_config', None) if checker: checker(config[config_name], config_name)
python
def check_toplevel_config(what, who): """Verify that some dependent configuration is present and correct. This will generally be called from a :meth:`~yakonfig.Configurable.check_config` implementation. `what` is a :class:`~yakonfig.Configurable`-like object. If the corresponding configuration isn't present in the global configuration, raise a :exc:`yakonfig.ConfigurationError` explaining that `who` required it. Otherwise call that module's :meth:`~yakonfig.Configurable.check_config` (if any). :param yakonfig.Configurable what: top-level module to require :param str who: name of the requiring module :raise yakonfig.ConfigurationError: if configuration for `what` is missing or incorrect """ config_name = what.config_name config = get_global_config() if config_name not in config: raise ConfigurationError( '{0} requires top-level configuration for {1}' .format(who, config_name)) checker = getattr(what, 'check_config', None) if checker: checker(config[config_name], config_name)
[ "def", "check_toplevel_config", "(", "what", ",", "who", ")", ":", "config_name", "=", "what", ".", "config_name", "config", "=", "get_global_config", "(", ")", "if", "config_name", "not", "in", "config", ":", "raise", "ConfigurationError", "(", "'{0} requires top-level configuration for {1}'", ".", "format", "(", "who", ",", "config_name", ")", ")", "checker", "=", "getattr", "(", "what", ",", "'check_config'", ",", "None", ")", "if", "checker", ":", "checker", "(", "config", "[", "config_name", "]", ",", "config_name", ")" ]
Verify that some dependent configuration is present and correct. This will generally be called from a :meth:`~yakonfig.Configurable.check_config` implementation. `what` is a :class:`~yakonfig.Configurable`-like object. If the corresponding configuration isn't present in the global configuration, raise a :exc:`yakonfig.ConfigurationError` explaining that `who` required it. Otherwise call that module's :meth:`~yakonfig.Configurable.check_config` (if any). :param yakonfig.Configurable what: top-level module to require :param str who: name of the requiring module :raise yakonfig.ConfigurationError: if configuration for `what` is missing or incorrect
[ "Verify", "that", "some", "dependent", "configuration", "is", "present", "and", "correct", "." ]
412e195da29b4f4fc7b72967c192714a6f5eaeb5
https://github.com/diffeo/yakonfig/blob/412e195da29b4f4fc7b72967c192714a6f5eaeb5/yakonfig/toplevel.py#L234-L259