partition
stringclasses
3 values
func_name
stringlengths
1
134
docstring
stringlengths
1
46.9k
path
stringlengths
4
223
original_string
stringlengths
75
104k
code
stringlengths
75
104k
docstring_tokens
listlengths
1
1.97k
repo
stringlengths
7
55
language
stringclasses
1 value
url
stringlengths
87
315
code_tokens
listlengths
19
28.4k
sha
stringlengths
40
40
test
ServiceModules.import_modules
Import customer's service module.
ternya/modules.py
def import_modules(self): """Import customer's service module.""" modules = self.get_modules() log.info("import service modules: " + str(modules)) try: for module in modules: __import__(module) except ImportError as error: raise ImportModulesError(error.msg)
def import_modules(self): """Import customer's service module.""" modules = self.get_modules() log.info("import service modules: " + str(modules)) try: for module in modules: __import__(module) except ImportError as error: raise ImportModulesError(error.msg)
[ "Import", "customer", "s", "service", "module", "." ]
ndrlslz/ternya
python
https://github.com/ndrlslz/ternya/blob/c05aec10029e645d63ff04313dbcf2644743481f/ternya/modules.py#L50-L58
[ "def", "import_modules", "(", "self", ")", ":", "modules", "=", "self", ".", "get_modules", "(", ")", "log", ".", "info", "(", "\"import service modules: \"", "+", "str", "(", "modules", ")", ")", "try", ":", "for", "module", "in", "modules", ":", "__import__", "(", "module", ")", "except", "ImportError", "as", "error", ":", "raise", "ImportModulesError", "(", "error", ".", "msg", ")" ]
c05aec10029e645d63ff04313dbcf2644743481f
test
to_dates
This function takes a date string in various formats and converts it to a normalized and validated date range. A list with two elements is returned, lower and upper date boundary. Valid inputs are, for example: 2012 => Jan 1 20012 - Dec 31 2012 (whole year) 201201 => Jan 1 2012 - Jan 31 2012 (whole month) 2012101 => Jan 1 2012 - Jan 1 2012 (whole day) 2011-2011 => same as "2011", which means whole year 2012 2011-2012 => Jan 1 2011 - Dec 31 2012 (two years) 201104-2012 => Apr 1 2011 - Dec 31 2012 201104-201203 => Apr 1 2011 - March 31 2012 20110408-2011 => Apr 8 2011 - Dec 31 2011 20110408-201105 => Apr 8 2011 - May 31 2011 20110408-20110507 => Apr 8 2011 - May 07 2011 2011- => Jan 1 2012 - Dec 31 9999 (unlimited) 201104- => Apr 1 2011 - Dec 31 9999 (unlimited) 20110408- => Apr 8 2011 - Dec 31 9999 (unlimited) -2011 Jan 1 0000 - Dez 31 2011 -201104 Jan 1 0000 - Apr 30, 2011 -20110408 Jan 1 0000 - Apr 8, 2011
daterangestr.py
def to_dates(param): """ This function takes a date string in various formats and converts it to a normalized and validated date range. A list with two elements is returned, lower and upper date boundary. Valid inputs are, for example: 2012 => Jan 1 20012 - Dec 31 2012 (whole year) 201201 => Jan 1 2012 - Jan 31 2012 (whole month) 2012101 => Jan 1 2012 - Jan 1 2012 (whole day) 2011-2011 => same as "2011", which means whole year 2012 2011-2012 => Jan 1 2011 - Dec 31 2012 (two years) 201104-2012 => Apr 1 2011 - Dec 31 2012 201104-201203 => Apr 1 2011 - March 31 2012 20110408-2011 => Apr 8 2011 - Dec 31 2011 20110408-201105 => Apr 8 2011 - May 31 2011 20110408-20110507 => Apr 8 2011 - May 07 2011 2011- => Jan 1 2012 - Dec 31 9999 (unlimited) 201104- => Apr 1 2011 - Dec 31 9999 (unlimited) 20110408- => Apr 8 2011 - Dec 31 9999 (unlimited) -2011 Jan 1 0000 - Dez 31 2011 -201104 Jan 1 0000 - Apr 30, 2011 -20110408 Jan 1 0000 - Apr 8, 2011 """ pos = param.find('-') lower, upper = (None, None) if pos == -1: # no seperator given lower, upper = (param, param) else: lower, upper = param.split('-') ret = (expand_date_param(lower, 'lower'), expand_date_param(upper, 'upper')) return ret
def to_dates(param): """ This function takes a date string in various formats and converts it to a normalized and validated date range. A list with two elements is returned, lower and upper date boundary. Valid inputs are, for example: 2012 => Jan 1 20012 - Dec 31 2012 (whole year) 201201 => Jan 1 2012 - Jan 31 2012 (whole month) 2012101 => Jan 1 2012 - Jan 1 2012 (whole day) 2011-2011 => same as "2011", which means whole year 2012 2011-2012 => Jan 1 2011 - Dec 31 2012 (two years) 201104-2012 => Apr 1 2011 - Dec 31 2012 201104-201203 => Apr 1 2011 - March 31 2012 20110408-2011 => Apr 8 2011 - Dec 31 2011 20110408-201105 => Apr 8 2011 - May 31 2011 20110408-20110507 => Apr 8 2011 - May 07 2011 2011- => Jan 1 2012 - Dec 31 9999 (unlimited) 201104- => Apr 1 2011 - Dec 31 9999 (unlimited) 20110408- => Apr 8 2011 - Dec 31 9999 (unlimited) -2011 Jan 1 0000 - Dez 31 2011 -201104 Jan 1 0000 - Apr 30, 2011 -20110408 Jan 1 0000 - Apr 8, 2011 """ pos = param.find('-') lower, upper = (None, None) if pos == -1: # no seperator given lower, upper = (param, param) else: lower, upper = param.split('-') ret = (expand_date_param(lower, 'lower'), expand_date_param(upper, 'upper')) return ret
[ "This", "function", "takes", "a", "date", "string", "in", "various", "formats", "and", "converts", "it", "to", "a", "normalized", "and", "validated", "date", "range", ".", "A", "list", "with", "two", "elements", "is", "returned", "lower", "and", "upper", "date", "boundary", "." ]
marians/py-daterangestr
python
https://github.com/marians/py-daterangestr/blob/fa5dd78c8fea5f91a85bf732af8a0bc307641134/daterangestr.py#L33-L65
[ "def", "to_dates", "(", "param", ")", ":", "pos", "=", "param", ".", "find", "(", "'-'", ")", "lower", ",", "upper", "=", "(", "None", ",", "None", ")", "if", "pos", "==", "-", "1", ":", "# no seperator given", "lower", ",", "upper", "=", "(", "param", ",", "param", ")", "else", ":", "lower", ",", "upper", "=", "param", ".", "split", "(", "'-'", ")", "ret", "=", "(", "expand_date_param", "(", "lower", ",", "'lower'", ")", ",", "expand_date_param", "(", "upper", ",", "'upper'", ")", ")", "return", "ret" ]
fa5dd78c8fea5f91a85bf732af8a0bc307641134
test
expand_date_param
Expands a (possibly) incomplete date string to either the lowest or highest possible contained date and returns datetime.datetime for that string. 0753 (lower) => 0753-01-01 2012 (upper) => 2012-12-31 2012 (lower) => 2012-01-01 201208 (upper) => 2012-08-31 etc.
daterangestr.py
def expand_date_param(param, lower_upper): """ Expands a (possibly) incomplete date string to either the lowest or highest possible contained date and returns datetime.datetime for that string. 0753 (lower) => 0753-01-01 2012 (upper) => 2012-12-31 2012 (lower) => 2012-01-01 201208 (upper) => 2012-08-31 etc. """ year = datetime.MINYEAR month = 1 day = 1 hour = 0 minute = 0 second = 0 if lower_upper == 'upper': year = datetime.MAXYEAR month = 12 day = 31 hour = 23 minute = 59 second = 59 if len(param) == 0: # leave defaults pass elif len(param) == 4: year = int(param) if lower_upper == 'lower': month = 1 day = 1 hour = 0 minute = 0 second = 0 else: month = 12 day = 31 hour = 23 minute = 59 second = 59 elif len(param) == 6: year = int(param[0:4]) month = int(param[4:6]) if lower_upper == 'lower': day = 1 else: (firstday, dayspermonth) = monthrange(year, month) day = dayspermonth elif len(param) == 8: year = int(param[0:4]) month = int(param[4:6]) day = int(param[6:8]) elif len(param) == 10: year = int(param[0:4]) month = int(param[4:6]) day = int(param[6:8]) hour = int(param[8:10]) elif len(param) == 12: year = int(param[0:4]) month = int(param[4:6]) day = int(param[6:8]) hour = int(param[8:10]) minute = int(param[10:12]) elif len(param) == 14: year = int(param[0:4]) month = int(param[4:6]) day = int(param[6:8]) hour = int(param[8:10]) minute = int(param[10:12]) second = int(param[12:14]) else: # wrong input length raise ValueError('Bad date string provided. Use YYYY, YYYYMM or YYYYMMDD.') # force numbers into valid ranges #print (param, lower_upper), [year, month, day, hour, minute, second] year = min(datetime.MAXYEAR, max(datetime.MINYEAR, year)) return datetime.datetime(year=year, month=month, day=day, hour=hour, minute=minute, second=second)
def expand_date_param(param, lower_upper): """ Expands a (possibly) incomplete date string to either the lowest or highest possible contained date and returns datetime.datetime for that string. 0753 (lower) => 0753-01-01 2012 (upper) => 2012-12-31 2012 (lower) => 2012-01-01 201208 (upper) => 2012-08-31 etc. """ year = datetime.MINYEAR month = 1 day = 1 hour = 0 minute = 0 second = 0 if lower_upper == 'upper': year = datetime.MAXYEAR month = 12 day = 31 hour = 23 minute = 59 second = 59 if len(param) == 0: # leave defaults pass elif len(param) == 4: year = int(param) if lower_upper == 'lower': month = 1 day = 1 hour = 0 minute = 0 second = 0 else: month = 12 day = 31 hour = 23 minute = 59 second = 59 elif len(param) == 6: year = int(param[0:4]) month = int(param[4:6]) if lower_upper == 'lower': day = 1 else: (firstday, dayspermonth) = monthrange(year, month) day = dayspermonth elif len(param) == 8: year = int(param[0:4]) month = int(param[4:6]) day = int(param[6:8]) elif len(param) == 10: year = int(param[0:4]) month = int(param[4:6]) day = int(param[6:8]) hour = int(param[8:10]) elif len(param) == 12: year = int(param[0:4]) month = int(param[4:6]) day = int(param[6:8]) hour = int(param[8:10]) minute = int(param[10:12]) elif len(param) == 14: year = int(param[0:4]) month = int(param[4:6]) day = int(param[6:8]) hour = int(param[8:10]) minute = int(param[10:12]) second = int(param[12:14]) else: # wrong input length raise ValueError('Bad date string provided. Use YYYY, YYYYMM or YYYYMMDD.') # force numbers into valid ranges #print (param, lower_upper), [year, month, day, hour, minute, second] year = min(datetime.MAXYEAR, max(datetime.MINYEAR, year)) return datetime.datetime(year=year, month=month, day=day, hour=hour, minute=minute, second=second)
[ "Expands", "a", "(", "possibly", ")", "incomplete", "date", "string", "to", "either", "the", "lowest", "or", "highest", "possible", "contained", "date", "and", "returns", "datetime", ".", "datetime", "for", "that", "string", "." ]
marians/py-daterangestr
python
https://github.com/marians/py-daterangestr/blob/fa5dd78c8fea5f91a85bf732af8a0bc307641134/daterangestr.py#L68-L147
[ "def", "expand_date_param", "(", "param", ",", "lower_upper", ")", ":", "year", "=", "datetime", ".", "MINYEAR", "month", "=", "1", "day", "=", "1", "hour", "=", "0", "minute", "=", "0", "second", "=", "0", "if", "lower_upper", "==", "'upper'", ":", "year", "=", "datetime", ".", "MAXYEAR", "month", "=", "12", "day", "=", "31", "hour", "=", "23", "minute", "=", "59", "second", "=", "59", "if", "len", "(", "param", ")", "==", "0", ":", "# leave defaults", "pass", "elif", "len", "(", "param", ")", "==", "4", ":", "year", "=", "int", "(", "param", ")", "if", "lower_upper", "==", "'lower'", ":", "month", "=", "1", "day", "=", "1", "hour", "=", "0", "minute", "=", "0", "second", "=", "0", "else", ":", "month", "=", "12", "day", "=", "31", "hour", "=", "23", "minute", "=", "59", "second", "=", "59", "elif", "len", "(", "param", ")", "==", "6", ":", "year", "=", "int", "(", "param", "[", "0", ":", "4", "]", ")", "month", "=", "int", "(", "param", "[", "4", ":", "6", "]", ")", "if", "lower_upper", "==", "'lower'", ":", "day", "=", "1", "else", ":", "(", "firstday", ",", "dayspermonth", ")", "=", "monthrange", "(", "year", ",", "month", ")", "day", "=", "dayspermonth", "elif", "len", "(", "param", ")", "==", "8", ":", "year", "=", "int", "(", "param", "[", "0", ":", "4", "]", ")", "month", "=", "int", "(", "param", "[", "4", ":", "6", "]", ")", "day", "=", "int", "(", "param", "[", "6", ":", "8", "]", ")", "elif", "len", "(", "param", ")", "==", "10", ":", "year", "=", "int", "(", "param", "[", "0", ":", "4", "]", ")", "month", "=", "int", "(", "param", "[", "4", ":", "6", "]", ")", "day", "=", "int", "(", "param", "[", "6", ":", "8", "]", ")", "hour", "=", "int", "(", "param", "[", "8", ":", "10", "]", ")", "elif", "len", "(", "param", ")", "==", "12", ":", "year", "=", "int", "(", "param", "[", "0", ":", "4", "]", ")", "month", "=", "int", "(", "param", "[", "4", ":", "6", "]", ")", "day", "=", "int", "(", "param", "[", "6", ":", "8", "]", ")", "hour", "=", "int", "(", "param", "[", "8", ":", "10", "]", ")", "minute", "=", "int", "(", "param", "[", "10", ":", "12", "]", ")", "elif", "len", "(", "param", ")", "==", "14", ":", "year", "=", "int", "(", "param", "[", "0", ":", "4", "]", ")", "month", "=", "int", "(", "param", "[", "4", ":", "6", "]", ")", "day", "=", "int", "(", "param", "[", "6", ":", "8", "]", ")", "hour", "=", "int", "(", "param", "[", "8", ":", "10", "]", ")", "minute", "=", "int", "(", "param", "[", "10", ":", "12", "]", ")", "second", "=", "int", "(", "param", "[", "12", ":", "14", "]", ")", "else", ":", "# wrong input length", "raise", "ValueError", "(", "'Bad date string provided. Use YYYY, YYYYMM or YYYYMMDD.'", ")", "# force numbers into valid ranges", "#print (param, lower_upper), [year, month, day, hour, minute, second]", "year", "=", "min", "(", "datetime", ".", "MAXYEAR", ",", "max", "(", "datetime", ".", "MINYEAR", ",", "year", ")", ")", "return", "datetime", ".", "datetime", "(", "year", "=", "year", ",", "month", "=", "month", ",", "day", "=", "day", ",", "hour", "=", "hour", ",", "minute", "=", "minute", ",", "second", "=", "second", ")" ]
fa5dd78c8fea5f91a85bf732af8a0bc307641134
test
Doc_Formatter.select_fields
Take 'doc' and create a new doc using only keys from the 'fields' list. Supports referencing fields using dotted notation "a.b.c" so we can parse nested fields the way MongoDB does. The nested field class is a hack. It should be a sub-class of dict.
pymongo_formatter/formatter.py
def select_fields(doc, field_list): ''' Take 'doc' and create a new doc using only keys from the 'fields' list. Supports referencing fields using dotted notation "a.b.c" so we can parse nested fields the way MongoDB does. The nested field class is a hack. It should be a sub-class of dict. ''' if field_list is None or len(field_list) == 0: return doc newDoc = Nested_Dict({}) oldDoc = Nested_Dict(doc) for i in field_list: if oldDoc.has_key(i): # print( "doc: %s" % doc ) # print( "i: %s" %i ) newDoc.set_value(i, oldDoc.get_value(i)) return newDoc.dict_value()
def select_fields(doc, field_list): ''' Take 'doc' and create a new doc using only keys from the 'fields' list. Supports referencing fields using dotted notation "a.b.c" so we can parse nested fields the way MongoDB does. The nested field class is a hack. It should be a sub-class of dict. ''' if field_list is None or len(field_list) == 0: return doc newDoc = Nested_Dict({}) oldDoc = Nested_Dict(doc) for i in field_list: if oldDoc.has_key(i): # print( "doc: %s" % doc ) # print( "i: %s" %i ) newDoc.set_value(i, oldDoc.get_value(i)) return newDoc.dict_value()
[ "Take", "doc", "and", "create", "a", "new", "doc", "using", "only", "keys", "from", "the", "fields", "list", ".", "Supports", "referencing", "fields", "using", "dotted", "notation", "a", ".", "b", ".", "c", "so", "we", "can", "parse", "nested", "fields", "the", "way", "MongoDB", "does", ".", "The", "nested", "field", "class", "is", "a", "hack", ".", "It", "should", "be", "a", "sub", "-", "class", "of", "dict", "." ]
jdrumgoole/pymongo_formatter
python
https://github.com/jdrumgoole/pymongo_formatter/blob/313fef8f2ff5e7d4f1515ea59a99ec25f7999e7b/pymongo_formatter/formatter.py#L80-L99
[ "def", "select_fields", "(", "doc", ",", "field_list", ")", ":", "if", "field_list", "is", "None", "or", "len", "(", "field_list", ")", "==", "0", ":", "return", "doc", "newDoc", "=", "Nested_Dict", "(", "{", "}", ")", "oldDoc", "=", "Nested_Dict", "(", "doc", ")", "for", "i", "in", "field_list", ":", "if", "oldDoc", ".", "has_key", "(", "i", ")", ":", "# print( \"doc: %s\" % doc )", "# print( \"i: %s\" %i )", "newDoc", ".", "set_value", "(", "i", ",", "oldDoc", ".", "get_value", "(", "i", ")", ")", "return", "newDoc", ".", "dict_value", "(", ")" ]
313fef8f2ff5e7d4f1515ea59a99ec25f7999e7b
test
Doc_Formatter.date_map
For all the datetime fields in "datemap" find that key in doc and map the datetime object to a strftime string. This pprint and others will print out readable datetimes.
pymongo_formatter/formatter.py
def date_map(doc, datemap_list, time_format=None): ''' For all the datetime fields in "datemap" find that key in doc and map the datetime object to a strftime string. This pprint and others will print out readable datetimes. ''' if datemap_list: for i in datemap_list: if isinstance(i, datetime): doc=CursorFormatter.date_map_field(doc, i, time_format=time_format) return doc
def date_map(doc, datemap_list, time_format=None): ''' For all the datetime fields in "datemap" find that key in doc and map the datetime object to a strftime string. This pprint and others will print out readable datetimes. ''' if datemap_list: for i in datemap_list: if isinstance(i, datetime): doc=CursorFormatter.date_map_field(doc, i, time_format=time_format) return doc
[ "For", "all", "the", "datetime", "fields", "in", "datemap", "find", "that", "key", "in", "doc", "and", "map", "the", "datetime", "object", "to", "a", "strftime", "string", ".", "This", "pprint", "and", "others", "will", "print", "out", "readable", "datetimes", "." ]
jdrumgoole/pymongo_formatter
python
https://github.com/jdrumgoole/pymongo_formatter/blob/313fef8f2ff5e7d4f1515ea59a99ec25f7999e7b/pymongo_formatter/formatter.py#L102-L111
[ "def", "date_map", "(", "doc", ",", "datemap_list", ",", "time_format", "=", "None", ")", ":", "if", "datemap_list", ":", "for", "i", "in", "datemap_list", ":", "if", "isinstance", "(", "i", ",", "datetime", ")", ":", "doc", "=", "CursorFormatter", ".", "date_map_field", "(", "doc", ",", "i", ",", "time_format", "=", "time_format", ")", "return", "doc" ]
313fef8f2ff5e7d4f1515ea59a99ec25f7999e7b
test
CursorFormatter.printCursor
Output a cursor to a filename or stdout if filename is "-". fmt defines whether we output CSV or JSON.
pymongo_formatter/formatter.py
def printCursor(self, fieldnames=None, datemap=None, time_format=None): ''' Output a cursor to a filename or stdout if filename is "-". fmt defines whether we output CSV or JSON. ''' if self._format == 'csv': count = self.printCSVCursor(fieldnames, datemap, time_format) else: count = self.printJSONCursor( fieldnames, datemap, time_format) return count
def printCursor(self, fieldnames=None, datemap=None, time_format=None): ''' Output a cursor to a filename or stdout if filename is "-". fmt defines whether we output CSV or JSON. ''' if self._format == 'csv': count = self.printCSVCursor(fieldnames, datemap, time_format) else: count = self.printJSONCursor( fieldnames, datemap, time_format) return count
[ "Output", "a", "cursor", "to", "a", "filename", "or", "stdout", "if", "filename", "is", "-", ".", "fmt", "defines", "whether", "we", "output", "CSV", "or", "JSON", "." ]
jdrumgoole/pymongo_formatter
python
https://github.com/jdrumgoole/pymongo_formatter/blob/313fef8f2ff5e7d4f1515ea59a99ec25f7999e7b/pymongo_formatter/formatter.py#L216-L227
[ "def", "printCursor", "(", "self", ",", "fieldnames", "=", "None", ",", "datemap", "=", "None", ",", "time_format", "=", "None", ")", ":", "if", "self", ".", "_format", "==", "'csv'", ":", "count", "=", "self", ".", "printCSVCursor", "(", "fieldnames", ",", "datemap", ",", "time_format", ")", "else", ":", "count", "=", "self", ".", "printJSONCursor", "(", "fieldnames", ",", "datemap", ",", "time_format", ")", "return", "count" ]
313fef8f2ff5e7d4f1515ea59a99ec25f7999e7b
test
CursorFormatter.output
Output all fields using the fieldNames list. for fields in the list datemap indicates the field must be date
pymongo_formatter/formatter.py
def output(self, fieldNames=None, datemap=None, time_format=None): ''' Output all fields using the fieldNames list. for fields in the list datemap indicates the field must be date ''' count = self.printCursor(self._cursor, fieldNames, datemap, time_format)
def output(self, fieldNames=None, datemap=None, time_format=None): ''' Output all fields using the fieldNames list. for fields in the list datemap indicates the field must be date ''' count = self.printCursor(self._cursor, fieldNames, datemap, time_format)
[ "Output", "all", "fields", "using", "the", "fieldNames", "list", ".", "for", "fields", "in", "the", "list", "datemap", "indicates", "the", "field", "must", "be", "date" ]
jdrumgoole/pymongo_formatter
python
https://github.com/jdrumgoole/pymongo_formatter/blob/313fef8f2ff5e7d4f1515ea59a99ec25f7999e7b/pymongo_formatter/formatter.py#L229-L235
[ "def", "output", "(", "self", ",", "fieldNames", "=", "None", ",", "datemap", "=", "None", ",", "time_format", "=", "None", ")", ":", "count", "=", "self", ".", "printCursor", "(", "self", ".", "_cursor", ",", "fieldNames", ",", "datemap", ",", "time_format", ")" ]
313fef8f2ff5e7d4f1515ea59a99ec25f7999e7b
test
get_tasks
Given a list of tasks to perform and a dependency graph, return the tasks that must be performed, in the correct order
pub/pub.py
def get_tasks(do_tasks, dep_graph): """Given a list of tasks to perform and a dependency graph, return the tasks that must be performed, in the correct order""" #XXX: Is it important that if a task has "foo" before "bar" as a dep, # that foo executes before bar? Why? ATM this may not happen. #Each task that the user has specified gets its own execution graph task_graphs = [] for task in do_tasks: exgraph = DiGraph() exgraph.add_node(task) _get_deps(task, exgraph, dep_graph) task_graphs.append(exgraph) return flatten(reversed(topological_sort(g)) for g in task_graphs)
def get_tasks(do_tasks, dep_graph): """Given a list of tasks to perform and a dependency graph, return the tasks that must be performed, in the correct order""" #XXX: Is it important that if a task has "foo" before "bar" as a dep, # that foo executes before bar? Why? ATM this may not happen. #Each task that the user has specified gets its own execution graph task_graphs = [] for task in do_tasks: exgraph = DiGraph() exgraph.add_node(task) _get_deps(task, exgraph, dep_graph) task_graphs.append(exgraph) return flatten(reversed(topological_sort(g)) for g in task_graphs)
[ "Given", "a", "list", "of", "tasks", "to", "perform", "and", "a", "dependency", "graph", "return", "the", "tasks", "that", "must", "be", "performed", "in", "the", "correct", "order" ]
llimllib/pub
python
https://github.com/llimllib/pub/blob/bd8472f04800612c50cac0682a4aee0a441b1d56/pub/pub.py#L66-L83
[ "def", "get_tasks", "(", "do_tasks", ",", "dep_graph", ")", ":", "#XXX: Is it important that if a task has \"foo\" before \"bar\" as a dep,", "# that foo executes before bar? Why? ATM this may not happen.", "#Each task that the user has specified gets its own execution graph", "task_graphs", "=", "[", "]", "for", "task", "in", "do_tasks", ":", "exgraph", "=", "DiGraph", "(", ")", "exgraph", ".", "add_node", "(", "task", ")", "_get_deps", "(", "task", ",", "exgraph", ",", "dep_graph", ")", "task_graphs", ".", "append", "(", "exgraph", ")", "return", "flatten", "(", "reversed", "(", "topological_sort", "(", "g", ")", ")", "for", "g", "in", "task_graphs", ")" ]
bd8472f04800612c50cac0682a4aee0a441b1d56
test
rotate
Rotates a file. moves original file.ext to targetdir/file-YYYY-MM-DD-THH:MM:SS.ext deletes all older files matching the same pattern in targetdir that exceed the amount of max_versions. if versions = None, no old versions are deleted. if archive_dir is set, old versions are not deleted but moved to archive_dir
pyque/utils.py
def rotate(filename, targetdir, max_versions=None, archive_dir=None): """ Rotates a file. moves original file.ext to targetdir/file-YYYY-MM-DD-THH:MM:SS.ext deletes all older files matching the same pattern in targetdir that exceed the amount of max_versions. if versions = None, no old versions are deleted. if archive_dir is set, old versions are not deleted but moved to archive_dir """ dtimeformat = '%Y-%m-%d-%H:%M:%S' now = datetime.now().strftime(dtimeformat) old_path, old_filename = os.path.split(filename) fileroot, ext = old_filename.split(os.extsep, 1) new_filename = fileroot + '-' + now + '.' + ext new_filepath = os.path.join(targetdir, new_filename) if max_versions: # find all files with same pattern that already exist in targetdir old_files = {} for file in os.listdir(targetdir): pattern = re.compile( '^%s-(?P<date>\d{4}-\d{2}-\d{2}-\d{2}:\d{2}:\d{2}).%s' % (fileroot, ext)) if pattern.match(file): d = re.search(pattern, file).group('date') old_files[d] = file delkeys = old_files.keys() # sort delkeys by date, newest first delkeys.sort(key=lambda x: datetime.strptime(x, dtimeformat), reverse=True) # delete all keys, that should not be deleted del delkeys[0 : max_versions -1] # delete all not needed files for k in delkeys: fname = old_files[k] fpath = os.path.join(targetdir, fname) if archive_dir: shutil.move(fpath, os.path.join(archive_dir, fname)) else: os.remove(fpath) shutil.move(filename, new_filepath) pass else: shutil.move(filename, new_filepath) return True
def rotate(filename, targetdir, max_versions=None, archive_dir=None): """ Rotates a file. moves original file.ext to targetdir/file-YYYY-MM-DD-THH:MM:SS.ext deletes all older files matching the same pattern in targetdir that exceed the amount of max_versions. if versions = None, no old versions are deleted. if archive_dir is set, old versions are not deleted but moved to archive_dir """ dtimeformat = '%Y-%m-%d-%H:%M:%S' now = datetime.now().strftime(dtimeformat) old_path, old_filename = os.path.split(filename) fileroot, ext = old_filename.split(os.extsep, 1) new_filename = fileroot + '-' + now + '.' + ext new_filepath = os.path.join(targetdir, new_filename) if max_versions: # find all files with same pattern that already exist in targetdir old_files = {} for file in os.listdir(targetdir): pattern = re.compile( '^%s-(?P<date>\d{4}-\d{2}-\d{2}-\d{2}:\d{2}:\d{2}).%s' % (fileroot, ext)) if pattern.match(file): d = re.search(pattern, file).group('date') old_files[d] = file delkeys = old_files.keys() # sort delkeys by date, newest first delkeys.sort(key=lambda x: datetime.strptime(x, dtimeformat), reverse=True) # delete all keys, that should not be deleted del delkeys[0 : max_versions -1] # delete all not needed files for k in delkeys: fname = old_files[k] fpath = os.path.join(targetdir, fname) if archive_dir: shutil.move(fpath, os.path.join(archive_dir, fname)) else: os.remove(fpath) shutil.move(filename, new_filepath) pass else: shutil.move(filename, new_filepath) return True
[ "Rotates", "a", "file", ".", "moves", "original", "file", ".", "ext", "to", "targetdir", "/", "file", "-", "YYYY", "-", "MM", "-", "DD", "-", "THH", ":", "MM", ":", "SS", ".", "ext" ]
bmaeser/pyque
python
https://github.com/bmaeser/pyque/blob/856dceab8d89cf3771cf21e682466c29a85ae8eb/pyque/utils.py#L11-L68
[ "def", "rotate", "(", "filename", ",", "targetdir", ",", "max_versions", "=", "None", ",", "archive_dir", "=", "None", ")", ":", "dtimeformat", "=", "'%Y-%m-%d-%H:%M:%S'", "now", "=", "datetime", ".", "now", "(", ")", ".", "strftime", "(", "dtimeformat", ")", "old_path", ",", "old_filename", "=", "os", ".", "path", ".", "split", "(", "filename", ")", "fileroot", ",", "ext", "=", "old_filename", ".", "split", "(", "os", ".", "extsep", ",", "1", ")", "new_filename", "=", "fileroot", "+", "'-'", "+", "now", "+", "'.'", "+", "ext", "new_filepath", "=", "os", ".", "path", ".", "join", "(", "targetdir", ",", "new_filename", ")", "if", "max_versions", ":", "# find all files with same pattern that already exist in targetdir", "old_files", "=", "{", "}", "for", "file", "in", "os", ".", "listdir", "(", "targetdir", ")", ":", "pattern", "=", "re", ".", "compile", "(", "'^%s-(?P<date>\\d{4}-\\d{2}-\\d{2}-\\d{2}:\\d{2}:\\d{2}).%s'", "%", "(", "fileroot", ",", "ext", ")", ")", "if", "pattern", ".", "match", "(", "file", ")", ":", "d", "=", "re", ".", "search", "(", "pattern", ",", "file", ")", ".", "group", "(", "'date'", ")", "old_files", "[", "d", "]", "=", "file", "delkeys", "=", "old_files", ".", "keys", "(", ")", "# sort delkeys by date, newest first", "delkeys", ".", "sort", "(", "key", "=", "lambda", "x", ":", "datetime", ".", "strptime", "(", "x", ",", "dtimeformat", ")", ",", "reverse", "=", "True", ")", "# delete all keys, that should not be deleted", "del", "delkeys", "[", "0", ":", "max_versions", "-", "1", "]", "# delete all not needed files", "for", "k", "in", "delkeys", ":", "fname", "=", "old_files", "[", "k", "]", "fpath", "=", "os", ".", "path", ".", "join", "(", "targetdir", ",", "fname", ")", "if", "archive_dir", ":", "shutil", ".", "move", "(", "fpath", ",", "os", ".", "path", ".", "join", "(", "archive_dir", ",", "fname", ")", ")", "else", ":", "os", ".", "remove", "(", "fpath", ")", "shutil", ".", "move", "(", "filename", ",", "new_filepath", ")", "pass", "else", ":", "shutil", ".", "move", "(", "filename", ",", "new_filepath", ")", "return", "True" ]
856dceab8d89cf3771cf21e682466c29a85ae8eb
test
api_request
View decorator that handles JSON based API requests and responses consistently. :param methods: A list of allowed methods :param require_token: Whether API token is checked automatically or not
customary/api/__init__.py
def api_request(methods=None, require_token=True): """ View decorator that handles JSON based API requests and responses consistently. :param methods: A list of allowed methods :param require_token: Whether API token is checked automatically or not """ def decorator(view_func): @wraps(view_func, assigned=available_attrs(view_func)) def _wrapped_view(request, *args, **kwargs): ApiToken = apps.get_model('api', 'ApiToken') m = methods if methods is not None else DEFAULT_API_METHODS if request.method not in m: response = ApiResponse(False, 'Method not supported', status=405) response['Allow'] = ', '.join(methods) return response try: data = json.loads(request.body.decode('utf-8')) if request.body else {} if require_token: token_string = request.GET['token'] if request.method == 'GET' else data['token'] try: token = ApiToken.objects.get(token=token_string) token.save() # Update the last_seen field data['token'] = token except ApiToken.DoesNotExist: logger.exception('Valid token required, "{0}" supplied'.format(token_string)) return ApiResponse(False, 'Valid token required', status=403) return ApiResponse(data=view_func(request, data=data, *args, **kwargs)) except Exception as e: if e.__class__.__name__ == 'DoesNotExist': logger.exception('Not found while handling ajax request') return ApiResponse(False, 'Exception: {0}'.format(e), status=404) else: logger.exception('Error handling ajax request') return ApiResponse(False, 'Exception: {0}'.format(e), status=500) return _wrapped_view return decorator
def api_request(methods=None, require_token=True): """ View decorator that handles JSON based API requests and responses consistently. :param methods: A list of allowed methods :param require_token: Whether API token is checked automatically or not """ def decorator(view_func): @wraps(view_func, assigned=available_attrs(view_func)) def _wrapped_view(request, *args, **kwargs): ApiToken = apps.get_model('api', 'ApiToken') m = methods if methods is not None else DEFAULT_API_METHODS if request.method not in m: response = ApiResponse(False, 'Method not supported', status=405) response['Allow'] = ', '.join(methods) return response try: data = json.loads(request.body.decode('utf-8')) if request.body else {} if require_token: token_string = request.GET['token'] if request.method == 'GET' else data['token'] try: token = ApiToken.objects.get(token=token_string) token.save() # Update the last_seen field data['token'] = token except ApiToken.DoesNotExist: logger.exception('Valid token required, "{0}" supplied'.format(token_string)) return ApiResponse(False, 'Valid token required', status=403) return ApiResponse(data=view_func(request, data=data, *args, **kwargs)) except Exception as e: if e.__class__.__name__ == 'DoesNotExist': logger.exception('Not found while handling ajax request') return ApiResponse(False, 'Exception: {0}'.format(e), status=404) else: logger.exception('Error handling ajax request') return ApiResponse(False, 'Exception: {0}'.format(e), status=500) return _wrapped_view return decorator
[ "View", "decorator", "that", "handles", "JSON", "based", "API", "requests", "and", "responses", "consistently", ".", ":", "param", "methods", ":", "A", "list", "of", "allowed", "methods", ":", "param", "require_token", ":", "Whether", "API", "token", "is", "checked", "automatically", "or", "not" ]
precond/django-customary
python
https://github.com/precond/django-customary/blob/2cf2295d84d3d1bb6c034d4df25e15d814c1eb75/customary/api/__init__.py#L20-L60
[ "def", "api_request", "(", "methods", "=", "None", ",", "require_token", "=", "True", ")", ":", "def", "decorator", "(", "view_func", ")", ":", "@", "wraps", "(", "view_func", ",", "assigned", "=", "available_attrs", "(", "view_func", ")", ")", "def", "_wrapped_view", "(", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "ApiToken", "=", "apps", ".", "get_model", "(", "'api'", ",", "'ApiToken'", ")", "m", "=", "methods", "if", "methods", "is", "not", "None", "else", "DEFAULT_API_METHODS", "if", "request", ".", "method", "not", "in", "m", ":", "response", "=", "ApiResponse", "(", "False", ",", "'Method not supported'", ",", "status", "=", "405", ")", "response", "[", "'Allow'", "]", "=", "', '", ".", "join", "(", "methods", ")", "return", "response", "try", ":", "data", "=", "json", ".", "loads", "(", "request", ".", "body", ".", "decode", "(", "'utf-8'", ")", ")", "if", "request", ".", "body", "else", "{", "}", "if", "require_token", ":", "token_string", "=", "request", ".", "GET", "[", "'token'", "]", "if", "request", ".", "method", "==", "'GET'", "else", "data", "[", "'token'", "]", "try", ":", "token", "=", "ApiToken", ".", "objects", ".", "get", "(", "token", "=", "token_string", ")", "token", ".", "save", "(", ")", "# Update the last_seen field", "data", "[", "'token'", "]", "=", "token", "except", "ApiToken", ".", "DoesNotExist", ":", "logger", ".", "exception", "(", "'Valid token required, \"{0}\" supplied'", ".", "format", "(", "token_string", ")", ")", "return", "ApiResponse", "(", "False", ",", "'Valid token required'", ",", "status", "=", "403", ")", "return", "ApiResponse", "(", "data", "=", "view_func", "(", "request", ",", "data", "=", "data", ",", "*", "args", ",", "*", "*", "kwargs", ")", ")", "except", "Exception", "as", "e", ":", "if", "e", ".", "__class__", ".", "__name__", "==", "'DoesNotExist'", ":", "logger", ".", "exception", "(", "'Not found while handling ajax request'", ")", "return", "ApiResponse", "(", "False", ",", "'Exception: {0}'", ".", "format", "(", "e", ")", ",", "status", "=", "404", ")", "else", ":", "logger", ".", "exception", "(", "'Error handling ajax request'", ")", "return", "ApiResponse", "(", "False", ",", "'Exception: {0}'", ".", "format", "(", "e", ")", ",", "status", "=", "500", ")", "return", "_wrapped_view", "return", "decorator" ]
2cf2295d84d3d1bb6c034d4df25e15d814c1eb75
test
add_default_deps
Add or create the default departments for the given project :param project: the project that needs default departments :type project: :class:`muke.models.Project` :returns: None :rtype: None :raises: None
src/jukedj/models.py
def add_default_deps(project): """Add or create the default departments for the given project :param project: the project that needs default departments :type project: :class:`muke.models.Project` :returns: None :rtype: None :raises: None """ # create deps for project for name, short, order, af in DEFAULT_DEPARTMENTS: dep, created = Department.objects.get_or_create(name=name, short=short, ordervalue=order, assetflag=af) dep.projects.add(project) dep.full_clean() dep.save()
def add_default_deps(project): """Add or create the default departments for the given project :param project: the project that needs default departments :type project: :class:`muke.models.Project` :returns: None :rtype: None :raises: None """ # create deps for project for name, short, order, af in DEFAULT_DEPARTMENTS: dep, created = Department.objects.get_or_create(name=name, short=short, ordervalue=order, assetflag=af) dep.projects.add(project) dep.full_clean() dep.save()
[ "Add", "or", "create", "the", "default", "departments", "for", "the", "given", "project" ]
JukeboxPipeline/jukedj
python
https://github.com/JukeboxPipeline/jukedj/blob/d4159961c819c26792a278981ee68106ee15f3f3/src/jukedj/models.py#L366-L380
[ "def", "add_default_deps", "(", "project", ")", ":", "# create deps for project", "for", "name", ",", "short", ",", "order", ",", "af", "in", "DEFAULT_DEPARTMENTS", ":", "dep", ",", "created", "=", "Department", ".", "objects", ".", "get_or_create", "(", "name", "=", "name", ",", "short", "=", "short", ",", "ordervalue", "=", "order", ",", "assetflag", "=", "af", ")", "dep", ".", "projects", ".", "add", "(", "project", ")", "dep", ".", "full_clean", "(", ")", "dep", ".", "save", "(", ")" ]
d4159961c819c26792a278981ee68106ee15f3f3
test
add_default_atypes
Add or create the default assettypes for the given project :param project: the project that needs default assettypes :type project: :class:`muke.models.Project` :returns: None :rtype: None :raises: None
src/jukedj/models.py
def add_default_atypes(project): """Add or create the default assettypes for the given project :param project: the project that needs default assettypes :type project: :class:`muke.models.Project` :returns: None :rtype: None :raises: None """ # create assettypes for project for name, desc in DEFAULT_ASSETTYPES: at, created = Atype.objects.get_or_create(name=name, defaults={'description': desc}) at.projects.add(project) at.full_clean() at.save()
def add_default_atypes(project): """Add or create the default assettypes for the given project :param project: the project that needs default assettypes :type project: :class:`muke.models.Project` :returns: None :rtype: None :raises: None """ # create assettypes for project for name, desc in DEFAULT_ASSETTYPES: at, created = Atype.objects.get_or_create(name=name, defaults={'description': desc}) at.projects.add(project) at.full_clean() at.save()
[ "Add", "or", "create", "the", "default", "assettypes", "for", "the", "given", "project" ]
JukeboxPipeline/jukedj
python
https://github.com/JukeboxPipeline/jukedj/blob/d4159961c819c26792a278981ee68106ee15f3f3/src/jukedj/models.py#L383-L397
[ "def", "add_default_atypes", "(", "project", ")", ":", "# create assettypes for project", "for", "name", ",", "desc", "in", "DEFAULT_ASSETTYPES", ":", "at", ",", "created", "=", "Atype", ".", "objects", ".", "get_or_create", "(", "name", "=", "name", ",", "defaults", "=", "{", "'description'", ":", "desc", "}", ")", "at", ".", "projects", ".", "add", "(", "project", ")", "at", ".", "full_clean", "(", ")", "at", ".", "save", "(", ")" ]
d4159961c819c26792a278981ee68106ee15f3f3
test
add_default_sequences
Add or create the default sequences for the given project :param project: the project that needs default sequences :type project: :class:`muke.models.Project` :returns: None :rtype: None :raises: None
src/jukedj/models.py
def add_default_sequences(project): """Add or create the default sequences for the given project :param project: the project that needs default sequences :type project: :class:`muke.models.Project` :returns: None :rtype: None :raises: None """ # create sequences for project seqs = [(GLOBAL_NAME, 'global sequence for project %s' % project.name), (RNDSEQ_NAME, 'research and development sequence for project %s' % project.name)] for name, desc in seqs: seq, created = Sequence.objects.get_or_create(name=name, project=project, defaults={'description': desc})
def add_default_sequences(project): """Add or create the default sequences for the given project :param project: the project that needs default sequences :type project: :class:`muke.models.Project` :returns: None :rtype: None :raises: None """ # create sequences for project seqs = [(GLOBAL_NAME, 'global sequence for project %s' % project.name), (RNDSEQ_NAME, 'research and development sequence for project %s' % project.name)] for name, desc in seqs: seq, created = Sequence.objects.get_or_create(name=name, project=project, defaults={'description': desc})
[ "Add", "or", "create", "the", "default", "sequences", "for", "the", "given", "project" ]
JukeboxPipeline/jukedj
python
https://github.com/JukeboxPipeline/jukedj/blob/d4159961c819c26792a278981ee68106ee15f3f3/src/jukedj/models.py#L400-L413
[ "def", "add_default_sequences", "(", "project", ")", ":", "# create sequences for project", "seqs", "=", "[", "(", "GLOBAL_NAME", ",", "'global sequence for project %s'", "%", "project", ".", "name", ")", ",", "(", "RNDSEQ_NAME", ",", "'research and development sequence for project %s'", "%", "project", ".", "name", ")", "]", "for", "name", ",", "desc", "in", "seqs", ":", "seq", ",", "created", "=", "Sequence", ".", "objects", ".", "get_or_create", "(", "name", "=", "name", ",", "project", "=", "project", ",", "defaults", "=", "{", "'description'", ":", "desc", "}", ")" ]
d4159961c819c26792a278981ee68106ee15f3f3
test
add_userrnd_shot
Add a rnd shot for every user in the project :param project: the project that needs its rnd shots updated :type project: :class:`muke.models.Project` :returns: None :rtype: None :raises: None
src/jukedj/models.py
def add_userrnd_shot(project): """Add a rnd shot for every user in the project :param project: the project that needs its rnd shots updated :type project: :class:`muke.models.Project` :returns: None :rtype: None :raises: None """ rndseq = project.sequence_set.get(name=RNDSEQ_NAME) users = [u for u in project.users.all()] for user in users: shot, created = Shot.objects.get_or_create(name=user.username, project=project, sequence=rndseq, defaults={'description': 'rnd shot for user %s' % user.username}) for t in shot.tasks.all(): t.users.add(user) t.full_clean() t.save()
def add_userrnd_shot(project): """Add a rnd shot for every user in the project :param project: the project that needs its rnd shots updated :type project: :class:`muke.models.Project` :returns: None :rtype: None :raises: None """ rndseq = project.sequence_set.get(name=RNDSEQ_NAME) users = [u for u in project.users.all()] for user in users: shot, created = Shot.objects.get_or_create(name=user.username, project=project, sequence=rndseq, defaults={'description': 'rnd shot for user %s' % user.username}) for t in shot.tasks.all(): t.users.add(user) t.full_clean() t.save()
[ "Add", "a", "rnd", "shot", "for", "every", "user", "in", "the", "project" ]
JukeboxPipeline/jukedj
python
https://github.com/JukeboxPipeline/jukedj/blob/d4159961c819c26792a278981ee68106ee15f3f3/src/jukedj/models.py#L416-L435
[ "def", "add_userrnd_shot", "(", "project", ")", ":", "rndseq", "=", "project", ".", "sequence_set", ".", "get", "(", "name", "=", "RNDSEQ_NAME", ")", "users", "=", "[", "u", "for", "u", "in", "project", ".", "users", ".", "all", "(", ")", "]", "for", "user", "in", "users", ":", "shot", ",", "created", "=", "Shot", ".", "objects", ".", "get_or_create", "(", "name", "=", "user", ".", "username", ",", "project", "=", "project", ",", "sequence", "=", "rndseq", ",", "defaults", "=", "{", "'description'", ":", "'rnd shot for user %s'", "%", "user", ".", "username", "}", ")", "for", "t", "in", "shot", ".", "tasks", ".", "all", "(", ")", ":", "t", ".", "users", ".", "add", "(", "user", ")", "t", ".", "full_clean", "(", ")", "t", ".", "save", "(", ")" ]
d4159961c819c26792a278981ee68106ee15f3f3
test
prj_post_save_handler
Post save receiver for when a Project is saved. Creates a rnd shot for every user. On creations does: 1. create all default departments 2. create all default assettypes 3. create all default sequences :param sender: the project class :type sender: :class:`muke.models.Project` :returns: None :raises: None
src/jukedj/models.py
def prj_post_save_handler(sender, **kwargs): """ Post save receiver for when a Project is saved. Creates a rnd shot for every user. On creations does: 1. create all default departments 2. create all default assettypes 3. create all default sequences :param sender: the project class :type sender: :class:`muke.models.Project` :returns: None :raises: None """ prj = kwargs['instance'] if not kwargs['created']: add_userrnd_shot(prj) return add_default_deps(prj) add_default_atypes(prj) add_default_sequences(prj)
def prj_post_save_handler(sender, **kwargs): """ Post save receiver for when a Project is saved. Creates a rnd shot for every user. On creations does: 1. create all default departments 2. create all default assettypes 3. create all default sequences :param sender: the project class :type sender: :class:`muke.models.Project` :returns: None :raises: None """ prj = kwargs['instance'] if not kwargs['created']: add_userrnd_shot(prj) return add_default_deps(prj) add_default_atypes(prj) add_default_sequences(prj)
[ "Post", "save", "receiver", "for", "when", "a", "Project", "is", "saved", "." ]
JukeboxPipeline/jukedj
python
https://github.com/JukeboxPipeline/jukedj/blob/d4159961c819c26792a278981ee68106ee15f3f3/src/jukedj/models.py#L439-L463
[ "def", "prj_post_save_handler", "(", "sender", ",", "*", "*", "kwargs", ")", ":", "prj", "=", "kwargs", "[", "'instance'", "]", "if", "not", "kwargs", "[", "'created'", "]", ":", "add_userrnd_shot", "(", "prj", ")", "return", "add_default_deps", "(", "prj", ")", "add_default_atypes", "(", "prj", ")", "add_default_sequences", "(", "prj", ")" ]
d4159961c819c26792a278981ee68106ee15f3f3
test
seq_post_save_handler
Post save receiver for when a sequence is saved. creates a global shot. :param sender: the sequence class :type sender: :class:`muke.models.Sequence` :returns: None :raises: None
src/jukedj/models.py
def seq_post_save_handler(sender, **kwargs): """ Post save receiver for when a sequence is saved. creates a global shot. :param sender: the sequence class :type sender: :class:`muke.models.Sequence` :returns: None :raises: None """ if not kwargs['created']: return seq = kwargs['instance'] if seq.name == RNDSEQ_NAME: return prj = seq.project name = GLOBAL_NAME desc = "Global shot for sequence %s" % seq.name Shot.objects.create(name=name, project=prj, sequence=seq, description=desc)
def seq_post_save_handler(sender, **kwargs): """ Post save receiver for when a sequence is saved. creates a global shot. :param sender: the sequence class :type sender: :class:`muke.models.Sequence` :returns: None :raises: None """ if not kwargs['created']: return seq = kwargs['instance'] if seq.name == RNDSEQ_NAME: return prj = seq.project name = GLOBAL_NAME desc = "Global shot for sequence %s" % seq.name Shot.objects.create(name=name, project=prj, sequence=seq, description=desc)
[ "Post", "save", "receiver", "for", "when", "a", "sequence", "is", "saved", "." ]
JukeboxPipeline/jukedj
python
https://github.com/JukeboxPipeline/jukedj/blob/d4159961c819c26792a278981ee68106ee15f3f3/src/jukedj/models.py#L467-L487
[ "def", "seq_post_save_handler", "(", "sender", ",", "*", "*", "kwargs", ")", ":", "if", "not", "kwargs", "[", "'created'", "]", ":", "return", "seq", "=", "kwargs", "[", "'instance'", "]", "if", "seq", ".", "name", "==", "RNDSEQ_NAME", ":", "return", "prj", "=", "seq", ".", "project", "name", "=", "GLOBAL_NAME", "desc", "=", "\"Global shot for sequence %s\"", "%", "seq", ".", "name", "Shot", ".", "objects", ".", "create", "(", "name", "=", "name", ",", "project", "=", "prj", ",", "sequence", "=", "seq", ",", "description", "=", "desc", ")" ]
d4159961c819c26792a278981ee68106ee15f3f3
test
create_all_tasks
Create all tasks for the element :param element: The shot or asset that needs tasks :type element: :class:`muke.models.Shot` | :class:`muke.models.Asset` :returns: None :rtype: None :raises: None
src/jukedj/models.py
def create_all_tasks(element): """Create all tasks for the element :param element: The shot or asset that needs tasks :type element: :class:`muke.models.Shot` | :class:`muke.models.Asset` :returns: None :rtype: None :raises: None """ prj = element.project if isinstance(element, Asset): flag=True else: flag=False deps = prj.department_set.filter(assetflag=flag) for d in deps: t = Task(project=prj, department=d, element=element) t.full_clean() t.save()
def create_all_tasks(element): """Create all tasks for the element :param element: The shot or asset that needs tasks :type element: :class:`muke.models.Shot` | :class:`muke.models.Asset` :returns: None :rtype: None :raises: None """ prj = element.project if isinstance(element, Asset): flag=True else: flag=False deps = prj.department_set.filter(assetflag=flag) for d in deps: t = Task(project=prj, department=d, element=element) t.full_clean() t.save()
[ "Create", "all", "tasks", "for", "the", "element" ]
JukeboxPipeline/jukedj
python
https://github.com/JukeboxPipeline/jukedj/blob/d4159961c819c26792a278981ee68106ee15f3f3/src/jukedj/models.py#L490-L508
[ "def", "create_all_tasks", "(", "element", ")", ":", "prj", "=", "element", ".", "project", "if", "isinstance", "(", "element", ",", "Asset", ")", ":", "flag", "=", "True", "else", ":", "flag", "=", "False", "deps", "=", "prj", ".", "department_set", ".", "filter", "(", "assetflag", "=", "flag", ")", "for", "d", "in", "deps", ":", "t", "=", "Task", "(", "project", "=", "prj", ",", "department", "=", "d", ",", "element", "=", "element", ")", "t", ".", "full_clean", "(", ")", "t", ".", "save", "(", ")" ]
d4159961c819c26792a278981ee68106ee15f3f3
test
Project.path
Return path :returns: path :rtype: str :raises: None
src/jukedj/models.py
def path(self): """Return path :returns: path :rtype: str :raises: None """ p = os.path.normpath(self._path) if p.endswith(':'): p = p + os.path.sep return p
def path(self): """Return path :returns: path :rtype: str :raises: None """ p = os.path.normpath(self._path) if p.endswith(':'): p = p + os.path.sep return p
[ "Return", "path" ]
JukeboxPipeline/jukedj
python
https://github.com/JukeboxPipeline/jukedj/blob/d4159961c819c26792a278981ee68106ee15f3f3/src/jukedj/models.py#L75-L85
[ "def", "path", "(", "self", ")", ":", "p", "=", "os", ".", "path", ".", "normpath", "(", "self", ".", "_path", ")", "if", "p", ".", "endswith", "(", "':'", ")", ":", "p", "=", "p", "+", "os", ".", "path", ".", "sep", "return", "p" ]
d4159961c819c26792a278981ee68106ee15f3f3
test
Project.path
Set path :param value: The value for path :type value: str :raises: None
src/jukedj/models.py
def path(self, value): """Set path :param value: The value for path :type value: str :raises: None """ prepval = value.replace('\\', '/') self._path = posixpath.normpath(prepval) if self._path.endswith(':'): self._path = self._path + posixpath.sep
def path(self, value): """Set path :param value: The value for path :type value: str :raises: None """ prepval = value.replace('\\', '/') self._path = posixpath.normpath(prepval) if self._path.endswith(':'): self._path = self._path + posixpath.sep
[ "Set", "path" ]
JukeboxPipeline/jukedj
python
https://github.com/JukeboxPipeline/jukedj/blob/d4159961c819c26792a278981ee68106ee15f3f3/src/jukedj/models.py#L88-L98
[ "def", "path", "(", "self", ",", "value", ")", ":", "prepval", "=", "value", ".", "replace", "(", "'\\\\'", ",", "'/'", ")", "self", ".", "_path", "=", "posixpath", ".", "normpath", "(", "prepval", ")", "if", "self", ".", "_path", ".", "endswith", "(", "':'", ")", ":", "self", ".", "_path", "=", "self", ".", "_path", "+", "posixpath", ".", "sep" ]
d4159961c819c26792a278981ee68106ee15f3f3
test
Shot.clean
Reimplemented from :class:`models.Model`. Check if startframe is before endframe :returns: None :rtype: None :raises: ValidationError
src/jukedj/models.py
def clean(self, ): """Reimplemented from :class:`models.Model`. Check if startframe is before endframe :returns: None :rtype: None :raises: ValidationError """ if self.startframe > self.endframe: raise ValidationError("Shot starts before it ends: Framerange(%s - %s)" % (self.startframe, self.endframe))
def clean(self, ): """Reimplemented from :class:`models.Model`. Check if startframe is before endframe :returns: None :rtype: None :raises: ValidationError """ if self.startframe > self.endframe: raise ValidationError("Shot starts before it ends: Framerange(%s - %s)" % (self.startframe, self.endframe))
[ "Reimplemented", "from", ":", "class", ":", "models", ".", "Model", ".", "Check", "if", "startframe", "is", "before", "endframe" ]
JukeboxPipeline/jukedj
python
https://github.com/JukeboxPipeline/jukedj/blob/d4159961c819c26792a278981ee68106ee15f3f3/src/jukedj/models.py#L270-L278
[ "def", "clean", "(", "self", ",", ")", ":", "if", "self", ".", "startframe", ">", "self", ".", "endframe", ":", "raise", "ValidationError", "(", "\"Shot starts before it ends: Framerange(%s - %s)\"", "%", "(", "self", ".", "startframe", ",", "self", ".", "endframe", ")", ")" ]
d4159961c819c26792a278981ee68106ee15f3f3
test
File.path
Set path :param value: The value for path :type value: str :raises: None
src/jukedj/models.py
def path(self, value): """Set path :param value: The value for path :type value: str :raises: None """ prepval = value.replace('\\', '/') self._path = posixpath.normpath(prepval)
def path(self, value): """Set path :param value: The value for path :type value: str :raises: None """ prepval = value.replace('\\', '/') self._path = posixpath.normpath(prepval)
[ "Set", "path" ]
JukeboxPipeline/jukedj
python
https://github.com/JukeboxPipeline/jukedj/blob/d4159961c819c26792a278981ee68106ee15f3f3/src/jukedj/models.py#L323-L331
[ "def", "path", "(", "self", ",", "value", ")", ":", "prepval", "=", "value", ".", "replace", "(", "'\\\\'", ",", "'/'", ")", "self", ".", "_path", "=", "posixpath", ".", "normpath", "(", "prepval", ")" ]
d4159961c819c26792a278981ee68106ee15f3f3
test
ConnectionPool.register_type
Registers a type name so that it may be used to send and receive packages. :param typename: Name of the packet type. A method with the same name and a "on_" prefix should be added to handle incomming packets. :raises ValueError: If there is a hash code collision.
anycall/connectionpool.py
def register_type(self, typename): """ Registers a type name so that it may be used to send and receive packages. :param typename: Name of the packet type. A method with the same name and a "on_" prefix should be added to handle incomming packets. :raises ValueError: If there is a hash code collision. """ # this is to check for collisions only self._dummy_protocol.register_type(typename) self._typenames.add(typename)
def register_type(self, typename): """ Registers a type name so that it may be used to send and receive packages. :param typename: Name of the packet type. A method with the same name and a "on_" prefix should be added to handle incomming packets. :raises ValueError: If there is a hash code collision. """ # this is to check for collisions only self._dummy_protocol.register_type(typename) self._typenames.add(typename)
[ "Registers", "a", "type", "name", "so", "that", "it", "may", "be", "used", "to", "send", "and", "receive", "packages", ".", ":", "param", "typename", ":", "Name", "of", "the", "packet", "type", ".", "A", "method", "with", "the", "same", "name", "and", "a", "on_", "prefix", "should", "be", "added", "to", "handle", "incomming", "packets", ".", ":", "raises", "ValueError", ":", "If", "there", "is", "a", "hash", "code", "collision", "." ]
pydron/anycall
python
https://github.com/pydron/anycall/blob/43add96660258a14b24aa8e8413dffb1741b72d7/anycall/connectionpool.py#L77-L90
[ "def", "register_type", "(", "self", ",", "typename", ")", ":", "# this is to check for collisions only", "self", ".", "_dummy_protocol", ".", "register_type", "(", "typename", ")", "self", ".", "_typenames", ".", "add", "(", "typename", ")" ]
43add96660258a14b24aa8e8413dffb1741b72d7
test
ConnectionPool.open
Opens the port. :param packet_received: Callback which is invoked when we received a packet. Is passed the peer, typename, and data. :returns: Deferred that callbacks when we are ready to receive.
anycall/connectionpool.py
def open(self, packet_received): """ Opens the port. :param packet_received: Callback which is invoked when we received a packet. Is passed the peer, typename, and data. :returns: Deferred that callbacks when we are ready to receive. """ def port_open(listeningport): self._listeningport = listeningport self.ownid = self.ownid_factory(listeningport) logger.debug("Port opened. Own-ID:%s" % self.ownid) return None logger.debug("Opening connection pool") self.packet_received = packet_received d = self.stream_server_endpoint.listen(PoolFactory(self, self._typenames)) d.addCallback(port_open) return d
def open(self, packet_received): """ Opens the port. :param packet_received: Callback which is invoked when we received a packet. Is passed the peer, typename, and data. :returns: Deferred that callbacks when we are ready to receive. """ def port_open(listeningport): self._listeningport = listeningport self.ownid = self.ownid_factory(listeningport) logger.debug("Port opened. Own-ID:%s" % self.ownid) return None logger.debug("Opening connection pool") self.packet_received = packet_received d = self.stream_server_endpoint.listen(PoolFactory(self, self._typenames)) d.addCallback(port_open) return d
[ "Opens", "the", "port", ".", ":", "param", "packet_received", ":", "Callback", "which", "is", "invoked", "when", "we", "received", "a", "packet", ".", "Is", "passed", "the", "peer", "typename", "and", "data", "." ]
pydron/anycall
python
https://github.com/pydron/anycall/blob/43add96660258a14b24aa8e8413dffb1741b72d7/anycall/connectionpool.py#L92-L112
[ "def", "open", "(", "self", ",", "packet_received", ")", ":", "def", "port_open", "(", "listeningport", ")", ":", "self", ".", "_listeningport", "=", "listeningport", "self", ".", "ownid", "=", "self", ".", "ownid_factory", "(", "listeningport", ")", "logger", ".", "debug", "(", "\"Port opened. Own-ID:%s\"", "%", "self", ".", "ownid", ")", "return", "None", "logger", ".", "debug", "(", "\"Opening connection pool\"", ")", "self", ".", "packet_received", "=", "packet_received", "d", "=", "self", ".", "stream_server_endpoint", ".", "listen", "(", "PoolFactory", "(", "self", ",", "self", ".", "_typenames", ")", ")", "d", ".", "addCallback", "(", "port_open", ")", "return", "d" ]
43add96660258a14b24aa8e8413dffb1741b72d7
test
ConnectionPool.pre_connect
Ensures that we have an open connection to the given peer. Returns the peer id. This should be equal to the given one, but it might not if the given peer was, say, the IP and the peer actually identifies itself with a host name. The returned peer is the real one that should be used. This can be handy if we aren't 100% sure of the peer's identity.
anycall/connectionpool.py
def pre_connect(self, peer): """ Ensures that we have an open connection to the given peer. Returns the peer id. This should be equal to the given one, but it might not if the given peer was, say, the IP and the peer actually identifies itself with a host name. The returned peer is the real one that should be used. This can be handy if we aren't 100% sure of the peer's identity. """ if peer in self._connections: return defer.succeed(peer) else: d = self._connect(peer, exact_peer=False) def connected(p): return p.peer d.addCallback(connected) return d
def pre_connect(self, peer): """ Ensures that we have an open connection to the given peer. Returns the peer id. This should be equal to the given one, but it might not if the given peer was, say, the IP and the peer actually identifies itself with a host name. The returned peer is the real one that should be used. This can be handy if we aren't 100% sure of the peer's identity. """ if peer in self._connections: return defer.succeed(peer) else: d = self._connect(peer, exact_peer=False) def connected(p): return p.peer d.addCallback(connected) return d
[ "Ensures", "that", "we", "have", "an", "open", "connection", "to", "the", "given", "peer", ".", "Returns", "the", "peer", "id", ".", "This", "should", "be", "equal", "to", "the", "given", "one", "but", "it", "might", "not", "if", "the", "given", "peer", "was", "say", "the", "IP", "and", "the", "peer", "actually", "identifies", "itself", "with", "a", "host", "name", ".", "The", "returned", "peer", "is", "the", "real", "one", "that", "should", "be", "used", ".", "This", "can", "be", "handy", "if", "we", "aren", "t", "100%", "sure", "of", "the", "peer", "s", "identity", "." ]
pydron/anycall
python
https://github.com/pydron/anycall/blob/43add96660258a14b24aa8e8413dffb1741b72d7/anycall/connectionpool.py#L114-L131
[ "def", "pre_connect", "(", "self", ",", "peer", ")", ":", "if", "peer", "in", "self", ".", "_connections", ":", "return", "defer", ".", "succeed", "(", "peer", ")", "else", ":", "d", "=", "self", ".", "_connect", "(", "peer", ",", "exact_peer", "=", "False", ")", "def", "connected", "(", "p", ")", ":", "return", "p", ".", "peer", "d", ".", "addCallback", "(", "connected", ")", "return", "d" ]
43add96660258a14b24aa8e8413dffb1741b72d7
test
ConnectionPool.send
Sends a packet to a peer.
anycall/connectionpool.py
def send(self, peer, typename, data): """ Sends a packet to a peer. """ def attempt_to_send(_): if peer not in self._connections: d = self._connect(peer) d.addCallback(attempt_to_send) return d else: conn = self._connections[peer][0] conn.send_packet(typename, data) return defer.succeed(None) d = attempt_to_send(None) self._ongoing_sends.add(d) def send_completed(result): if d in self._ongoing_sends: self._ongoing_sends.remove(d) return result d.addBoth(send_completed) return d
def send(self, peer, typename, data): """ Sends a packet to a peer. """ def attempt_to_send(_): if peer not in self._connections: d = self._connect(peer) d.addCallback(attempt_to_send) return d else: conn = self._connections[peer][0] conn.send_packet(typename, data) return defer.succeed(None) d = attempt_to_send(None) self._ongoing_sends.add(d) def send_completed(result): if d in self._ongoing_sends: self._ongoing_sends.remove(d) return result d.addBoth(send_completed) return d
[ "Sends", "a", "packet", "to", "a", "peer", "." ]
pydron/anycall
python
https://github.com/pydron/anycall/blob/43add96660258a14b24aa8e8413dffb1741b72d7/anycall/connectionpool.py#L152-L178
[ "def", "send", "(", "self", ",", "peer", ",", "typename", ",", "data", ")", ":", "def", "attempt_to_send", "(", "_", ")", ":", "if", "peer", "not", "in", "self", ".", "_connections", ":", "d", "=", "self", ".", "_connect", "(", "peer", ")", "d", ".", "addCallback", "(", "attempt_to_send", ")", "return", "d", "else", ":", "conn", "=", "self", ".", "_connections", "[", "peer", "]", "[", "0", "]", "conn", ".", "send_packet", "(", "typename", ",", "data", ")", "return", "defer", ".", "succeed", "(", "None", ")", "d", "=", "attempt_to_send", "(", "None", ")", "self", ".", "_ongoing_sends", ".", "add", "(", "d", ")", "def", "send_completed", "(", "result", ")", ":", "if", "d", "in", "self", ".", "_ongoing_sends", ":", "self", ".", "_ongoing_sends", ".", "remove", "(", "d", ")", "return", "result", "d", ".", "addBoth", "(", "send_completed", ")", "return", "d" ]
43add96660258a14b24aa8e8413dffb1741b72d7
test
ConnectionPool.close
Stop listing for new connections and close all open connections. :returns: Deferred that calls back once everything is closed.
anycall/connectionpool.py
def close(self): """ Stop listing for new connections and close all open connections. :returns: Deferred that calls back once everything is closed. """ def cancel_sends(_): logger.debug("Closed port. Cancelling all on-going send operations...") while self._ongoing_sends: d = self._ongoing_sends.pop() d.cancel() def close_connections(_): all_connections = [c for conns in self._connections.itervalues() for c in conns] logger.debug("Closing all connections (there are %s)..." % len(all_connections)) for c in all_connections: c.transport.loseConnection() ds = [c.wait_for_close() for c in all_connections] d = defer.DeferredList(ds, fireOnOneErrback=True) def allclosed(_): logger.debug("All connections closed.") d.addCallback(allclosed) return d logger.debug("Closing connection pool...") d = defer.maybeDeferred(self._listeningport.stopListening) d.addCallback(cancel_sends) d.addCallback(close_connections) return d
def close(self): """ Stop listing for new connections and close all open connections. :returns: Deferred that calls back once everything is closed. """ def cancel_sends(_): logger.debug("Closed port. Cancelling all on-going send operations...") while self._ongoing_sends: d = self._ongoing_sends.pop() d.cancel() def close_connections(_): all_connections = [c for conns in self._connections.itervalues() for c in conns] logger.debug("Closing all connections (there are %s)..." % len(all_connections)) for c in all_connections: c.transport.loseConnection() ds = [c.wait_for_close() for c in all_connections] d = defer.DeferredList(ds, fireOnOneErrback=True) def allclosed(_): logger.debug("All connections closed.") d.addCallback(allclosed) return d logger.debug("Closing connection pool...") d = defer.maybeDeferred(self._listeningport.stopListening) d.addCallback(cancel_sends) d.addCallback(close_connections) return d
[ "Stop", "listing", "for", "new", "connections", "and", "close", "all", "open", "connections", ".", ":", "returns", ":", "Deferred", "that", "calls", "back", "once", "everything", "is", "closed", "." ]
pydron/anycall
python
https://github.com/pydron/anycall/blob/43add96660258a14b24aa8e8413dffb1741b72d7/anycall/connectionpool.py#L180-L212
[ "def", "close", "(", "self", ")", ":", "def", "cancel_sends", "(", "_", ")", ":", "logger", ".", "debug", "(", "\"Closed port. Cancelling all on-going send operations...\"", ")", "while", "self", ".", "_ongoing_sends", ":", "d", "=", "self", ".", "_ongoing_sends", ".", "pop", "(", ")", "d", ".", "cancel", "(", ")", "def", "close_connections", "(", "_", ")", ":", "all_connections", "=", "[", "c", "for", "conns", "in", "self", ".", "_connections", ".", "itervalues", "(", ")", "for", "c", "in", "conns", "]", "logger", ".", "debug", "(", "\"Closing all connections (there are %s)...\"", "%", "len", "(", "all_connections", ")", ")", "for", "c", "in", "all_connections", ":", "c", ".", "transport", ".", "loseConnection", "(", ")", "ds", "=", "[", "c", ".", "wait_for_close", "(", ")", "for", "c", "in", "all_connections", "]", "d", "=", "defer", ".", "DeferredList", "(", "ds", ",", "fireOnOneErrback", "=", "True", ")", "def", "allclosed", "(", "_", ")", ":", "logger", ".", "debug", "(", "\"All connections closed.\"", ")", "d", ".", "addCallback", "(", "allclosed", ")", "return", "d", "logger", ".", "debug", "(", "\"Closing connection pool...\"", ")", "d", "=", "defer", ".", "maybeDeferred", "(", "self", ".", "_listeningport", ".", "stopListening", ")", "d", ".", "addCallback", "(", "cancel_sends", ")", "d", ".", "addCallback", "(", "close_connections", ")", "return", "d" ]
43add96660258a14b24aa8e8413dffb1741b72d7
test
Config.get_config_value
Read customer's config value by section and key. :param section: config file's section. i.e [default] :param key: config file's key under section. i.e packages_scan :param return_type: return value type, str | int | bool.
ternya/config.py
def get_config_value(self, section, key, return_type: type): """Read customer's config value by section and key. :param section: config file's section. i.e [default] :param key: config file's key under section. i.e packages_scan :param return_type: return value type, str | int | bool. """ try: value = self.method_mapping[return_type](section, key) except NoSectionError as e: raise ConfigError(e.message) except NoOptionError as e: raise ConfigError(e.message) return value
def get_config_value(self, section, key, return_type: type): """Read customer's config value by section and key. :param section: config file's section. i.e [default] :param key: config file's key under section. i.e packages_scan :param return_type: return value type, str | int | bool. """ try: value = self.method_mapping[return_type](section, key) except NoSectionError as e: raise ConfigError(e.message) except NoOptionError as e: raise ConfigError(e.message) return value
[ "Read", "customer", "s", "config", "value", "by", "section", "and", "key", "." ]
ndrlslz/ternya
python
https://github.com/ndrlslz/ternya/blob/c05aec10029e645d63ff04313dbcf2644743481f/ternya/config.py#L69-L82
[ "def", "get_config_value", "(", "self", ",", "section", ",", "key", ",", "return_type", ":", "type", ")", ":", "try", ":", "value", "=", "self", ".", "method_mapping", "[", "return_type", "]", "(", "section", ",", "key", ")", "except", "NoSectionError", "as", "e", ":", "raise", "ConfigError", "(", "e", ".", "message", ")", "except", "NoOptionError", "as", "e", ":", "raise", "ConfigError", "(", "e", ".", "message", ")", "return", "value" ]
c05aec10029e645d63ff04313dbcf2644743481f
test
nova
Nova annotation for adding function to process nova notification. if event_type include wildcard, will put {pattern: function} into process_wildcard dict else will put {event_type: function} into process dict :param arg: event_type of notification
ternya/annotation.py
def nova(*arg): """ Nova annotation for adding function to process nova notification. if event_type include wildcard, will put {pattern: function} into process_wildcard dict else will put {event_type: function} into process dict :param arg: event_type of notification """ check_event_type(Openstack.Nova, *arg) event_type = arg[0] def decorator(func): if event_type.find("*") != -1: event_type_pattern = pre_compile(event_type) nova_customer_process_wildcard[event_type_pattern] = func else: nova_customer_process[event_type] = func log.info("add function {0} to process event_type:{1}".format(func.__name__, event_type)) @functools.wraps(func) def wrapper(*args, **kwargs): func(*args, **kwargs) return wrapper return decorator
def nova(*arg): """ Nova annotation for adding function to process nova notification. if event_type include wildcard, will put {pattern: function} into process_wildcard dict else will put {event_type: function} into process dict :param arg: event_type of notification """ check_event_type(Openstack.Nova, *arg) event_type = arg[0] def decorator(func): if event_type.find("*") != -1: event_type_pattern = pre_compile(event_type) nova_customer_process_wildcard[event_type_pattern] = func else: nova_customer_process[event_type] = func log.info("add function {0} to process event_type:{1}".format(func.__name__, event_type)) @functools.wraps(func) def wrapper(*args, **kwargs): func(*args, **kwargs) return wrapper return decorator
[ "Nova", "annotation", "for", "adding", "function", "to", "process", "nova", "notification", "." ]
ndrlslz/ternya
python
https://github.com/ndrlslz/ternya/blob/c05aec10029e645d63ff04313dbcf2644743481f/ternya/annotation.py#L53-L79
[ "def", "nova", "(", "*", "arg", ")", ":", "check_event_type", "(", "Openstack", ".", "Nova", ",", "*", "arg", ")", "event_type", "=", "arg", "[", "0", "]", "def", "decorator", "(", "func", ")", ":", "if", "event_type", ".", "find", "(", "\"*\"", ")", "!=", "-", "1", ":", "event_type_pattern", "=", "pre_compile", "(", "event_type", ")", "nova_customer_process_wildcard", "[", "event_type_pattern", "]", "=", "func", "else", ":", "nova_customer_process", "[", "event_type", "]", "=", "func", "log", ".", "info", "(", "\"add function {0} to process event_type:{1}\"", ".", "format", "(", "func", ".", "__name__", ",", "event_type", ")", ")", "@", "functools", ".", "wraps", "(", "func", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "func", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "wrapper", "return", "decorator" ]
c05aec10029e645d63ff04313dbcf2644743481f
test
cinder
Cinder annotation for adding function to process cinder notification. if event_type include wildcard, will put {pattern: function} into process_wildcard dict else will put {event_type: function} into process dict :param arg: event_type of notification
ternya/annotation.py
def cinder(*arg): """ Cinder annotation for adding function to process cinder notification. if event_type include wildcard, will put {pattern: function} into process_wildcard dict else will put {event_type: function} into process dict :param arg: event_type of notification """ check_event_type(Openstack.Cinder, *arg) event_type = arg[0] def decorator(func): if event_type.find("*") != -1: event_type_pattern = pre_compile(event_type) cinder_customer_process_wildcard[event_type_pattern] = func else: cinder_customer_process[event_type] = func log.info("add function {0} to process event_type:{1}".format(func.__name__, event_type)) @functools.wraps(func) def wrapper(*args, **kwargs): func(*args, **kwargs) return wrapper return decorator
def cinder(*arg): """ Cinder annotation for adding function to process cinder notification. if event_type include wildcard, will put {pattern: function} into process_wildcard dict else will put {event_type: function} into process dict :param arg: event_type of notification """ check_event_type(Openstack.Cinder, *arg) event_type = arg[0] def decorator(func): if event_type.find("*") != -1: event_type_pattern = pre_compile(event_type) cinder_customer_process_wildcard[event_type_pattern] = func else: cinder_customer_process[event_type] = func log.info("add function {0} to process event_type:{1}".format(func.__name__, event_type)) @functools.wraps(func) def wrapper(*args, **kwargs): func(*args, **kwargs) return wrapper return decorator
[ "Cinder", "annotation", "for", "adding", "function", "to", "process", "cinder", "notification", "." ]
ndrlslz/ternya
python
https://github.com/ndrlslz/ternya/blob/c05aec10029e645d63ff04313dbcf2644743481f/ternya/annotation.py#L82-L108
[ "def", "cinder", "(", "*", "arg", ")", ":", "check_event_type", "(", "Openstack", ".", "Cinder", ",", "*", "arg", ")", "event_type", "=", "arg", "[", "0", "]", "def", "decorator", "(", "func", ")", ":", "if", "event_type", ".", "find", "(", "\"*\"", ")", "!=", "-", "1", ":", "event_type_pattern", "=", "pre_compile", "(", "event_type", ")", "cinder_customer_process_wildcard", "[", "event_type_pattern", "]", "=", "func", "else", ":", "cinder_customer_process", "[", "event_type", "]", "=", "func", "log", ".", "info", "(", "\"add function {0} to process event_type:{1}\"", ".", "format", "(", "func", ".", "__name__", ",", "event_type", ")", ")", "@", "functools", ".", "wraps", "(", "func", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "func", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "wrapper", "return", "decorator" ]
c05aec10029e645d63ff04313dbcf2644743481f
test
neutron
Neutron annotation for adding function to process neutron notification. if event_type include wildcard, will put {pattern: function} into process_wildcard dict else will put {event_type: function} into process dict :param arg: event_type of notification
ternya/annotation.py
def neutron(*arg): """ Neutron annotation for adding function to process neutron notification. if event_type include wildcard, will put {pattern: function} into process_wildcard dict else will put {event_type: function} into process dict :param arg: event_type of notification """ check_event_type(Openstack.Neutron, *arg) event_type = arg[0] def decorator(func): if event_type.find("*") != -1: event_type_pattern = pre_compile(event_type) neutron_customer_process_wildcard[event_type_pattern] = func else: neutron_customer_process[event_type] = func log.info("add function {0} to process event_type:{1}".format(func.__name__, event_type)) @functools.wraps(func) def wrapper(*args, **kwargs): func(*args, **kwargs) return wrapper return decorator
def neutron(*arg): """ Neutron annotation for adding function to process neutron notification. if event_type include wildcard, will put {pattern: function} into process_wildcard dict else will put {event_type: function} into process dict :param arg: event_type of notification """ check_event_type(Openstack.Neutron, *arg) event_type = arg[0] def decorator(func): if event_type.find("*") != -1: event_type_pattern = pre_compile(event_type) neutron_customer_process_wildcard[event_type_pattern] = func else: neutron_customer_process[event_type] = func log.info("add function {0} to process event_type:{1}".format(func.__name__, event_type)) @functools.wraps(func) def wrapper(*args, **kwargs): func(*args, **kwargs) return wrapper return decorator
[ "Neutron", "annotation", "for", "adding", "function", "to", "process", "neutron", "notification", "." ]
ndrlslz/ternya
python
https://github.com/ndrlslz/ternya/blob/c05aec10029e645d63ff04313dbcf2644743481f/ternya/annotation.py#L111-L137
[ "def", "neutron", "(", "*", "arg", ")", ":", "check_event_type", "(", "Openstack", ".", "Neutron", ",", "*", "arg", ")", "event_type", "=", "arg", "[", "0", "]", "def", "decorator", "(", "func", ")", ":", "if", "event_type", ".", "find", "(", "\"*\"", ")", "!=", "-", "1", ":", "event_type_pattern", "=", "pre_compile", "(", "event_type", ")", "neutron_customer_process_wildcard", "[", "event_type_pattern", "]", "=", "func", "else", ":", "neutron_customer_process", "[", "event_type", "]", "=", "func", "log", ".", "info", "(", "\"add function {0} to process event_type:{1}\"", ".", "format", "(", "func", ".", "__name__", ",", "event_type", ")", ")", "@", "functools", ".", "wraps", "(", "func", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "func", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "wrapper", "return", "decorator" ]
c05aec10029e645d63ff04313dbcf2644743481f
test
glance
Glance annotation for adding function to process glance notification. if event_type include wildcard, will put {pattern: function} into process_wildcard dict else will put {event_type: function} into process dict :param arg: event_type of notification
ternya/annotation.py
def glance(*arg): """ Glance annotation for adding function to process glance notification. if event_type include wildcard, will put {pattern: function} into process_wildcard dict else will put {event_type: function} into process dict :param arg: event_type of notification """ check_event_type(Openstack.Glance, *arg) event_type = arg[0] def decorator(func): if event_type.find("*") != -1: event_type_pattern = pre_compile(event_type) glance_customer_process_wildcard[event_type_pattern] = func else: glance_customer_process[event_type] = func log.info("add function {0} to process event_type:{1}".format(func.__name__, event_type)) @functools.wraps(func) def wrapper(*args, **kwargs): func(*args, **kwargs) return wrapper return decorator
def glance(*arg): """ Glance annotation for adding function to process glance notification. if event_type include wildcard, will put {pattern: function} into process_wildcard dict else will put {event_type: function} into process dict :param arg: event_type of notification """ check_event_type(Openstack.Glance, *arg) event_type = arg[0] def decorator(func): if event_type.find("*") != -1: event_type_pattern = pre_compile(event_type) glance_customer_process_wildcard[event_type_pattern] = func else: glance_customer_process[event_type] = func log.info("add function {0} to process event_type:{1}".format(func.__name__, event_type)) @functools.wraps(func) def wrapper(*args, **kwargs): func(*args, **kwargs) return wrapper return decorator
[ "Glance", "annotation", "for", "adding", "function", "to", "process", "glance", "notification", "." ]
ndrlslz/ternya
python
https://github.com/ndrlslz/ternya/blob/c05aec10029e645d63ff04313dbcf2644743481f/ternya/annotation.py#L140-L166
[ "def", "glance", "(", "*", "arg", ")", ":", "check_event_type", "(", "Openstack", ".", "Glance", ",", "*", "arg", ")", "event_type", "=", "arg", "[", "0", "]", "def", "decorator", "(", "func", ")", ":", "if", "event_type", ".", "find", "(", "\"*\"", ")", "!=", "-", "1", ":", "event_type_pattern", "=", "pre_compile", "(", "event_type", ")", "glance_customer_process_wildcard", "[", "event_type_pattern", "]", "=", "func", "else", ":", "glance_customer_process", "[", "event_type", "]", "=", "func", "log", ".", "info", "(", "\"add function {0} to process event_type:{1}\"", ".", "format", "(", "func", ".", "__name__", ",", "event_type", ")", ")", "@", "functools", ".", "wraps", "(", "func", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "func", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "wrapper", "return", "decorator" ]
c05aec10029e645d63ff04313dbcf2644743481f
test
swift
Swift annotation for adding function to process swift notification. if event_type include wildcard, will put {pattern: function} into process_wildcard dict else will put {event_type: function} into process dict :param arg: event_type of notification
ternya/annotation.py
def swift(*arg): """ Swift annotation for adding function to process swift notification. if event_type include wildcard, will put {pattern: function} into process_wildcard dict else will put {event_type: function} into process dict :param arg: event_type of notification """ check_event_type(Openstack.Swift, *arg) event_type = arg[0] def decorator(func): if event_type.find("*") != -1: event_type_pattern = pre_compile(event_type) swift_customer_process_wildcard[event_type_pattern] = func else: swift_customer_process[event_type] = func log.info("add function {0} to process event_type:{1}".format(func.__name__, event_type)) @functools.wraps(func) def wrapper(*args, **kwargs): func(*args, **kwargs) return wrapper return decorator
def swift(*arg): """ Swift annotation for adding function to process swift notification. if event_type include wildcard, will put {pattern: function} into process_wildcard dict else will put {event_type: function} into process dict :param arg: event_type of notification """ check_event_type(Openstack.Swift, *arg) event_type = arg[0] def decorator(func): if event_type.find("*") != -1: event_type_pattern = pre_compile(event_type) swift_customer_process_wildcard[event_type_pattern] = func else: swift_customer_process[event_type] = func log.info("add function {0} to process event_type:{1}".format(func.__name__, event_type)) @functools.wraps(func) def wrapper(*args, **kwargs): func(*args, **kwargs) return wrapper return decorator
[ "Swift", "annotation", "for", "adding", "function", "to", "process", "swift", "notification", "." ]
ndrlslz/ternya
python
https://github.com/ndrlslz/ternya/blob/c05aec10029e645d63ff04313dbcf2644743481f/ternya/annotation.py#L169-L195
[ "def", "swift", "(", "*", "arg", ")", ":", "check_event_type", "(", "Openstack", ".", "Swift", ",", "*", "arg", ")", "event_type", "=", "arg", "[", "0", "]", "def", "decorator", "(", "func", ")", ":", "if", "event_type", ".", "find", "(", "\"*\"", ")", "!=", "-", "1", ":", "event_type_pattern", "=", "pre_compile", "(", "event_type", ")", "swift_customer_process_wildcard", "[", "event_type_pattern", "]", "=", "func", "else", ":", "swift_customer_process", "[", "event_type", "]", "=", "func", "log", ".", "info", "(", "\"add function {0} to process event_type:{1}\"", ".", "format", "(", "func", ".", "__name__", ",", "event_type", ")", ")", "@", "functools", ".", "wraps", "(", "func", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "func", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "wrapper", "return", "decorator" ]
c05aec10029e645d63ff04313dbcf2644743481f
test
keystone
Swift annotation for adding function to process keystone notification. if event_type include wildcard, will put {pattern: function} into process_wildcard dict else will put {event_type: function} into process dict :param arg: event_type of notification
ternya/annotation.py
def keystone(*arg): """ Swift annotation for adding function to process keystone notification. if event_type include wildcard, will put {pattern: function} into process_wildcard dict else will put {event_type: function} into process dict :param arg: event_type of notification """ check_event_type(Openstack.Keystone, *arg) event_type = arg[0] def decorator(func): if event_type.find("*") != -1: event_type_pattern = pre_compile(event_type) keystone_customer_process_wildcard[event_type_pattern] = func else: keystone_customer_process[event_type] = func log.info("add function {0} to process event_type:{1}".format(func.__name__, event_type)) @functools.wraps(func) def wrapper(*args, **kwargs): func(*args, **kwargs) return wrapper return decorator
def keystone(*arg): """ Swift annotation for adding function to process keystone notification. if event_type include wildcard, will put {pattern: function} into process_wildcard dict else will put {event_type: function} into process dict :param arg: event_type of notification """ check_event_type(Openstack.Keystone, *arg) event_type = arg[0] def decorator(func): if event_type.find("*") != -1: event_type_pattern = pre_compile(event_type) keystone_customer_process_wildcard[event_type_pattern] = func else: keystone_customer_process[event_type] = func log.info("add function {0} to process event_type:{1}".format(func.__name__, event_type)) @functools.wraps(func) def wrapper(*args, **kwargs): func(*args, **kwargs) return wrapper return decorator
[ "Swift", "annotation", "for", "adding", "function", "to", "process", "keystone", "notification", "." ]
ndrlslz/ternya
python
https://github.com/ndrlslz/ternya/blob/c05aec10029e645d63ff04313dbcf2644743481f/ternya/annotation.py#L198-L224
[ "def", "keystone", "(", "*", "arg", ")", ":", "check_event_type", "(", "Openstack", ".", "Keystone", ",", "*", "arg", ")", "event_type", "=", "arg", "[", "0", "]", "def", "decorator", "(", "func", ")", ":", "if", "event_type", ".", "find", "(", "\"*\"", ")", "!=", "-", "1", ":", "event_type_pattern", "=", "pre_compile", "(", "event_type", ")", "keystone_customer_process_wildcard", "[", "event_type_pattern", "]", "=", "func", "else", ":", "keystone_customer_process", "[", "event_type", "]", "=", "func", "log", ".", "info", "(", "\"add function {0} to process event_type:{1}\"", ".", "format", "(", "func", ".", "__name__", ",", "event_type", ")", ")", "@", "functools", ".", "wraps", "(", "func", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "func", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "wrapper", "return", "decorator" ]
c05aec10029e645d63ff04313dbcf2644743481f
test
heat
Heat annotation for adding function to process heat notification. if event_type include wildcard, will put {pattern: function} into process_wildcard dict else will put {event_type: function} into process dict :param arg: event_type of notification
ternya/annotation.py
def heat(*arg): """ Heat annotation for adding function to process heat notification. if event_type include wildcard, will put {pattern: function} into process_wildcard dict else will put {event_type: function} into process dict :param arg: event_type of notification """ check_event_type(Openstack.Heat, *arg) event_type = arg[0] def decorator(func): if event_type.find("*") != -1: event_type_pattern = pre_compile(event_type) heat_customer_process_wildcard[event_type_pattern] = func else: heat_customer_process[event_type] = func log.info("add function {0} to process event_type:{1}".format(func.__name__, event_type)) @functools.wraps(func) def wrapper(*args, **kwargs): func(*args, **kwargs) return wrapper return decorator
def heat(*arg): """ Heat annotation for adding function to process heat notification. if event_type include wildcard, will put {pattern: function} into process_wildcard dict else will put {event_type: function} into process dict :param arg: event_type of notification """ check_event_type(Openstack.Heat, *arg) event_type = arg[0] def decorator(func): if event_type.find("*") != -1: event_type_pattern = pre_compile(event_type) heat_customer_process_wildcard[event_type_pattern] = func else: heat_customer_process[event_type] = func log.info("add function {0} to process event_type:{1}".format(func.__name__, event_type)) @functools.wraps(func) def wrapper(*args, **kwargs): func(*args, **kwargs) return wrapper return decorator
[ "Heat", "annotation", "for", "adding", "function", "to", "process", "heat", "notification", "." ]
ndrlslz/ternya
python
https://github.com/ndrlslz/ternya/blob/c05aec10029e645d63ff04313dbcf2644743481f/ternya/annotation.py#L227-L253
[ "def", "heat", "(", "*", "arg", ")", ":", "check_event_type", "(", "Openstack", ".", "Heat", ",", "*", "arg", ")", "event_type", "=", "arg", "[", "0", "]", "def", "decorator", "(", "func", ")", ":", "if", "event_type", ".", "find", "(", "\"*\"", ")", "!=", "-", "1", ":", "event_type_pattern", "=", "pre_compile", "(", "event_type", ")", "heat_customer_process_wildcard", "[", "event_type_pattern", "]", "=", "func", "else", ":", "heat_customer_process", "[", "event_type", "]", "=", "func", "log", ".", "info", "(", "\"add function {0} to process event_type:{1}\"", ".", "format", "(", "func", ".", "__name__", ",", "event_type", ")", ")", "@", "functools", ".", "wraps", "(", "func", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "func", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "wrapper", "return", "decorator" ]
c05aec10029e645d63ff04313dbcf2644743481f
test
MultiplexingCommandLocator.addFactory
Adds a factory. After calling this method, remote clients will be able to connect to it. This will call ``factory.doStart``.
txampext/multiplexing.py
def addFactory(self, identifier, factory): """Adds a factory. After calling this method, remote clients will be able to connect to it. This will call ``factory.doStart``. """ factory.doStart() self._factories[identifier] = factory
def addFactory(self, identifier, factory): """Adds a factory. After calling this method, remote clients will be able to connect to it. This will call ``factory.doStart``. """ factory.doStart() self._factories[identifier] = factory
[ "Adds", "a", "factory", "." ]
lvh/txampext
python
https://github.com/lvh/txampext/blob/a7d6cb9f1e9200dba597378cd40eb6a2096d4fd9/txampext/multiplexing.py#L99-L109
[ "def", "addFactory", "(", "self", ",", "identifier", ",", "factory", ")", ":", "factory", ".", "doStart", "(", ")", "self", ".", "_factories", "[", "identifier", "]", "=", "factory" ]
a7d6cb9f1e9200dba597378cd40eb6a2096d4fd9
test
MultiplexingCommandLocator.removeFactory
Removes a factory. After calling this method, remote clients will no longer be able to connect to it. This will call the factory's ``doStop`` method.
txampext/multiplexing.py
def removeFactory(self, identifier): """Removes a factory. After calling this method, remote clients will no longer be able to connect to it. This will call the factory's ``doStop`` method. """ factory = self._factories.pop(identifier) factory.doStop() return factory
def removeFactory(self, identifier): """Removes a factory. After calling this method, remote clients will no longer be able to connect to it. This will call the factory's ``doStop`` method. """ factory = self._factories.pop(identifier) factory.doStop() return factory
[ "Removes", "a", "factory", "." ]
lvh/txampext
python
https://github.com/lvh/txampext/blob/a7d6cb9f1e9200dba597378cd40eb6a2096d4fd9/txampext/multiplexing.py#L112-L123
[ "def", "removeFactory", "(", "self", ",", "identifier", ")", ":", "factory", "=", "self", ".", "_factories", ".", "pop", "(", "identifier", ")", "factory", ".", "doStop", "(", ")", "return", "factory" ]
a7d6cb9f1e9200dba597378cd40eb6a2096d4fd9
test
MultiplexingCommandLocator.connect
Attempts to connect using a given factory. This will find the requested factory and use it to build a protocol as if the AMP protocol's peer was making the connection. It will create a transport for the protocol and connect it immediately. It will then store the protocol under a unique identifier, and return that identifier.
txampext/multiplexing.py
def connect(self, factory): """Attempts to connect using a given factory. This will find the requested factory and use it to build a protocol as if the AMP protocol's peer was making the connection. It will create a transport for the protocol and connect it immediately. It will then store the protocol under a unique identifier, and return that identifier. """ try: factory = self._factories[factory] except KeyError: raise NoSuchFactory() remote = self.getProtocol() addr = remote.transport.getPeer() proto = factory.buildProtocol(addr) if proto is None: raise ConnectionRefused() identifier = uuid4().hex transport = MultiplexedTransport(identifier, remote) proto.makeConnection(transport) self._protocols[identifier] = proto return {"connection": identifier}
def connect(self, factory): """Attempts to connect using a given factory. This will find the requested factory and use it to build a protocol as if the AMP protocol's peer was making the connection. It will create a transport for the protocol and connect it immediately. It will then store the protocol under a unique identifier, and return that identifier. """ try: factory = self._factories[factory] except KeyError: raise NoSuchFactory() remote = self.getProtocol() addr = remote.transport.getPeer() proto = factory.buildProtocol(addr) if proto is None: raise ConnectionRefused() identifier = uuid4().hex transport = MultiplexedTransport(identifier, remote) proto.makeConnection(transport) self._protocols[identifier] = proto return {"connection": identifier}
[ "Attempts", "to", "connect", "using", "a", "given", "factory", "." ]
lvh/txampext
python
https://github.com/lvh/txampext/blob/a7d6cb9f1e9200dba597378cd40eb6a2096d4fd9/txampext/multiplexing.py#L138-L164
[ "def", "connect", "(", "self", ",", "factory", ")", ":", "try", ":", "factory", "=", "self", ".", "_factories", "[", "factory", "]", "except", "KeyError", ":", "raise", "NoSuchFactory", "(", ")", "remote", "=", "self", ".", "getProtocol", "(", ")", "addr", "=", "remote", ".", "transport", ".", "getPeer", "(", ")", "proto", "=", "factory", ".", "buildProtocol", "(", "addr", ")", "if", "proto", "is", "None", ":", "raise", "ConnectionRefused", "(", ")", "identifier", "=", "uuid4", "(", ")", ".", "hex", "transport", "=", "MultiplexedTransport", "(", "identifier", ",", "remote", ")", "proto", ".", "makeConnection", "(", "transport", ")", "self", ".", "_protocols", "[", "identifier", "]", "=", "proto", "return", "{", "\"connection\"", ":", "identifier", "}" ]
a7d6cb9f1e9200dba597378cd40eb6a2096d4fd9
test
MultiplexingCommandLocator.receiveData
Receives some data for the given protocol.
txampext/multiplexing.py
def receiveData(self, connection, data): """ Receives some data for the given protocol. """ try: protocol = self._protocols[connection] except KeyError: raise NoSuchConnection() protocol.dataReceived(data) return {}
def receiveData(self, connection, data): """ Receives some data for the given protocol. """ try: protocol = self._protocols[connection] except KeyError: raise NoSuchConnection() protocol.dataReceived(data) return {}
[ "Receives", "some", "data", "for", "the", "given", "protocol", "." ]
lvh/txampext
python
https://github.com/lvh/txampext/blob/a7d6cb9f1e9200dba597378cd40eb6a2096d4fd9/txampext/multiplexing.py#L168-L178
[ "def", "receiveData", "(", "self", ",", "connection", ",", "data", ")", ":", "try", ":", "protocol", "=", "self", ".", "_protocols", "[", "connection", "]", "except", "KeyError", ":", "raise", "NoSuchConnection", "(", ")", "protocol", ".", "dataReceived", "(", "data", ")", "return", "{", "}" ]
a7d6cb9f1e9200dba597378cd40eb6a2096d4fd9
test
MultiplexingCommandLocator.disconnect
Disconnects the given protocol.
txampext/multiplexing.py
def disconnect(self, connection): """ Disconnects the given protocol. """ proto = self._protocols.pop(connection) proto.transport = None return {}
def disconnect(self, connection): """ Disconnects the given protocol. """ proto = self._protocols.pop(connection) proto.transport = None return {}
[ "Disconnects", "the", "given", "protocol", "." ]
lvh/txampext
python
https://github.com/lvh/txampext/blob/a7d6cb9f1e9200dba597378cd40eb6a2096d4fd9/txampext/multiplexing.py#L182-L188
[ "def", "disconnect", "(", "self", ",", "connection", ")", ":", "proto", "=", "self", ".", "_protocols", ".", "pop", "(", "connection", ")", "proto", ".", "transport", "=", "None", "return", "{", "}" ]
a7d6cb9f1e9200dba597378cd40eb6a2096d4fd9
test
ProxyingProtocol._callRemote
Shorthand for ``callRemote``. This uses the factory's connection to the AMP peer.
txampext/multiplexing.py
def _callRemote(self, command, **kwargs): """Shorthand for ``callRemote``. This uses the factory's connection to the AMP peer. """ return self.factory.remote.callRemote(command, **kwargs)
def _callRemote(self, command, **kwargs): """Shorthand for ``callRemote``. This uses the factory's connection to the AMP peer. """ return self.factory.remote.callRemote(command, **kwargs)
[ "Shorthand", "for", "callRemote", "." ]
lvh/txampext
python
https://github.com/lvh/txampext/blob/a7d6cb9f1e9200dba597378cd40eb6a2096d4fd9/txampext/multiplexing.py#L260-L266
[ "def", "_callRemote", "(", "self", ",", "command", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "factory", ".", "remote", ".", "callRemote", "(", "command", ",", "*", "*", "kwargs", ")" ]
a7d6cb9f1e9200dba597378cd40eb6a2096d4fd9
test
ProxyingProtocol.connectionMade
Create a multiplexed stream connection. Connect to the AMP server's multiplexed factory using the identifier (defined by this class' factory). When done, stores the connection reference and causes buffered data to be sent.
txampext/multiplexing.py
def connectionMade(self): """Create a multiplexed stream connection. Connect to the AMP server's multiplexed factory using the identifier (defined by this class' factory). When done, stores the connection reference and causes buffered data to be sent. """ log.msg("Creating multiplexed AMP connection...") remoteFactoryIdentifier = self.factory.remoteFactoryIdentifier d = self._callRemote(Connect, factory=remoteFactoryIdentifier) d.addCallback(self._multiplexedConnectionMade)
def connectionMade(self): """Create a multiplexed stream connection. Connect to the AMP server's multiplexed factory using the identifier (defined by this class' factory). When done, stores the connection reference and causes buffered data to be sent. """ log.msg("Creating multiplexed AMP connection...") remoteFactoryIdentifier = self.factory.remoteFactoryIdentifier d = self._callRemote(Connect, factory=remoteFactoryIdentifier) d.addCallback(self._multiplexedConnectionMade)
[ "Create", "a", "multiplexed", "stream", "connection", "." ]
lvh/txampext
python
https://github.com/lvh/txampext/blob/a7d6cb9f1e9200dba597378cd40eb6a2096d4fd9/txampext/multiplexing.py#L269-L280
[ "def", "connectionMade", "(", "self", ")", ":", "log", ".", "msg", "(", "\"Creating multiplexed AMP connection...\"", ")", "remoteFactoryIdentifier", "=", "self", ".", "factory", ".", "remoteFactoryIdentifier", "d", "=", "self", ".", "_callRemote", "(", "Connect", ",", "factory", "=", "remoteFactoryIdentifier", ")", "d", ".", "addCallback", "(", "self", ".", "_multiplexedConnectionMade", ")" ]
a7d6cb9f1e9200dba597378cd40eb6a2096d4fd9
test
ProxyingProtocol._multiplexedConnectionMade
Stores a reference to the connection, registers this protocol on the factory as one related to a multiplexed AMP connection, and sends currently buffered data. Gets rid of the buffer afterwards.
txampext/multiplexing.py
def _multiplexedConnectionMade(self, response): """Stores a reference to the connection, registers this protocol on the factory as one related to a multiplexed AMP connection, and sends currently buffered data. Gets rid of the buffer afterwards. """ self.connection = conn = response["connection"] self.factory.protocols[conn] = self log.msg("Multiplexed AMP connection ({!r}) made!".format(conn)) data, self._buffer = self._buffer.getvalue(), None if data: log.msg("Sending {} bytes of buffered data...".format(len(data))) self._sendData(data) else: log.msg("No buffered data to send!")
def _multiplexedConnectionMade(self, response): """Stores a reference to the connection, registers this protocol on the factory as one related to a multiplexed AMP connection, and sends currently buffered data. Gets rid of the buffer afterwards. """ self.connection = conn = response["connection"] self.factory.protocols[conn] = self log.msg("Multiplexed AMP connection ({!r}) made!".format(conn)) data, self._buffer = self._buffer.getvalue(), None if data: log.msg("Sending {} bytes of buffered data...".format(len(data))) self._sendData(data) else: log.msg("No buffered data to send!")
[ "Stores", "a", "reference", "to", "the", "connection", "registers", "this", "protocol", "on", "the", "factory", "as", "one", "related", "to", "a", "multiplexed", "AMP", "connection", "and", "sends", "currently", "buffered", "data", ".", "Gets", "rid", "of", "the", "buffer", "afterwards", "." ]
lvh/txampext
python
https://github.com/lvh/txampext/blob/a7d6cb9f1e9200dba597378cd40eb6a2096d4fd9/txampext/multiplexing.py#L283-L300
[ "def", "_multiplexedConnectionMade", "(", "self", ",", "response", ")", ":", "self", ".", "connection", "=", "conn", "=", "response", "[", "\"connection\"", "]", "self", ".", "factory", ".", "protocols", "[", "conn", "]", "=", "self", "log", ".", "msg", "(", "\"Multiplexed AMP connection ({!r}) made!\"", ".", "format", "(", "conn", ")", ")", "data", ",", "self", ".", "_buffer", "=", "self", ".", "_buffer", ".", "getvalue", "(", ")", ",", "None", "if", "data", ":", "log", ".", "msg", "(", "\"Sending {} bytes of buffered data...\"", ".", "format", "(", "len", "(", "data", ")", ")", ")", "self", ".", "_sendData", "(", "data", ")", "else", ":", "log", ".", "msg", "(", "\"No buffered data to send!\"", ")" ]
a7d6cb9f1e9200dba597378cd40eb6a2096d4fd9
test
ProxyingProtocol.dataReceived
Received some data from the local side. If we have set up the multiplexed connection, sends the data over the multiplexed connection. Otherwise, buffers.
txampext/multiplexing.py
def dataReceived(self, data): """Received some data from the local side. If we have set up the multiplexed connection, sends the data over the multiplexed connection. Otherwise, buffers. """ log.msg("{} bytes of data received locally".format(len(data))) if self.connection is None: # we haven't finished connecting yet log.msg("Connection not made yet, buffering...") self._buffer.write(data) else: log.msg("Sending data...") self._sendData(data)
def dataReceived(self, data): """Received some data from the local side. If we have set up the multiplexed connection, sends the data over the multiplexed connection. Otherwise, buffers. """ log.msg("{} bytes of data received locally".format(len(data))) if self.connection is None: # we haven't finished connecting yet log.msg("Connection not made yet, buffering...") self._buffer.write(data) else: log.msg("Sending data...") self._sendData(data)
[ "Received", "some", "data", "from", "the", "local", "side", "." ]
lvh/txampext
python
https://github.com/lvh/txampext/blob/a7d6cb9f1e9200dba597378cd40eb6a2096d4fd9/txampext/multiplexing.py#L303-L317
[ "def", "dataReceived", "(", "self", ",", "data", ")", ":", "log", ".", "msg", "(", "\"{} bytes of data received locally\"", ".", "format", "(", "len", "(", "data", ")", ")", ")", "if", "self", ".", "connection", "is", "None", ":", "# we haven't finished connecting yet", "log", ".", "msg", "(", "\"Connection not made yet, buffering...\"", ")", "self", ".", "_buffer", ".", "write", "(", "data", ")", "else", ":", "log", ".", "msg", "(", "\"Sending data...\"", ")", "self", ".", "_sendData", "(", "data", ")" ]
a7d6cb9f1e9200dba597378cd40eb6a2096d4fd9
test
ProxyingProtocol._sendData
Actually sends data over the wire.
txampext/multiplexing.py
def _sendData(self, data): """Actually sends data over the wire. """ d = self._callRemote(Transmit, connection=self.connection, data=data) d.addErrback(log.err)
def _sendData(self, data): """Actually sends data over the wire. """ d = self._callRemote(Transmit, connection=self.connection, data=data) d.addErrback(log.err)
[ "Actually", "sends", "data", "over", "the", "wire", "." ]
lvh/txampext
python
https://github.com/lvh/txampext/blob/a7d6cb9f1e9200dba597378cd40eb6a2096d4fd9/txampext/multiplexing.py#L320-L325
[ "def", "_sendData", "(", "self", ",", "data", ")", ":", "d", "=", "self", ".", "_callRemote", "(", "Transmit", ",", "connection", "=", "self", ".", "connection", ",", "data", "=", "data", ")", "d", ".", "addErrback", "(", "log", ".", "err", ")" ]
a7d6cb9f1e9200dba597378cd40eb6a2096d4fd9
test
ProxyingProtocol.connectionLost
If we already have an AMP connection registered on the factory, get rid of it.
txampext/multiplexing.py
def connectionLost(self, reason): """If we already have an AMP connection registered on the factory, get rid of it. """ if self.connection is not None: del self.factory.protocols[self.connection]
def connectionLost(self, reason): """If we already have an AMP connection registered on the factory, get rid of it. """ if self.connection is not None: del self.factory.protocols[self.connection]
[ "If", "we", "already", "have", "an", "AMP", "connection", "registered", "on", "the", "factory", "get", "rid", "of", "it", "." ]
lvh/txampext
python
https://github.com/lvh/txampext/blob/a7d6cb9f1e9200dba597378cd40eb6a2096d4fd9/txampext/multiplexing.py#L328-L334
[ "def", "connectionLost", "(", "self", ",", "reason", ")", ":", "if", "self", ".", "connection", "is", "not", "None", ":", "del", "self", ".", "factory", ".", "protocols", "[", "self", ".", "connection", "]" ]
a7d6cb9f1e9200dba597378cd40eb6a2096d4fd9
test
ProxyingAMPLocator.getLocalProtocol
Attempts to get a local protocol by connection identifier.
txampext/multiplexing.py
def getLocalProtocol(self, connectionIdentifier): """Attempts to get a local protocol by connection identifier. """ for factory in self.localFactories: try: return factory.protocols[connectionIdentifier] except KeyError: continue raise NoSuchConnection()
def getLocalProtocol(self, connectionIdentifier): """Attempts to get a local protocol by connection identifier. """ for factory in self.localFactories: try: return factory.protocols[connectionIdentifier] except KeyError: continue raise NoSuchConnection()
[ "Attempts", "to", "get", "a", "local", "protocol", "by", "connection", "identifier", "." ]
lvh/txampext
python
https://github.com/lvh/txampext/blob/a7d6cb9f1e9200dba597378cd40eb6a2096d4fd9/txampext/multiplexing.py#L363-L373
[ "def", "getLocalProtocol", "(", "self", ",", "connectionIdentifier", ")", ":", "for", "factory", "in", "self", ".", "localFactories", ":", "try", ":", "return", "factory", ".", "protocols", "[", "connectionIdentifier", "]", "except", "KeyError", ":", "continue", "raise", "NoSuchConnection", "(", ")" ]
a7d6cb9f1e9200dba597378cd40eb6a2096d4fd9
test
ProxyingAMPLocator.remoteDataReceived
Some data was received from the remote end. Find the matching protocol and replay it.
txampext/multiplexing.py
def remoteDataReceived(self, connection, data): """Some data was received from the remote end. Find the matching protocol and replay it. """ proto = self.getLocalProtocol(connection) proto.transport.write(data) return {}
def remoteDataReceived(self, connection, data): """Some data was received from the remote end. Find the matching protocol and replay it. """ proto = self.getLocalProtocol(connection) proto.transport.write(data) return {}
[ "Some", "data", "was", "received", "from", "the", "remote", "end", ".", "Find", "the", "matching", "protocol", "and", "replay", "it", "." ]
lvh/txampext
python
https://github.com/lvh/txampext/blob/a7d6cb9f1e9200dba597378cd40eb6a2096d4fd9/txampext/multiplexing.py#L377-L384
[ "def", "remoteDataReceived", "(", "self", ",", "connection", ",", "data", ")", ":", "proto", "=", "self", ".", "getLocalProtocol", "(", "connection", ")", "proto", ".", "transport", ".", "write", "(", "data", ")", "return", "{", "}" ]
a7d6cb9f1e9200dba597378cd40eb6a2096d4fd9
test
ProxyingAMPLocator.disconnect
The other side has asked us to disconnect.
txampext/multiplexing.py
def disconnect(self, connection): """The other side has asked us to disconnect. """ proto = self.getLocalProtocol(connection) proto.transport.loseConnection() return {}
def disconnect(self, connection): """The other side has asked us to disconnect. """ proto = self.getLocalProtocol(connection) proto.transport.loseConnection() return {}
[ "The", "other", "side", "has", "asked", "us", "to", "disconnect", "." ]
lvh/txampext
python
https://github.com/lvh/txampext/blob/a7d6cb9f1e9200dba597378cd40eb6a2096d4fd9/txampext/multiplexing.py#L388-L394
[ "def", "disconnect", "(", "self", ",", "connection", ")", ":", "proto", "=", "self", ".", "getLocalProtocol", "(", "connection", ")", "proto", ".", "transport", ".", "loseConnection", "(", ")", "return", "{", "}" ]
a7d6cb9f1e9200dba597378cd40eb6a2096d4fd9
test
ByteQueue.enqueue
Append `s` to the queue. Equivalent to:: queue += s if `queue` where a regular string.
anycall/bytequeue.py
def enqueue(self, s): """ Append `s` to the queue. Equivalent to:: queue += s if `queue` where a regular string. """ self._parts.append(s) self._len += len(s)
def enqueue(self, s): """ Append `s` to the queue. Equivalent to:: queue += s if `queue` where a regular string. """ self._parts.append(s) self._len += len(s)
[ "Append", "s", "to", "the", "queue", ".", "Equivalent", "to", "::", "queue", "+", "=", "s", "if", "queue", "where", "a", "regular", "string", "." ]
pydron/anycall
python
https://github.com/pydron/anycall/blob/43add96660258a14b24aa8e8413dffb1741b72d7/anycall/bytequeue.py#L19-L30
[ "def", "enqueue", "(", "self", ",", "s", ")", ":", "self", ".", "_parts", ".", "append", "(", "s", ")", "self", ".", "_len", "+=", "len", "(", "s", ")" ]
43add96660258a14b24aa8e8413dffb1741b72d7
test
ByteQueue.dequeue
Remove and return the first `n` characters from the queue. Throws an error if there are less than `n` characters in the queue. Equivalent to:: s = queue[:n] queue = queue[n:] if `queue` where a regular string.
anycall/bytequeue.py
def dequeue(self, n): """ Remove and return the first `n` characters from the queue. Throws an error if there are less than `n` characters in the queue. Equivalent to:: s = queue[:n] queue = queue[n:] if `queue` where a regular string. """ if self._len < n: raise ValueError("Not enough bytes in the queue") self._len -= n def part_generator(n): """ Returns the requested bytes in parts """ remaining = n while remaining: part = self._parts.popleft() if len(part) <= remaining: yield part remaining -= len(part) else: yield part[:remaining] self._parts.appendleft(part[remaining:]) remaining = 0 return "".join(part_generator(n))
def dequeue(self, n): """ Remove and return the first `n` characters from the queue. Throws an error if there are less than `n` characters in the queue. Equivalent to:: s = queue[:n] queue = queue[n:] if `queue` where a regular string. """ if self._len < n: raise ValueError("Not enough bytes in the queue") self._len -= n def part_generator(n): """ Returns the requested bytes in parts """ remaining = n while remaining: part = self._parts.popleft() if len(part) <= remaining: yield part remaining -= len(part) else: yield part[:remaining] self._parts.appendleft(part[remaining:]) remaining = 0 return "".join(part_generator(n))
[ "Remove", "and", "return", "the", "first", "n", "characters", "from", "the", "queue", ".", "Throws", "an", "error", "if", "there", "are", "less", "than", "n", "characters", "in", "the", "queue", ".", "Equivalent", "to", "::", "s", "=", "queue", "[", ":", "n", "]", "queue", "=", "queue", "[", "n", ":", "]", "if", "queue", "where", "a", "regular", "string", "." ]
pydron/anycall
python
https://github.com/pydron/anycall/blob/43add96660258a14b24aa8e8413dffb1741b72d7/anycall/bytequeue.py#L32-L63
[ "def", "dequeue", "(", "self", ",", "n", ")", ":", "if", "self", ".", "_len", "<", "n", ":", "raise", "ValueError", "(", "\"Not enough bytes in the queue\"", ")", "self", ".", "_len", "-=", "n", "def", "part_generator", "(", "n", ")", ":", "\"\"\"\n Returns the requested bytes in parts\n \"\"\"", "remaining", "=", "n", "while", "remaining", ":", "part", "=", "self", ".", "_parts", ".", "popleft", "(", ")", "if", "len", "(", "part", ")", "<=", "remaining", ":", "yield", "part", "remaining", "-=", "len", "(", "part", ")", "else", ":", "yield", "part", "[", ":", "remaining", "]", "self", ".", "_parts", ".", "appendleft", "(", "part", "[", "remaining", ":", "]", ")", "remaining", "=", "0", "return", "\"\"", ".", "join", "(", "part_generator", "(", "n", ")", ")" ]
43add96660258a14b24aa8e8413dffb1741b72d7
test
ByteQueue.drop
Removes `n` bytes from the beginning of the queue. Throws an error if there are less than `n` characters in the queue. Equivalent to:: queue = queue[n:] if `queue` where a regular string.
anycall/bytequeue.py
def drop(self, n): """ Removes `n` bytes from the beginning of the queue. Throws an error if there are less than `n` characters in the queue. Equivalent to:: queue = queue[n:] if `queue` where a regular string. """ if self._len < n: raise ValueError("Not enough bytes in the queue") self._len -= n remaining = n while remaining: part = self._parts.popleft() if len(part) <= remaining: remaining -= len(part) else: self._parts.appendleft(part[remaining:]) remaining = 0
def drop(self, n): """ Removes `n` bytes from the beginning of the queue. Throws an error if there are less than `n` characters in the queue. Equivalent to:: queue = queue[n:] if `queue` where a regular string. """ if self._len < n: raise ValueError("Not enough bytes in the queue") self._len -= n remaining = n while remaining: part = self._parts.popleft() if len(part) <= remaining: remaining -= len(part) else: self._parts.appendleft(part[remaining:]) remaining = 0
[ "Removes", "n", "bytes", "from", "the", "beginning", "of", "the", "queue", ".", "Throws", "an", "error", "if", "there", "are", "less", "than", "n", "characters", "in", "the", "queue", ".", "Equivalent", "to", "::", "queue", "=", "queue", "[", "n", ":", "]", "if", "queue", "where", "a", "regular", "string", "." ]
pydron/anycall
python
https://github.com/pydron/anycall/blob/43add96660258a14b24aa8e8413dffb1741b72d7/anycall/bytequeue.py#L65-L89
[ "def", "drop", "(", "self", ",", "n", ")", ":", "if", "self", ".", "_len", "<", "n", ":", "raise", "ValueError", "(", "\"Not enough bytes in the queue\"", ")", "self", ".", "_len", "-=", "n", "remaining", "=", "n", "while", "remaining", ":", "part", "=", "self", ".", "_parts", ".", "popleft", "(", ")", "if", "len", "(", "part", ")", "<=", "remaining", ":", "remaining", "-=", "len", "(", "part", ")", "else", ":", "self", ".", "_parts", ".", "appendleft", "(", "part", "[", "remaining", ":", "]", ")", "remaining", "=", "0" ]
43add96660258a14b24aa8e8413dffb1741b72d7
test
ByteQueue.peek
Return the first `n` characters from the queue without removing them. Throws an error if there are less than `n` characters in the queue. Equivalent to:: s = queue[:n] if `queue` where a regular string.
anycall/bytequeue.py
def peek(self, n): """ Return the first `n` characters from the queue without removing them. Throws an error if there are less than `n` characters in the queue. Equivalent to:: s = queue[:n] if `queue` where a regular string. """ if self._len < n: raise ValueError("Not enough bytes in the queue") def part_generator(n): """ Returns the requested bytes in parts """ remaining = n for part in self._parts: if len(part) <= remaining: yield part remaining -= len(part) else: yield part[:remaining] remaining = 0 if remaining == 0: break return "".join(part_generator(n))
def peek(self, n): """ Return the first `n` characters from the queue without removing them. Throws an error if there are less than `n` characters in the queue. Equivalent to:: s = queue[:n] if `queue` where a regular string. """ if self._len < n: raise ValueError("Not enough bytes in the queue") def part_generator(n): """ Returns the requested bytes in parts """ remaining = n for part in self._parts: if len(part) <= remaining: yield part remaining -= len(part) else: yield part[:remaining] remaining = 0 if remaining == 0: break return "".join(part_generator(n))
[ "Return", "the", "first", "n", "characters", "from", "the", "queue", "without", "removing", "them", ".", "Throws", "an", "error", "if", "there", "are", "less", "than", "n", "characters", "in", "the", "queue", ".", "Equivalent", "to", "::", "s", "=", "queue", "[", ":", "n", "]", "if", "queue", "where", "a", "regular", "string", "." ]
pydron/anycall
python
https://github.com/pydron/anycall/blob/43add96660258a14b24aa8e8413dffb1741b72d7/anycall/bytequeue.py#L93-L125
[ "def", "peek", "(", "self", ",", "n", ")", ":", "if", "self", ".", "_len", "<", "n", ":", "raise", "ValueError", "(", "\"Not enough bytes in the queue\"", ")", "def", "part_generator", "(", "n", ")", ":", "\"\"\"\n Returns the requested bytes in parts\n \"\"\"", "remaining", "=", "n", "for", "part", "in", "self", ".", "_parts", ":", "if", "len", "(", "part", ")", "<=", "remaining", ":", "yield", "part", "remaining", "-=", "len", "(", "part", ")", "else", ":", "yield", "part", "[", ":", "remaining", "]", "remaining", "=", "0", "if", "remaining", "==", "0", ":", "break", "return", "\"\"", ".", "join", "(", "part_generator", "(", "n", ")", ")" ]
43add96660258a14b24aa8e8413dffb1741b72d7
test
centered
Takes a string, centres it, and pads it on both sides
minchin/text.py
def centered(mystring, linewidth=None, fill=" "): '''Takes a string, centres it, and pads it on both sides''' if linewidth is None: linewidth = get_terminal_size().columns - 1 sides = (linewidth - length_no_ansi(mystring))//2 extra = (linewidth - length_no_ansi(mystring)) % 2 fill = fill[:1] sidestring = fill*sides extrastring = fill*extra newstring = sidestring + mystring + sidestring + extrastring return newstring
def centered(mystring, linewidth=None, fill=" "): '''Takes a string, centres it, and pads it on both sides''' if linewidth is None: linewidth = get_terminal_size().columns - 1 sides = (linewidth - length_no_ansi(mystring))//2 extra = (linewidth - length_no_ansi(mystring)) % 2 fill = fill[:1] sidestring = fill*sides extrastring = fill*extra newstring = sidestring + mystring + sidestring + extrastring return newstring
[ "Takes", "a", "string", "centres", "it", "and", "pads", "it", "on", "both", "sides" ]
MinchinWeb/minchin.text
python
https://github.com/MinchinWeb/minchin.text/blob/4d136039561892c3adab49fe81b2f246e5a1507b/minchin/text.py#L85-L95
[ "def", "centered", "(", "mystring", ",", "linewidth", "=", "None", ",", "fill", "=", "\" \"", ")", ":", "if", "linewidth", "is", "None", ":", "linewidth", "=", "get_terminal_size", "(", ")", ".", "columns", "-", "1", "sides", "=", "(", "linewidth", "-", "length_no_ansi", "(", "mystring", ")", ")", "//", "2", "extra", "=", "(", "linewidth", "-", "length_no_ansi", "(", "mystring", ")", ")", "%", "2", "fill", "=", "fill", "[", ":", "1", "]", "sidestring", "=", "fill", "*", "sides", "extrastring", "=", "fill", "*", "extra", "newstring", "=", "sidestring", "+", "mystring", "+", "sidestring", "+", "extrastring", "return", "newstring" ]
4d136039561892c3adab49fe81b2f246e5a1507b
test
clock_on_right
Takes a string, and prints it with the time right aligned
minchin/text.py
def clock_on_right(mystring): '''Takes a string, and prints it with the time right aligned''' taken = length_no_ansi(mystring) padding = (get_terminal_size().columns - 1) - taken - 5 clock = time.strftime("%I:%M", time.localtime()) print(mystring + " "*padding + clock)
def clock_on_right(mystring): '''Takes a string, and prints it with the time right aligned''' taken = length_no_ansi(mystring) padding = (get_terminal_size().columns - 1) - taken - 5 clock = time.strftime("%I:%M", time.localtime()) print(mystring + " "*padding + clock)
[ "Takes", "a", "string", "and", "prints", "it", "with", "the", "time", "right", "aligned" ]
MinchinWeb/minchin.text
python
https://github.com/MinchinWeb/minchin.text/blob/4d136039561892c3adab49fe81b2f246e5a1507b/minchin/text.py#L98-L103
[ "def", "clock_on_right", "(", "mystring", ")", ":", "taken", "=", "length_no_ansi", "(", "mystring", ")", "padding", "=", "(", "get_terminal_size", "(", ")", ".", "columns", "-", "1", ")", "-", "taken", "-", "5", "clock", "=", "time", ".", "strftime", "(", "\"%I:%M\"", ",", "time", ".", "localtime", "(", ")", ")", "print", "(", "mystring", "+", "\" \"", "*", "padding", "+", "clock", ")" ]
4d136039561892c3adab49fe81b2f246e5a1507b
test
query_yes_no
Ask a yes/no question via raw_input() and return their answer. "question" is a string that is presented to the user. "default" is the presumed answer if the user just hits <Enter>. It must be "yes" (the default), "no" or None (meaning an answer is required of the user). The return value is one of Answers.YES or Answers.NO. Copied (and modified) from http://stackoverflow.com/questions/3041986/python-command-line-yes-no-input
minchin/text.py
def query_yes_no(question, default="yes"): '''Ask a yes/no question via raw_input() and return their answer. "question" is a string that is presented to the user. "default" is the presumed answer if the user just hits <Enter>. It must be "yes" (the default), "no" or None (meaning an answer is required of the user). The return value is one of Answers.YES or Answers.NO. Copied (and modified) from http://stackoverflow.com/questions/3041986/python-command-line-yes-no-input ''' valid = {"yes": Answers.YES, "y": Answers.YES, "ye": Answers.YES, "no": Answers.NO, "n": Answers.NO} if default is None: prompt = " [y/n] " elif default == "yes": prompt = " [Y/n] " elif default == "no": prompt = " [y/N] " else: raise ValueError("invalid default answer: '%s'" % default) while True: sys.stdout.write(question + prompt) choice = input().lower() if default is not None and choice == '': return valid[default] elif choice in valid: return valid[choice] else: sys.stdout.write("Please respond with 'yes' or 'no' " "(or 'y' or 'n').\n")
def query_yes_no(question, default="yes"): '''Ask a yes/no question via raw_input() and return their answer. "question" is a string that is presented to the user. "default" is the presumed answer if the user just hits <Enter>. It must be "yes" (the default), "no" or None (meaning an answer is required of the user). The return value is one of Answers.YES or Answers.NO. Copied (and modified) from http://stackoverflow.com/questions/3041986/python-command-line-yes-no-input ''' valid = {"yes": Answers.YES, "y": Answers.YES, "ye": Answers.YES, "no": Answers.NO, "n": Answers.NO} if default is None: prompt = " [y/n] " elif default == "yes": prompt = " [Y/n] " elif default == "no": prompt = " [y/N] " else: raise ValueError("invalid default answer: '%s'" % default) while True: sys.stdout.write(question + prompt) choice = input().lower() if default is not None and choice == '': return valid[default] elif choice in valid: return valid[choice] else: sys.stdout.write("Please respond with 'yes' or 'no' " "(or 'y' or 'n').\n")
[ "Ask", "a", "yes", "/", "no", "question", "via", "raw_input", "()", "and", "return", "their", "answer", "." ]
MinchinWeb/minchin.text
python
https://github.com/MinchinWeb/minchin.text/blob/4d136039561892c3adab49fe81b2f246e5a1507b/minchin/text.py#L106-L139
[ "def", "query_yes_no", "(", "question", ",", "default", "=", "\"yes\"", ")", ":", "valid", "=", "{", "\"yes\"", ":", "Answers", ".", "YES", ",", "\"y\"", ":", "Answers", ".", "YES", ",", "\"ye\"", ":", "Answers", ".", "YES", ",", "\"no\"", ":", "Answers", ".", "NO", ",", "\"n\"", ":", "Answers", ".", "NO", "}", "if", "default", "is", "None", ":", "prompt", "=", "\" [y/n] \"", "elif", "default", "==", "\"yes\"", ":", "prompt", "=", "\" [Y/n] \"", "elif", "default", "==", "\"no\"", ":", "prompt", "=", "\" [y/N] \"", "else", ":", "raise", "ValueError", "(", "\"invalid default answer: '%s'\"", "%", "default", ")", "while", "True", ":", "sys", ".", "stdout", ".", "write", "(", "question", "+", "prompt", ")", "choice", "=", "input", "(", ")", ".", "lower", "(", ")", "if", "default", "is", "not", "None", "and", "choice", "==", "''", ":", "return", "valid", "[", "default", "]", "elif", "choice", "in", "valid", ":", "return", "valid", "[", "choice", "]", "else", ":", "sys", ".", "stdout", ".", "write", "(", "\"Please respond with 'yes' or 'no' \"", "\"(or 'y' or 'n').\\n\"", ")" ]
4d136039561892c3adab49fe81b2f246e5a1507b
test
query_yes_quit
Ask a yes/quit question via raw_input() and return their answer. "question" is a string that is presented to the user. "default" is the presumed answer if the user just hits <Enter>. It must be "yes" (the default), "quit" or None (meaning an answer is required of the user). The "answer" return value is one of "yes" or "quit". Modified from http://stackoverflow.com/questions/3041986/python-command-line-yes-no-input
minchin/text.py
def query_yes_quit(question, default="quit"): '''Ask a yes/quit question via raw_input() and return their answer. "question" is a string that is presented to the user. "default" is the presumed answer if the user just hits <Enter>. It must be "yes" (the default), "quit" or None (meaning an answer is required of the user). The "answer" return value is one of "yes" or "quit". Modified from http://stackoverflow.com/questions/3041986/python-command-line-yes-no-input ''' valid = {"yes": Answers.YES, "y": Answers.YES, "ye": Answers.YES, "quit": Answers.QUIT, "q": Answers.QUIT} if default is None: prompt = " [y/q] " elif default == "yes": prompt = " [Y/q] " elif default == "quit": prompt = " [y/Q] " else: raise ValueError("invalid default answer: '%s'" % default) while True: sys.stdout.write(question + prompt) choice = input().lower() if default is not None and choice == '': return valid[default] elif choice in valid: return valid[choice] else: sys.stdout.write("Please respond with 'yes' or 'quit' " "(or 'y' or 'q').\n")
def query_yes_quit(question, default="quit"): '''Ask a yes/quit question via raw_input() and return their answer. "question" is a string that is presented to the user. "default" is the presumed answer if the user just hits <Enter>. It must be "yes" (the default), "quit" or None (meaning an answer is required of the user). The "answer" return value is one of "yes" or "quit". Modified from http://stackoverflow.com/questions/3041986/python-command-line-yes-no-input ''' valid = {"yes": Answers.YES, "y": Answers.YES, "ye": Answers.YES, "quit": Answers.QUIT, "q": Answers.QUIT} if default is None: prompt = " [y/q] " elif default == "yes": prompt = " [Y/q] " elif default == "quit": prompt = " [y/Q] " else: raise ValueError("invalid default answer: '%s'" % default) while True: sys.stdout.write(question + prompt) choice = input().lower() if default is not None and choice == '': return valid[default] elif choice in valid: return valid[choice] else: sys.stdout.write("Please respond with 'yes' or 'quit' " "(or 'y' or 'q').\n")
[ "Ask", "a", "yes", "/", "quit", "question", "via", "raw_input", "()", "and", "return", "their", "answer", "." ]
MinchinWeb/minchin.text
python
https://github.com/MinchinWeb/minchin.text/blob/4d136039561892c3adab49fe81b2f246e5a1507b/minchin/text.py#L217-L250
[ "def", "query_yes_quit", "(", "question", ",", "default", "=", "\"quit\"", ")", ":", "valid", "=", "{", "\"yes\"", ":", "Answers", ".", "YES", ",", "\"y\"", ":", "Answers", ".", "YES", ",", "\"ye\"", ":", "Answers", ".", "YES", ",", "\"quit\"", ":", "Answers", ".", "QUIT", ",", "\"q\"", ":", "Answers", ".", "QUIT", "}", "if", "default", "is", "None", ":", "prompt", "=", "\" [y/q] \"", "elif", "default", "==", "\"yes\"", ":", "prompt", "=", "\" [Y/q] \"", "elif", "default", "==", "\"quit\"", ":", "prompt", "=", "\" [y/Q] \"", "else", ":", "raise", "ValueError", "(", "\"invalid default answer: '%s'\"", "%", "default", ")", "while", "True", ":", "sys", ".", "stdout", ".", "write", "(", "question", "+", "prompt", ")", "choice", "=", "input", "(", ")", ".", "lower", "(", ")", "if", "default", "is", "not", "None", "and", "choice", "==", "''", ":", "return", "valid", "[", "default", "]", "elif", "choice", "in", "valid", ":", "return", "valid", "[", "choice", "]", "else", ":", "sys", ".", "stdout", ".", "write", "(", "\"Please respond with 'yes' or 'quit' \"", "\"(or 'y' or 'q').\\n\"", ")" ]
4d136039561892c3adab49fe81b2f246e5a1507b
test
wait
Prints a timer with the format 0:00 to the console, and then clears the line when the timer is done
minchin/text.py
def wait(sec): ''' Prints a timer with the format 0:00 to the console, and then clears the line when the timer is done ''' while sec > 0: sys.stdout.write('\r' + str(sec//60).zfill(1) + ":" + str(sec % 60).zfill(2) + ' ') sec -= 1 time.sleep(1) sys.stdout.write('\r' + ' ' + '\r')
def wait(sec): ''' Prints a timer with the format 0:00 to the console, and then clears the line when the timer is done ''' while sec > 0: sys.stdout.write('\r' + str(sec//60).zfill(1) + ":" + str(sec % 60).zfill(2) + ' ') sec -= 1 time.sleep(1) sys.stdout.write('\r' + ' ' + '\r')
[ "Prints", "a", "timer", "with", "the", "format", "0", ":", "00", "to", "the", "console", "and", "then", "clears", "the", "line", "when", "the", "timer", "is", "done" ]
MinchinWeb/minchin.text
python
https://github.com/MinchinWeb/minchin.text/blob/4d136039561892c3adab49fe81b2f246e5a1507b/minchin/text.py#L253-L263
[ "def", "wait", "(", "sec", ")", ":", "while", "sec", ">", "0", ":", "sys", ".", "stdout", ".", "write", "(", "'\\r'", "+", "str", "(", "sec", "//", "60", ")", ".", "zfill", "(", "1", ")", "+", "\":\"", "+", "str", "(", "sec", "%", "60", ")", ".", "zfill", "(", "2", ")", "+", "' '", ")", "sec", "-=", "1", "time", ".", "sleep", "(", "1", ")", "sys", ".", "stdout", ".", "write", "(", "'\\r'", "+", "' '", "+", "'\\r'", ")" ]
4d136039561892c3adab49fe81b2f246e5a1507b
test
version_number_str
Takes the parts of a semantic version number, and returns a nicely formatted string.
minchin/text.py
def version_number_str(major, minor=0, patch=0, prerelease=None, build=None): """ Takes the parts of a semantic version number, and returns a nicely formatted string. """ version = str(major) + '.' + str(minor) + '.' + str(patch) if prerelease: if prerelease.startswith('-'): version = version + prerelease else: version = version + "-" + str(prerelease) if build: if build.startswith('+'): version = version + build else: version = version + "+" + str(build) return(version)
def version_number_str(major, minor=0, patch=0, prerelease=None, build=None): """ Takes the parts of a semantic version number, and returns a nicely formatted string. """ version = str(major) + '.' + str(minor) + '.' + str(patch) if prerelease: if prerelease.startswith('-'): version = version + prerelease else: version = version + "-" + str(prerelease) if build: if build.startswith('+'): version = version + build else: version = version + "+" + str(build) return(version)
[ "Takes", "the", "parts", "of", "a", "semantic", "version", "number", "and", "returns", "a", "nicely", "formatted", "string", "." ]
MinchinWeb/minchin.text
python
https://github.com/MinchinWeb/minchin.text/blob/4d136039561892c3adab49fe81b2f246e5a1507b/minchin/text.py#L333-L349
[ "def", "version_number_str", "(", "major", ",", "minor", "=", "0", ",", "patch", "=", "0", ",", "prerelease", "=", "None", ",", "build", "=", "None", ")", ":", "version", "=", "str", "(", "major", ")", "+", "'.'", "+", "str", "(", "minor", ")", "+", "'.'", "+", "str", "(", "patch", ")", "if", "prerelease", ":", "if", "prerelease", ".", "startswith", "(", "'-'", ")", ":", "version", "=", "version", "+", "prerelease", "else", ":", "version", "=", "version", "+", "\"-\"", "+", "str", "(", "prerelease", ")", "if", "build", ":", "if", "build", ".", "startswith", "(", "'+'", ")", ":", "version", "=", "version", "+", "build", "else", ":", "version", "=", "version", "+", "\"+\"", "+", "str", "(", "build", ")", "return", "(", "version", ")" ]
4d136039561892c3adab49fe81b2f246e5a1507b
test
get_terminal_size
Returns terminal dimensions :return: Returns ``(width, height)``. If there's no terminal to be found, we'll just return ``(80, 24)``.
minchin/text.py
def get_terminal_size(): """Returns terminal dimensions :return: Returns ``(width, height)``. If there's no terminal to be found, we'll just return ``(80, 24)``. """ try: # shutil.get_terminal_size was added to the standard # library in Python 3.3 try: from shutil import get_terminal_size as _get_terminal_size # pylint: disable=no-name-in-module except ImportError: from backports.shutil_get_terminal_size import get_terminal_size as _get_terminal_size # pylint: disable=import-error sz = _get_terminal_size() except ValueError: """ This can result from the 'underlying buffer being detached', which occurs during running the unittest on Windows (but not on Linux?) """ terminal_size = namedtuple('Terminal_Size', 'columns lines') sz = terminal_size(80, 24) return sz
def get_terminal_size(): """Returns terminal dimensions :return: Returns ``(width, height)``. If there's no terminal to be found, we'll just return ``(80, 24)``. """ try: # shutil.get_terminal_size was added to the standard # library in Python 3.3 try: from shutil import get_terminal_size as _get_terminal_size # pylint: disable=no-name-in-module except ImportError: from backports.shutil_get_terminal_size import get_terminal_size as _get_terminal_size # pylint: disable=import-error sz = _get_terminal_size() except ValueError: """ This can result from the 'underlying buffer being detached', which occurs during running the unittest on Windows (but not on Linux?) """ terminal_size = namedtuple('Terminal_Size', 'columns lines') sz = terminal_size(80, 24) return sz
[ "Returns", "terminal", "dimensions", ":", "return", ":", "Returns", "(", "width", "height", ")", ".", "If", "there", "s", "no", "terminal", "to", "be", "found", "we", "ll", "just", "return", "(", "80", "24", ")", "." ]
MinchinWeb/minchin.text
python
https://github.com/MinchinWeb/minchin.text/blob/4d136039561892c3adab49fe81b2f246e5a1507b/minchin/text.py#L352-L374
[ "def", "get_terminal_size", "(", ")", ":", "try", ":", "# shutil.get_terminal_size was added to the standard", "# library in Python 3.3", "try", ":", "from", "shutil", "import", "get_terminal_size", "as", "_get_terminal_size", "# pylint: disable=no-name-in-module", "except", "ImportError", ":", "from", "backports", ".", "shutil_get_terminal_size", "import", "get_terminal_size", "as", "_get_terminal_size", "# pylint: disable=import-error", "sz", "=", "_get_terminal_size", "(", ")", "except", "ValueError", ":", "\"\"\"\n This can result from the 'underlying buffer being detached', which\n occurs during running the unittest on Windows (but not on Linux?)\n \"\"\"", "terminal_size", "=", "namedtuple", "(", "'Terminal_Size'", ",", "'columns lines'", ")", "sz", "=", "terminal_size", "(", "80", ",", "24", ")", "return", "sz" ]
4d136039561892c3adab49fe81b2f246e5a1507b
test
identify_unit_framework
Identify whether the user is requesting unit validation against astropy.units, pint, or quantities.
numtraits.py
def identify_unit_framework(target_unit): """ Identify whether the user is requesting unit validation against astropy.units, pint, or quantities. """ if HAS_ASTROPY: from astropy.units import UnitBase if isinstance(target_unit, UnitBase): return ASTROPY if HAS_PINT: from pint.unit import UnitsContainer if hasattr(target_unit, 'dimensionality') and isinstance(target_unit.dimensionality, UnitsContainer): return PINT if HAS_QUANTITIES: from quantities.unitquantity import IrreducibleUnit from quantities import Quantity if isinstance(target_unit, IrreducibleUnit) or isinstance(target_unit, Quantity): return QUANTITIES raise TraitError("Could not identify unit framework for target unit of type {0}".format(type(target_unit).__name__))
def identify_unit_framework(target_unit): """ Identify whether the user is requesting unit validation against astropy.units, pint, or quantities. """ if HAS_ASTROPY: from astropy.units import UnitBase if isinstance(target_unit, UnitBase): return ASTROPY if HAS_PINT: from pint.unit import UnitsContainer if hasattr(target_unit, 'dimensionality') and isinstance(target_unit.dimensionality, UnitsContainer): return PINT if HAS_QUANTITIES: from quantities.unitquantity import IrreducibleUnit from quantities import Quantity if isinstance(target_unit, IrreducibleUnit) or isinstance(target_unit, Quantity): return QUANTITIES raise TraitError("Could not identify unit framework for target unit of type {0}".format(type(target_unit).__name__))
[ "Identify", "whether", "the", "user", "is", "requesting", "unit", "validation", "against", "astropy", ".", "units", "pint", "or", "quantities", "." ]
astrofrog/numtraits
python
https://github.com/astrofrog/numtraits/blob/d0afadc946e9d81d1d5b6c851530899d6b0e1d7c/numtraits.py#L167-L198
[ "def", "identify_unit_framework", "(", "target_unit", ")", ":", "if", "HAS_ASTROPY", ":", "from", "astropy", ".", "units", "import", "UnitBase", "if", "isinstance", "(", "target_unit", ",", "UnitBase", ")", ":", "return", "ASTROPY", "if", "HAS_PINT", ":", "from", "pint", ".", "unit", "import", "UnitsContainer", "if", "hasattr", "(", "target_unit", ",", "'dimensionality'", ")", "and", "isinstance", "(", "target_unit", ".", "dimensionality", ",", "UnitsContainer", ")", ":", "return", "PINT", "if", "HAS_QUANTITIES", ":", "from", "quantities", ".", "unitquantity", "import", "IrreducibleUnit", "from", "quantities", "import", "Quantity", "if", "isinstance", "(", "target_unit", ",", "IrreducibleUnit", ")", "or", "isinstance", "(", "target_unit", ",", "Quantity", ")", ":", "return", "QUANTITIES", "raise", "TraitError", "(", "\"Could not identify unit framework for target unit of type {0}\"", ".", "format", "(", "type", "(", "target_unit", ")", ".", "__name__", ")", ")" ]
d0afadc946e9d81d1d5b6c851530899d6b0e1d7c
test
assert_unit_convertability
Check that a value has physical type consistent with user-specified units Note that this does not convert the value, only check that the units have the right physical dimensionality. Parameters ---------- name : str The name of the value to check (used for error messages). value : `numpy.ndarray` or instance of `numpy.ndarray` subclass The value to check. target_unit : unit The unit that the value should be convertible to. unit_framework : str The unit framework to use
numtraits.py
def assert_unit_convertability(name, value, target_unit, unit_framework): """ Check that a value has physical type consistent with user-specified units Note that this does not convert the value, only check that the units have the right physical dimensionality. Parameters ---------- name : str The name of the value to check (used for error messages). value : `numpy.ndarray` or instance of `numpy.ndarray` subclass The value to check. target_unit : unit The unit that the value should be convertible to. unit_framework : str The unit framework to use """ if unit_framework == ASTROPY: from astropy.units import Quantity if not isinstance(value, Quantity): raise TraitError("{0} should be given as an Astropy Quantity instance".format(name)) if not target_unit.is_equivalent(value.unit): raise TraitError("{0} should be in units convertible to {1}".format(name, target_unit)) elif unit_framework == PINT: from pint.unit import UnitsContainer if not (hasattr(value, 'dimensionality') and isinstance(value.dimensionality, UnitsContainer)): raise TraitError("{0} should be given as a Pint Quantity instance".format(name)) if value.dimensionality != target_unit.dimensionality: raise TraitError("{0} should be in units convertible to {1}".format(name, target_unit)) elif unit_framework == QUANTITIES: from quantities import Quantity if not isinstance(value, Quantity): raise TraitError("{0} should be given as a quantities Quantity instance".format(name)) if value.dimensionality.simplified != target_unit.dimensionality.simplified: raise TraitError("{0} should be in units convertible to {1}".format(name, target_unit.dimensionality.string))
def assert_unit_convertability(name, value, target_unit, unit_framework): """ Check that a value has physical type consistent with user-specified units Note that this does not convert the value, only check that the units have the right physical dimensionality. Parameters ---------- name : str The name of the value to check (used for error messages). value : `numpy.ndarray` or instance of `numpy.ndarray` subclass The value to check. target_unit : unit The unit that the value should be convertible to. unit_framework : str The unit framework to use """ if unit_framework == ASTROPY: from astropy.units import Quantity if not isinstance(value, Quantity): raise TraitError("{0} should be given as an Astropy Quantity instance".format(name)) if not target_unit.is_equivalent(value.unit): raise TraitError("{0} should be in units convertible to {1}".format(name, target_unit)) elif unit_framework == PINT: from pint.unit import UnitsContainer if not (hasattr(value, 'dimensionality') and isinstance(value.dimensionality, UnitsContainer)): raise TraitError("{0} should be given as a Pint Quantity instance".format(name)) if value.dimensionality != target_unit.dimensionality: raise TraitError("{0} should be in units convertible to {1}".format(name, target_unit)) elif unit_framework == QUANTITIES: from quantities import Quantity if not isinstance(value, Quantity): raise TraitError("{0} should be given as a quantities Quantity instance".format(name)) if value.dimensionality.simplified != target_unit.dimensionality.simplified: raise TraitError("{0} should be in units convertible to {1}".format(name, target_unit.dimensionality.string))
[ "Check", "that", "a", "value", "has", "physical", "type", "consistent", "with", "user", "-", "specified", "units" ]
astrofrog/numtraits
python
https://github.com/astrofrog/numtraits/blob/d0afadc946e9d81d1d5b6c851530899d6b0e1d7c/numtraits.py#L201-L248
[ "def", "assert_unit_convertability", "(", "name", ",", "value", ",", "target_unit", ",", "unit_framework", ")", ":", "if", "unit_framework", "==", "ASTROPY", ":", "from", "astropy", ".", "units", "import", "Quantity", "if", "not", "isinstance", "(", "value", ",", "Quantity", ")", ":", "raise", "TraitError", "(", "\"{0} should be given as an Astropy Quantity instance\"", ".", "format", "(", "name", ")", ")", "if", "not", "target_unit", ".", "is_equivalent", "(", "value", ".", "unit", ")", ":", "raise", "TraitError", "(", "\"{0} should be in units convertible to {1}\"", ".", "format", "(", "name", ",", "target_unit", ")", ")", "elif", "unit_framework", "==", "PINT", ":", "from", "pint", ".", "unit", "import", "UnitsContainer", "if", "not", "(", "hasattr", "(", "value", ",", "'dimensionality'", ")", "and", "isinstance", "(", "value", ".", "dimensionality", ",", "UnitsContainer", ")", ")", ":", "raise", "TraitError", "(", "\"{0} should be given as a Pint Quantity instance\"", ".", "format", "(", "name", ")", ")", "if", "value", ".", "dimensionality", "!=", "target_unit", ".", "dimensionality", ":", "raise", "TraitError", "(", "\"{0} should be in units convertible to {1}\"", ".", "format", "(", "name", ",", "target_unit", ")", ")", "elif", "unit_framework", "==", "QUANTITIES", ":", "from", "quantities", "import", "Quantity", "if", "not", "isinstance", "(", "value", ",", "Quantity", ")", ":", "raise", "TraitError", "(", "\"{0} should be given as a quantities Quantity instance\"", ".", "format", "(", "name", ")", ")", "if", "value", ".", "dimensionality", ".", "simplified", "!=", "target_unit", ".", "dimensionality", ".", "simplified", ":", "raise", "TraitError", "(", "\"{0} should be in units convertible to {1}\"", ".", "format", "(", "name", ",", "target_unit", ".", "dimensionality", ".", "string", ")", ")" ]
d0afadc946e9d81d1d5b6c851530899d6b0e1d7c
test
pad
Apply standard padding. :Parameters: data_to_pad : byte string The data that needs to be padded. block_size : integer The block boundary to use for padding. The output length is guaranteed to be a multiple of ``block_size``. style : string Padding algorithm. It can be *'pkcs7'* (default), *'iso7816'* or *'x923'*. :Return: The original data with the appropriate padding added at the end.
deterministic_encryption_utils/encryption/Padding.py
def pad(data_to_pad, block_size, style='pkcs7'): """Apply standard padding. :Parameters: data_to_pad : byte string The data that needs to be padded. block_size : integer The block boundary to use for padding. The output length is guaranteed to be a multiple of ``block_size``. style : string Padding algorithm. It can be *'pkcs7'* (default), *'iso7816'* or *'x923'*. :Return: The original data with the appropriate padding added at the end. """ padding_len = block_size-len(data_to_pad)%block_size if style == 'pkcs7': padding = bchr(padding_len)*padding_len elif style == 'x923': padding = bchr(0)*(padding_len-1) + bchr(padding_len) elif style == 'iso7816': padding = bchr(128) + bchr(0)*(padding_len-1) else: raise ValueError("Unknown padding style") return data_to_pad + padding
def pad(data_to_pad, block_size, style='pkcs7'): """Apply standard padding. :Parameters: data_to_pad : byte string The data that needs to be padded. block_size : integer The block boundary to use for padding. The output length is guaranteed to be a multiple of ``block_size``. style : string Padding algorithm. It can be *'pkcs7'* (default), *'iso7816'* or *'x923'*. :Return: The original data with the appropriate padding added at the end. """ padding_len = block_size-len(data_to_pad)%block_size if style == 'pkcs7': padding = bchr(padding_len)*padding_len elif style == 'x923': padding = bchr(0)*(padding_len-1) + bchr(padding_len) elif style == 'iso7816': padding = bchr(128) + bchr(0)*(padding_len-1) else: raise ValueError("Unknown padding style") return data_to_pad + padding
[ "Apply", "standard", "padding", "." ]
seiferma/deterministic_encryption_utils
python
https://github.com/seiferma/deterministic_encryption_utils/blob/a747da3cd6daf39b0c26d4d497725e8863af1dd1/deterministic_encryption_utils/encryption/Padding.py#L38-L62
[ "def", "pad", "(", "data_to_pad", ",", "block_size", ",", "style", "=", "'pkcs7'", ")", ":", "padding_len", "=", "block_size", "-", "len", "(", "data_to_pad", ")", "%", "block_size", "if", "style", "==", "'pkcs7'", ":", "padding", "=", "bchr", "(", "padding_len", ")", "*", "padding_len", "elif", "style", "==", "'x923'", ":", "padding", "=", "bchr", "(", "0", ")", "*", "(", "padding_len", "-", "1", ")", "+", "bchr", "(", "padding_len", ")", "elif", "style", "==", "'iso7816'", ":", "padding", "=", "bchr", "(", "128", ")", "+", "bchr", "(", "0", ")", "*", "(", "padding_len", "-", "1", ")", "else", ":", "raise", "ValueError", "(", "\"Unknown padding style\"", ")", "return", "data_to_pad", "+", "padding" ]
a747da3cd6daf39b0c26d4d497725e8863af1dd1
test
unpad
Remove standard padding. :Parameters: padded_data : byte string A piece of data with padding that needs to be stripped. block_size : integer The block boundary to use for padding. The input length must be a multiple of ``block_size``. style : string Padding algorithm. It can be *'pkcs7'* (default), *'iso7816'* or *'x923'*. :Return: Data without padding. :Raises ValueError: if the padding is incorrect.
deterministic_encryption_utils/encryption/Padding.py
def unpad(padded_data, block_size, style='pkcs7'): """Remove standard padding. :Parameters: padded_data : byte string A piece of data with padding that needs to be stripped. block_size : integer The block boundary to use for padding. The input length must be a multiple of ``block_size``. style : string Padding algorithm. It can be *'pkcs7'* (default), *'iso7816'* or *'x923'*. :Return: Data without padding. :Raises ValueError: if the padding is incorrect. """ pdata_len = len(padded_data) if pdata_len % block_size: raise ValueError("Input data is not padded") if style in ('pkcs7', 'x923'): padding_len = bord(padded_data[-1]) if padding_len<1 or padding_len>min(block_size, pdata_len): raise ValueError("Padding is incorrect.") if style == 'pkcs7': if padded_data[-padding_len:]!=bchr(padding_len)*padding_len: raise ValueError("PKCS#7 padding is incorrect.") else: if padded_data[-padding_len:-1]!=bchr(0)*(padding_len-1): raise ValueError("ANSI X.923 padding is incorrect.") elif style == 'iso7816': padding_len = pdata_len - padded_data.rfind(bchr(128)) if padding_len<1 or padding_len>min(block_size, pdata_len): raise ValueError("Padding is incorrect.") if padding_len>1 and padded_data[1-padding_len:]!=bchr(0)*(padding_len-1): raise ValueError("ISO 7816-4 padding is incorrect.") else: raise ValueError("Unknown padding style") return padded_data[:-padding_len]
def unpad(padded_data, block_size, style='pkcs7'): """Remove standard padding. :Parameters: padded_data : byte string A piece of data with padding that needs to be stripped. block_size : integer The block boundary to use for padding. The input length must be a multiple of ``block_size``. style : string Padding algorithm. It can be *'pkcs7'* (default), *'iso7816'* or *'x923'*. :Return: Data without padding. :Raises ValueError: if the padding is incorrect. """ pdata_len = len(padded_data) if pdata_len % block_size: raise ValueError("Input data is not padded") if style in ('pkcs7', 'x923'): padding_len = bord(padded_data[-1]) if padding_len<1 or padding_len>min(block_size, pdata_len): raise ValueError("Padding is incorrect.") if style == 'pkcs7': if padded_data[-padding_len:]!=bchr(padding_len)*padding_len: raise ValueError("PKCS#7 padding is incorrect.") else: if padded_data[-padding_len:-1]!=bchr(0)*(padding_len-1): raise ValueError("ANSI X.923 padding is incorrect.") elif style == 'iso7816': padding_len = pdata_len - padded_data.rfind(bchr(128)) if padding_len<1 or padding_len>min(block_size, pdata_len): raise ValueError("Padding is incorrect.") if padding_len>1 and padded_data[1-padding_len:]!=bchr(0)*(padding_len-1): raise ValueError("ISO 7816-4 padding is incorrect.") else: raise ValueError("Unknown padding style") return padded_data[:-padding_len]
[ "Remove", "standard", "padding", "." ]
seiferma/deterministic_encryption_utils
python
https://github.com/seiferma/deterministic_encryption_utils/blob/a747da3cd6daf39b0c26d4d497725e8863af1dd1/deterministic_encryption_utils/encryption/Padding.py#L64-L102
[ "def", "unpad", "(", "padded_data", ",", "block_size", ",", "style", "=", "'pkcs7'", ")", ":", "pdata_len", "=", "len", "(", "padded_data", ")", "if", "pdata_len", "%", "block_size", ":", "raise", "ValueError", "(", "\"Input data is not padded\"", ")", "if", "style", "in", "(", "'pkcs7'", ",", "'x923'", ")", ":", "padding_len", "=", "bord", "(", "padded_data", "[", "-", "1", "]", ")", "if", "padding_len", "<", "1", "or", "padding_len", ">", "min", "(", "block_size", ",", "pdata_len", ")", ":", "raise", "ValueError", "(", "\"Padding is incorrect.\"", ")", "if", "style", "==", "'pkcs7'", ":", "if", "padded_data", "[", "-", "padding_len", ":", "]", "!=", "bchr", "(", "padding_len", ")", "*", "padding_len", ":", "raise", "ValueError", "(", "\"PKCS#7 padding is incorrect.\"", ")", "else", ":", "if", "padded_data", "[", "-", "padding_len", ":", "-", "1", "]", "!=", "bchr", "(", "0", ")", "*", "(", "padding_len", "-", "1", ")", ":", "raise", "ValueError", "(", "\"ANSI X.923 padding is incorrect.\"", ")", "elif", "style", "==", "'iso7816'", ":", "padding_len", "=", "pdata_len", "-", "padded_data", ".", "rfind", "(", "bchr", "(", "128", ")", ")", "if", "padding_len", "<", "1", "or", "padding_len", ">", "min", "(", "block_size", ",", "pdata_len", ")", ":", "raise", "ValueError", "(", "\"Padding is incorrect.\"", ")", "if", "padding_len", ">", "1", "and", "padded_data", "[", "1", "-", "padding_len", ":", "]", "!=", "bchr", "(", "0", ")", "*", "(", "padding_len", "-", "1", ")", ":", "raise", "ValueError", "(", "\"ISO 7816-4 padding is incorrect.\"", ")", "else", ":", "raise", "ValueError", "(", "\"Unknown padding style\"", ")", "return", "padded_data", "[", ":", "-", "padding_len", "]" ]
a747da3cd6daf39b0c26d4d497725e8863af1dd1
test
make_federation_entity
Construct a :py:class:`fedoidcmsg.entity.FederationEntity` instance based on given configuration. :param config: Federation entity configuration :param eid: Entity ID :param httpcli: A http client instance to use when sending HTTP requests :param verify_ssl: Whether TLS/SSL certificates should be verified :return: A :py:class:`fedoidcmsg.entity.FederationEntity` instance
src/fedoidcmsg/entity.py
def make_federation_entity(config, eid='', httpcli=None, verify_ssl=True): """ Construct a :py:class:`fedoidcmsg.entity.FederationEntity` instance based on given configuration. :param config: Federation entity configuration :param eid: Entity ID :param httpcli: A http client instance to use when sending HTTP requests :param verify_ssl: Whether TLS/SSL certificates should be verified :return: A :py:class:`fedoidcmsg.entity.FederationEntity` instance """ args = {} if not eid: try: eid = config['entity_id'] except KeyError: pass if 'self_signer' in config: self_signer = make_internal_signing_service(config['self_signer'], eid) args['self_signer'] = self_signer try: bundle_cnf = config['fo_bundle'] except KeyError: pass else: _args = dict([(k, v) for k, v in bundle_cnf.items() if k in KJ_SPECS]) if _args: _kj = init_key_jar(**_args) else: _kj = None if 'dir' in bundle_cnf: jb = FSJWKSBundle(eid, _kj, bundle_cnf['dir'], key_conv={'to': quote_plus, 'from': unquote_plus}) else: jb = JWKSBundle(eid, _kj) args['fo_bundle'] = jb for item in ['context', 'entity_id', 'fo_priority', 'mds_owner']: try: args[item] = config[item] except KeyError: pass if 'entity_id' not in args: args['entity_id'] = eid # These are mutually exclusive if 'sms_dir' in config: args['sms_dir'] = config['sms_dir'] return FederationEntityOOB(httpcli, iss=eid, **args) elif 'mds_service' in config: args['verify_ssl'] = verify_ssl args['mds_service'] = config['mds_service'] return FederationEntityAMS(httpcli, iss=eid, **args) elif 'mdss_endpoint' in config: args['verify_ssl'] = verify_ssl # These are mandatory for this type of entity for key in ['mdss_endpoint', 'mdss_owner', 'mdss_keys']: args[key] = config[key] return FederationEntitySwamid(httpcli, iss=eid, **args)
def make_federation_entity(config, eid='', httpcli=None, verify_ssl=True): """ Construct a :py:class:`fedoidcmsg.entity.FederationEntity` instance based on given configuration. :param config: Federation entity configuration :param eid: Entity ID :param httpcli: A http client instance to use when sending HTTP requests :param verify_ssl: Whether TLS/SSL certificates should be verified :return: A :py:class:`fedoidcmsg.entity.FederationEntity` instance """ args = {} if not eid: try: eid = config['entity_id'] except KeyError: pass if 'self_signer' in config: self_signer = make_internal_signing_service(config['self_signer'], eid) args['self_signer'] = self_signer try: bundle_cnf = config['fo_bundle'] except KeyError: pass else: _args = dict([(k, v) for k, v in bundle_cnf.items() if k in KJ_SPECS]) if _args: _kj = init_key_jar(**_args) else: _kj = None if 'dir' in bundle_cnf: jb = FSJWKSBundle(eid, _kj, bundle_cnf['dir'], key_conv={'to': quote_plus, 'from': unquote_plus}) else: jb = JWKSBundle(eid, _kj) args['fo_bundle'] = jb for item in ['context', 'entity_id', 'fo_priority', 'mds_owner']: try: args[item] = config[item] except KeyError: pass if 'entity_id' not in args: args['entity_id'] = eid # These are mutually exclusive if 'sms_dir' in config: args['sms_dir'] = config['sms_dir'] return FederationEntityOOB(httpcli, iss=eid, **args) elif 'mds_service' in config: args['verify_ssl'] = verify_ssl args['mds_service'] = config['mds_service'] return FederationEntityAMS(httpcli, iss=eid, **args) elif 'mdss_endpoint' in config: args['verify_ssl'] = verify_ssl # These are mandatory for this type of entity for key in ['mdss_endpoint', 'mdss_owner', 'mdss_keys']: args[key] = config[key] return FederationEntitySwamid(httpcli, iss=eid, **args)
[ "Construct", "a", ":", "py", ":", "class", ":", "fedoidcmsg", ".", "entity", ".", "FederationEntity", "instance", "based", "on", "given", "configuration", "." ]
IdentityPython/fedoidcmsg
python
https://github.com/IdentityPython/fedoidcmsg/blob/d30107be02521fa6cdfe285da3b6b0cdd153c8cc/src/fedoidcmsg/entity.py#L505-L569
[ "def", "make_federation_entity", "(", "config", ",", "eid", "=", "''", ",", "httpcli", "=", "None", ",", "verify_ssl", "=", "True", ")", ":", "args", "=", "{", "}", "if", "not", "eid", ":", "try", ":", "eid", "=", "config", "[", "'entity_id'", "]", "except", "KeyError", ":", "pass", "if", "'self_signer'", "in", "config", ":", "self_signer", "=", "make_internal_signing_service", "(", "config", "[", "'self_signer'", "]", ",", "eid", ")", "args", "[", "'self_signer'", "]", "=", "self_signer", "try", ":", "bundle_cnf", "=", "config", "[", "'fo_bundle'", "]", "except", "KeyError", ":", "pass", "else", ":", "_args", "=", "dict", "(", "[", "(", "k", ",", "v", ")", "for", "k", ",", "v", "in", "bundle_cnf", ".", "items", "(", ")", "if", "k", "in", "KJ_SPECS", "]", ")", "if", "_args", ":", "_kj", "=", "init_key_jar", "(", "*", "*", "_args", ")", "else", ":", "_kj", "=", "None", "if", "'dir'", "in", "bundle_cnf", ":", "jb", "=", "FSJWKSBundle", "(", "eid", ",", "_kj", ",", "bundle_cnf", "[", "'dir'", "]", ",", "key_conv", "=", "{", "'to'", ":", "quote_plus", ",", "'from'", ":", "unquote_plus", "}", ")", "else", ":", "jb", "=", "JWKSBundle", "(", "eid", ",", "_kj", ")", "args", "[", "'fo_bundle'", "]", "=", "jb", "for", "item", "in", "[", "'context'", ",", "'entity_id'", ",", "'fo_priority'", ",", "'mds_owner'", "]", ":", "try", ":", "args", "[", "item", "]", "=", "config", "[", "item", "]", "except", "KeyError", ":", "pass", "if", "'entity_id'", "not", "in", "args", ":", "args", "[", "'entity_id'", "]", "=", "eid", "# These are mutually exclusive", "if", "'sms_dir'", "in", "config", ":", "args", "[", "'sms_dir'", "]", "=", "config", "[", "'sms_dir'", "]", "return", "FederationEntityOOB", "(", "httpcli", ",", "iss", "=", "eid", ",", "*", "*", "args", ")", "elif", "'mds_service'", "in", "config", ":", "args", "[", "'verify_ssl'", "]", "=", "verify_ssl", "args", "[", "'mds_service'", "]", "=", "config", "[", "'mds_service'", "]", "return", "FederationEntityAMS", "(", "httpcli", ",", "iss", "=", "eid", ",", "*", "*", "args", ")", "elif", "'mdss_endpoint'", "in", "config", ":", "args", "[", "'verify_ssl'", "]", "=", "verify_ssl", "# These are mandatory for this type of entity", "for", "key", "in", "[", "'mdss_endpoint'", ",", "'mdss_owner'", ",", "'mdss_keys'", "]", ":", "args", "[", "key", "]", "=", "config", "[", "key", "]", "return", "FederationEntitySwamid", "(", "httpcli", ",", "iss", "=", "eid", ",", "*", "*", "args", ")" ]
d30107be02521fa6cdfe285da3b6b0cdd153c8cc
test
FederationEntity.pick_signed_metadata_statements_regex
Pick signed metadata statements based on ISS pattern matching :param pattern: A regular expression to match the iss against :return: list of tuples (FO ID, signed metadata statement)
src/fedoidcmsg/entity.py
def pick_signed_metadata_statements_regex(self, pattern, context): """ Pick signed metadata statements based on ISS pattern matching :param pattern: A regular expression to match the iss against :return: list of tuples (FO ID, signed metadata statement) """ comp_pat = re.compile(pattern) sms_dict = self.signer.metadata_statements[context] res = [] for iss, vals in sms_dict.items(): if comp_pat.search(iss): res.extend((iss, vals)) return res
def pick_signed_metadata_statements_regex(self, pattern, context): """ Pick signed metadata statements based on ISS pattern matching :param pattern: A regular expression to match the iss against :return: list of tuples (FO ID, signed metadata statement) """ comp_pat = re.compile(pattern) sms_dict = self.signer.metadata_statements[context] res = [] for iss, vals in sms_dict.items(): if comp_pat.search(iss): res.extend((iss, vals)) return res
[ "Pick", "signed", "metadata", "statements", "based", "on", "ISS", "pattern", "matching", ":", "param", "pattern", ":", "A", "regular", "expression", "to", "match", "the", "iss", "against", ":", "return", ":", "list", "of", "tuples", "(", "FO", "ID", "signed", "metadata", "statement", ")" ]
IdentityPython/fedoidcmsg
python
https://github.com/IdentityPython/fedoidcmsg/blob/d30107be02521fa6cdfe285da3b6b0cdd153c8cc/src/fedoidcmsg/entity.py#L76-L89
[ "def", "pick_signed_metadata_statements_regex", "(", "self", ",", "pattern", ",", "context", ")", ":", "comp_pat", "=", "re", ".", "compile", "(", "pattern", ")", "sms_dict", "=", "self", ".", "signer", ".", "metadata_statements", "[", "context", "]", "res", "=", "[", "]", "for", "iss", ",", "vals", "in", "sms_dict", ".", "items", "(", ")", ":", "if", "comp_pat", ".", "search", "(", "iss", ")", ":", "res", ".", "extend", "(", "(", "iss", ",", "vals", ")", ")", "return", "res" ]
d30107be02521fa6cdfe285da3b6b0cdd153c8cc
test
FederationEntity.pick_signed_metadata_statements
Pick signed metadata statements based on ISS pattern matching :param fo: Federation operators ID :param context: In connect with which operation (one of the values in :py:data:`fedoidc.CONTEXTS`). :return: list of tuples (FO ID, signed metadata statement)
src/fedoidcmsg/entity.py
def pick_signed_metadata_statements(self, fo, context): """ Pick signed metadata statements based on ISS pattern matching :param fo: Federation operators ID :param context: In connect with which operation (one of the values in :py:data:`fedoidc.CONTEXTS`). :return: list of tuples (FO ID, signed metadata statement) """ sms_dict = self.signer.metadata_statements[context] res = [] for iss, vals in sms_dict.items(): if iss == fo: res.extend((iss, vals)) return res
def pick_signed_metadata_statements(self, fo, context): """ Pick signed metadata statements based on ISS pattern matching :param fo: Federation operators ID :param context: In connect with which operation (one of the values in :py:data:`fedoidc.CONTEXTS`). :return: list of tuples (FO ID, signed metadata statement) """ sms_dict = self.signer.metadata_statements[context] res = [] for iss, vals in sms_dict.items(): if iss == fo: res.extend((iss, vals)) return res
[ "Pick", "signed", "metadata", "statements", "based", "on", "ISS", "pattern", "matching", ":", "param", "fo", ":", "Federation", "operators", "ID", ":", "param", "context", ":", "In", "connect", "with", "which", "operation", "(", "one", "of", "the", "values", "in", ":", "py", ":", "data", ":", "fedoidc", ".", "CONTEXTS", ")", ".", ":", "return", ":", "list", "of", "tuples", "(", "FO", "ID", "signed", "metadata", "statement", ")" ]
IdentityPython/fedoidcmsg
python
https://github.com/IdentityPython/fedoidcmsg/blob/d30107be02521fa6cdfe285da3b6b0cdd153c8cc/src/fedoidcmsg/entity.py#L91-L105
[ "def", "pick_signed_metadata_statements", "(", "self", ",", "fo", ",", "context", ")", ":", "sms_dict", "=", "self", ".", "signer", ".", "metadata_statements", "[", "context", "]", "res", "=", "[", "]", "for", "iss", ",", "vals", "in", "sms_dict", ".", "items", "(", ")", ":", "if", "iss", "==", "fo", ":", "res", ".", "extend", "(", "(", "iss", ",", "vals", ")", ")", "return", "res" ]
d30107be02521fa6cdfe285da3b6b0cdd153c8cc
test
FederationEntity.get_metadata_statement
Unpack and evaluate a compound metadata statement. Goes through the necessary three steps. * unpack the metadata statement * verify that the given statements are expected to be used in this context * evaluate the metadata statements (= flatten) :param input: The metadata statement as a JSON document or a dictionary :param cls: The class the response should be typed into :param context: In which context the metadata statement should be used. :return: A list of :py:class:`fedoidc.operator.LessOrEqual` instances
src/fedoidcmsg/entity.py
def get_metadata_statement(self, input, cls=MetadataStatement, context=''): """ Unpack and evaluate a compound metadata statement. Goes through the necessary three steps. * unpack the metadata statement * verify that the given statements are expected to be used in this context * evaluate the metadata statements (= flatten) :param input: The metadata statement as a JSON document or a dictionary :param cls: The class the response should be typed into :param context: In which context the metadata statement should be used. :return: A list of :py:class:`fedoidc.operator.LessOrEqual` instances """ logger.debug('Incoming metadata statement: {}'.format(input)) if isinstance(input, dict): data = input else: if isinstance(input, Message): data = input.to_dict() else: data = json.loads(input) _pi = self.unpack_metadata_statement(ms_dict=data, cls=cls) if not _pi.result: return [] logger.debug('Managed to unpack the metadata statement') if context: _cms = self.correct_usage(_pi.result, context) else: _cms = _pi.result logger.debug('After filtering for correct usage: {}'.format(_cms)) if _cms: return self.evaluate_metadata_statement(_cms) else: return []
def get_metadata_statement(self, input, cls=MetadataStatement, context=''): """ Unpack and evaluate a compound metadata statement. Goes through the necessary three steps. * unpack the metadata statement * verify that the given statements are expected to be used in this context * evaluate the metadata statements (= flatten) :param input: The metadata statement as a JSON document or a dictionary :param cls: The class the response should be typed into :param context: In which context the metadata statement should be used. :return: A list of :py:class:`fedoidc.operator.LessOrEqual` instances """ logger.debug('Incoming metadata statement: {}'.format(input)) if isinstance(input, dict): data = input else: if isinstance(input, Message): data = input.to_dict() else: data = json.loads(input) _pi = self.unpack_metadata_statement(ms_dict=data, cls=cls) if not _pi.result: return [] logger.debug('Managed to unpack the metadata statement') if context: _cms = self.correct_usage(_pi.result, context) else: _cms = _pi.result logger.debug('After filtering for correct usage: {}'.format(_cms)) if _cms: return self.evaluate_metadata_statement(_cms) else: return []
[ "Unpack", "and", "evaluate", "a", "compound", "metadata", "statement", ".", "Goes", "through", "the", "necessary", "three", "steps", ".", "*", "unpack", "the", "metadata", "statement", "*", "verify", "that", "the", "given", "statements", "are", "expected", "to", "be", "used", "in", "this", "context", "*", "evaluate", "the", "metadata", "statements", "(", "=", "flatten", ")" ]
IdentityPython/fedoidcmsg
python
https://github.com/IdentityPython/fedoidcmsg/blob/d30107be02521fa6cdfe285da3b6b0cdd153c8cc/src/fedoidcmsg/entity.py#L107-L148
[ "def", "get_metadata_statement", "(", "self", ",", "input", ",", "cls", "=", "MetadataStatement", ",", "context", "=", "''", ")", ":", "logger", ".", "debug", "(", "'Incoming metadata statement: {}'", ".", "format", "(", "input", ")", ")", "if", "isinstance", "(", "input", ",", "dict", ")", ":", "data", "=", "input", "else", ":", "if", "isinstance", "(", "input", ",", "Message", ")", ":", "data", "=", "input", ".", "to_dict", "(", ")", "else", ":", "data", "=", "json", ".", "loads", "(", "input", ")", "_pi", "=", "self", ".", "unpack_metadata_statement", "(", "ms_dict", "=", "data", ",", "cls", "=", "cls", ")", "if", "not", "_pi", ".", "result", ":", "return", "[", "]", "logger", ".", "debug", "(", "'Managed to unpack the metadata statement'", ")", "if", "context", ":", "_cms", "=", "self", ".", "correct_usage", "(", "_pi", ".", "result", ",", "context", ")", "else", ":", "_cms", "=", "_pi", ".", "result", "logger", ".", "debug", "(", "'After filtering for correct usage: {}'", ".", "format", "(", "_cms", ")", ")", "if", "_cms", ":", "return", "self", ".", "evaluate_metadata_statement", "(", "_cms", ")", "else", ":", "return", "[", "]" ]
d30107be02521fa6cdfe285da3b6b0cdd153c8cc
test
FederationEntity.self_sign
Sign the extended request. :param req: Request, a :py:class:`fedoidcmsg.MetadataStatement' instance :param receiver: The intended user of this metadata statement :param aud: The audience, a list of receivers. :return: An augmented set of request arguments
src/fedoidcmsg/entity.py
def self_sign(self, req, receiver='', aud=None): """ Sign the extended request. :param req: Request, a :py:class:`fedoidcmsg.MetadataStatement' instance :param receiver: The intended user of this metadata statement :param aud: The audience, a list of receivers. :return: An augmented set of request arguments """ if self.entity_id: _iss = self.entity_id else: _iss = self.iss creq = req.copy() if not 'metadata_statement_uris' in creq and not \ 'metadata_statements' in creq: _copy = creq.copy() _jws = self.self_signer.sign(_copy, receiver=receiver, iss=_iss, aud=aud) sms_spec = {'metadata_statements': {self.iss: _jws}} else: for ref in ['metadata_statement_uris', 'metadata_statements']: try: del creq[ref] except KeyError: pass sms_spec = {'metadata_statements': Message()} for ref in ['metadata_statement_uris', 'metadata_statements']: if ref not in req: continue for foid, value in req[ref].items(): _copy = creq.copy() _copy[ref] = Message() _copy[ref][foid] = value _jws = self.self_signer.sign(_copy, receiver=receiver, iss=_iss, aud=aud) sms_spec['metadata_statements'][foid] = _jws creq.update(sms_spec) return creq
def self_sign(self, req, receiver='', aud=None): """ Sign the extended request. :param req: Request, a :py:class:`fedoidcmsg.MetadataStatement' instance :param receiver: The intended user of this metadata statement :param aud: The audience, a list of receivers. :return: An augmented set of request arguments """ if self.entity_id: _iss = self.entity_id else: _iss = self.iss creq = req.copy() if not 'metadata_statement_uris' in creq and not \ 'metadata_statements' in creq: _copy = creq.copy() _jws = self.self_signer.sign(_copy, receiver=receiver, iss=_iss, aud=aud) sms_spec = {'metadata_statements': {self.iss: _jws}} else: for ref in ['metadata_statement_uris', 'metadata_statements']: try: del creq[ref] except KeyError: pass sms_spec = {'metadata_statements': Message()} for ref in ['metadata_statement_uris', 'metadata_statements']: if ref not in req: continue for foid, value in req[ref].items(): _copy = creq.copy() _copy[ref] = Message() _copy[ref][foid] = value _jws = self.self_signer.sign(_copy, receiver=receiver, iss=_iss, aud=aud) sms_spec['metadata_statements'][foid] = _jws creq.update(sms_spec) return creq
[ "Sign", "the", "extended", "request", "." ]
IdentityPython/fedoidcmsg
python
https://github.com/IdentityPython/fedoidcmsg/blob/d30107be02521fa6cdfe285da3b6b0cdd153c8cc/src/fedoidcmsg/entity.py#L150-L193
[ "def", "self_sign", "(", "self", ",", "req", ",", "receiver", "=", "''", ",", "aud", "=", "None", ")", ":", "if", "self", ".", "entity_id", ":", "_iss", "=", "self", ".", "entity_id", "else", ":", "_iss", "=", "self", ".", "iss", "creq", "=", "req", ".", "copy", "(", ")", "if", "not", "'metadata_statement_uris'", "in", "creq", "and", "not", "'metadata_statements'", "in", "creq", ":", "_copy", "=", "creq", ".", "copy", "(", ")", "_jws", "=", "self", ".", "self_signer", ".", "sign", "(", "_copy", ",", "receiver", "=", "receiver", ",", "iss", "=", "_iss", ",", "aud", "=", "aud", ")", "sms_spec", "=", "{", "'metadata_statements'", ":", "{", "self", ".", "iss", ":", "_jws", "}", "}", "else", ":", "for", "ref", "in", "[", "'metadata_statement_uris'", ",", "'metadata_statements'", "]", ":", "try", ":", "del", "creq", "[", "ref", "]", "except", "KeyError", ":", "pass", "sms_spec", "=", "{", "'metadata_statements'", ":", "Message", "(", ")", "}", "for", "ref", "in", "[", "'metadata_statement_uris'", ",", "'metadata_statements'", "]", ":", "if", "ref", "not", "in", "req", ":", "continue", "for", "foid", ",", "value", "in", "req", "[", "ref", "]", ".", "items", "(", ")", ":", "_copy", "=", "creq", ".", "copy", "(", ")", "_copy", "[", "ref", "]", "=", "Message", "(", ")", "_copy", "[", "ref", "]", "[", "foid", "]", "=", "value", "_jws", "=", "self", ".", "self_signer", ".", "sign", "(", "_copy", ",", "receiver", "=", "receiver", ",", "iss", "=", "_iss", ",", "aud", "=", "aud", ")", "sms_spec", "[", "'metadata_statements'", "]", "[", "foid", "]", "=", "_jws", "creq", ".", "update", "(", "sms_spec", ")", "return", "creq" ]
d30107be02521fa6cdfe285da3b6b0cdd153c8cc
test
FederationEntity.update_metadata_statement
Update a metadata statement by: * adding signed metadata statements or uris pointing to signed metadata statements. * adding the entities signing keys * create metadata statements one per signed metadata statement or uri sign these and add them to the metadata statement :param metadata_statement: A :py:class:`fedoidcmsg.MetadataStatement` instance :param receiver: The intended receiver of the metadata statement :param federation: :param context: :return: An augmented metadata statement
src/fedoidcmsg/entity.py
def update_metadata_statement(self, metadata_statement, receiver='', federation=None, context=''): """ Update a metadata statement by: * adding signed metadata statements or uris pointing to signed metadata statements. * adding the entities signing keys * create metadata statements one per signed metadata statement or uri sign these and add them to the metadata statement :param metadata_statement: A :py:class:`fedoidcmsg.MetadataStatement` instance :param receiver: The intended receiver of the metadata statement :param federation: :param context: :return: An augmented metadata statement """ self.add_sms_spec_to_request(metadata_statement, federation=federation, context=context) self.add_signing_keys(metadata_statement) metadata_statement = self.self_sign(metadata_statement, receiver) # These are unprotected here so can as well be removed del metadata_statement['signing_keys'] return metadata_statement
def update_metadata_statement(self, metadata_statement, receiver='', federation=None, context=''): """ Update a metadata statement by: * adding signed metadata statements or uris pointing to signed metadata statements. * adding the entities signing keys * create metadata statements one per signed metadata statement or uri sign these and add them to the metadata statement :param metadata_statement: A :py:class:`fedoidcmsg.MetadataStatement` instance :param receiver: The intended receiver of the metadata statement :param federation: :param context: :return: An augmented metadata statement """ self.add_sms_spec_to_request(metadata_statement, federation=federation, context=context) self.add_signing_keys(metadata_statement) metadata_statement = self.self_sign(metadata_statement, receiver) # These are unprotected here so can as well be removed del metadata_statement['signing_keys'] return metadata_statement
[ "Update", "a", "metadata", "statement", "by", ":", "*", "adding", "signed", "metadata", "statements", "or", "uris", "pointing", "to", "signed", "metadata", "statements", ".", "*", "adding", "the", "entities", "signing", "keys", "*", "create", "metadata", "statements", "one", "per", "signed", "metadata", "statement", "or", "uri", "sign", "these", "and", "add", "them", "to", "the", "metadata", "statement" ]
IdentityPython/fedoidcmsg
python
https://github.com/IdentityPython/fedoidcmsg/blob/d30107be02521fa6cdfe285da3b6b0cdd153c8cc/src/fedoidcmsg/entity.py#L209-L232
[ "def", "update_metadata_statement", "(", "self", ",", "metadata_statement", ",", "receiver", "=", "''", ",", "federation", "=", "None", ",", "context", "=", "''", ")", ":", "self", ".", "add_sms_spec_to_request", "(", "metadata_statement", ",", "federation", "=", "federation", ",", "context", "=", "context", ")", "self", ".", "add_signing_keys", "(", "metadata_statement", ")", "metadata_statement", "=", "self", ".", "self_sign", "(", "metadata_statement", ",", "receiver", ")", "# These are unprotected here so can as well be removed", "del", "metadata_statement", "[", "'signing_keys'", "]", "return", "metadata_statement" ]
d30107be02521fa6cdfe285da3b6b0cdd153c8cc
test
FederationEntityOOB.add_sms_spec_to_request
Update a request with signed metadata statements. :param req: The request :param federation: Federation Operator ID :param loes: List of :py:class:`fedoidc.operator.LessOrEqual` instances :param context: :return: The updated request
src/fedoidcmsg/entity.py
def add_sms_spec_to_request(self, req, federation='', loes=None, context=''): """ Update a request with signed metadata statements. :param req: The request :param federation: Federation Operator ID :param loes: List of :py:class:`fedoidc.operator.LessOrEqual` instances :param context: :return: The updated request """ if federation: # A specific federation or list of federations if isinstance(federation, list): req.update(self.gather_metadata_statements(federation, context=context)) else: req.update(self.gather_metadata_statements([federation], context=context)) else: # All federations I belong to if loes: _fos = list([r.fo for r in loes]) req.update(self.gather_metadata_statements(_fos, context=context)) else: req.update(self.gather_metadata_statements(context=context)) return req
def add_sms_spec_to_request(self, req, federation='', loes=None, context=''): """ Update a request with signed metadata statements. :param req: The request :param federation: Federation Operator ID :param loes: List of :py:class:`fedoidc.operator.LessOrEqual` instances :param context: :return: The updated request """ if federation: # A specific federation or list of federations if isinstance(federation, list): req.update(self.gather_metadata_statements(federation, context=context)) else: req.update(self.gather_metadata_statements([federation], context=context)) else: # All federations I belong to if loes: _fos = list([r.fo for r in loes]) req.update(self.gather_metadata_statements(_fos, context=context)) else: req.update(self.gather_metadata_statements(context=context)) return req
[ "Update", "a", "request", "with", "signed", "metadata", "statements", ".", ":", "param", "req", ":", "The", "request", ":", "param", "federation", ":", "Federation", "Operator", "ID", ":", "param", "loes", ":", "List", "of", ":", "py", ":", "class", ":", "fedoidc", ".", "operator", ".", "LessOrEqual", "instances", ":", "param", "context", ":", ":", "return", ":", "The", "updated", "request" ]
IdentityPython/fedoidcmsg
python
https://github.com/IdentityPython/fedoidcmsg/blob/d30107be02521fa6cdfe285da3b6b0cdd153c8cc/src/fedoidcmsg/entity.py#L267-L293
[ "def", "add_sms_spec_to_request", "(", "self", ",", "req", ",", "federation", "=", "''", ",", "loes", "=", "None", ",", "context", "=", "''", ")", ":", "if", "federation", ":", "# A specific federation or list of federations", "if", "isinstance", "(", "federation", ",", "list", ")", ":", "req", ".", "update", "(", "self", ".", "gather_metadata_statements", "(", "federation", ",", "context", "=", "context", ")", ")", "else", ":", "req", ".", "update", "(", "self", ".", "gather_metadata_statements", "(", "[", "federation", "]", ",", "context", "=", "context", ")", ")", "else", ":", "# All federations I belong to", "if", "loes", ":", "_fos", "=", "list", "(", "[", "r", ".", "fo", "for", "r", "in", "loes", "]", ")", "req", ".", "update", "(", "self", ".", "gather_metadata_statements", "(", "_fos", ",", "context", "=", "context", ")", ")", "else", ":", "req", ".", "update", "(", "self", ".", "gather_metadata_statements", "(", "context", "=", "context", ")", ")", "return", "req" ]
d30107be02521fa6cdfe285da3b6b0cdd153c8cc
test
FederationEntityOOB.gather_metadata_statements
Only gathers metadata statements and returns them. :param fos: Signed metadata statements from these Federation Operators should be added. :param context: context of the metadata exchange :return: Dictionary with signed Metadata Statements as values
src/fedoidcmsg/entity.py
def gather_metadata_statements(self, fos=None, context=''): """ Only gathers metadata statements and returns them. :param fos: Signed metadata statements from these Federation Operators should be added. :param context: context of the metadata exchange :return: Dictionary with signed Metadata Statements as values """ if not context: context = self.context _res = {} if self.metadata_statements: try: cms = self.metadata_statements[context] except KeyError: if self.metadata_statements == { 'register': {}, 'discovery': {}, 'response': {} }: # No superior so an FO then. Nothing to add .. pass else: logger.error( 'No metadata statements for this context: {}'.format( context)) raise ValueError('Wrong context "{}"'.format(context)) else: if cms != {}: if fos is None: fos = list(cms.keys()) for f in fos: try: val = cms[f] except KeyError: continue if val.startswith('http'): value_type = 'metadata_statement_uris' else: value_type = 'metadata_statements' try: _res[value_type][f] = val except KeyError: _res[value_type] = Message() _res[value_type][f] = val return _res
def gather_metadata_statements(self, fos=None, context=''): """ Only gathers metadata statements and returns them. :param fos: Signed metadata statements from these Federation Operators should be added. :param context: context of the metadata exchange :return: Dictionary with signed Metadata Statements as values """ if not context: context = self.context _res = {} if self.metadata_statements: try: cms = self.metadata_statements[context] except KeyError: if self.metadata_statements == { 'register': {}, 'discovery': {}, 'response': {} }: # No superior so an FO then. Nothing to add .. pass else: logger.error( 'No metadata statements for this context: {}'.format( context)) raise ValueError('Wrong context "{}"'.format(context)) else: if cms != {}: if fos is None: fos = list(cms.keys()) for f in fos: try: val = cms[f] except KeyError: continue if val.startswith('http'): value_type = 'metadata_statement_uris' else: value_type = 'metadata_statements' try: _res[value_type][f] = val except KeyError: _res[value_type] = Message() _res[value_type][f] = val return _res
[ "Only", "gathers", "metadata", "statements", "and", "returns", "them", "." ]
IdentityPython/fedoidcmsg
python
https://github.com/IdentityPython/fedoidcmsg/blob/d30107be02521fa6cdfe285da3b6b0cdd153c8cc/src/fedoidcmsg/entity.py#L295-L347
[ "def", "gather_metadata_statements", "(", "self", ",", "fos", "=", "None", ",", "context", "=", "''", ")", ":", "if", "not", "context", ":", "context", "=", "self", ".", "context", "_res", "=", "{", "}", "if", "self", ".", "metadata_statements", ":", "try", ":", "cms", "=", "self", ".", "metadata_statements", "[", "context", "]", "except", "KeyError", ":", "if", "self", ".", "metadata_statements", "==", "{", "'register'", ":", "{", "}", ",", "'discovery'", ":", "{", "}", ",", "'response'", ":", "{", "}", "}", ":", "# No superior so an FO then. Nothing to add ..", "pass", "else", ":", "logger", ".", "error", "(", "'No metadata statements for this context: {}'", ".", "format", "(", "context", ")", ")", "raise", "ValueError", "(", "'Wrong context \"{}\"'", ".", "format", "(", "context", ")", ")", "else", ":", "if", "cms", "!=", "{", "}", ":", "if", "fos", "is", "None", ":", "fos", "=", "list", "(", "cms", ".", "keys", "(", ")", ")", "for", "f", "in", "fos", ":", "try", ":", "val", "=", "cms", "[", "f", "]", "except", "KeyError", ":", "continue", "if", "val", ".", "startswith", "(", "'http'", ")", ":", "value_type", "=", "'metadata_statement_uris'", "else", ":", "value_type", "=", "'metadata_statements'", "try", ":", "_res", "[", "value_type", "]", "[", "f", "]", "=", "val", "except", "KeyError", ":", "_res", "[", "value_type", "]", "=", "Message", "(", ")", "_res", "[", "value_type", "]", "[", "f", "]", "=", "val", "return", "_res" ]
d30107be02521fa6cdfe285da3b6b0cdd153c8cc
test
FederationEntityAMS.add_sms_spec_to_request
Add signed metadata statements to the request :param req: The request so far :param federation: If only signed metadata statements from a specific set of federations should be included this is the set. :param loes: - not used - :param context: What kind of request/response it is: 'registration', 'discovery' or 'response'. The later being registration response. :param url: Just for testing !! :return: A possibly augmented request.
src/fedoidcmsg/entity.py
def add_sms_spec_to_request(self, req, federation='', loes=None, context='', url=''): """ Add signed metadata statements to the request :param req: The request so far :param federation: If only signed metadata statements from a specific set of federations should be included this is the set. :param loes: - not used - :param context: What kind of request/response it is: 'registration', 'discovery' or 'response'. The later being registration response. :param url: Just for testing !! :return: A possibly augmented request. """ # fetch the signed metadata statement collection if federation: if not isinstance(federation, list): federation = [federation] if not url: url = "{}/getms/{}/{}".format(self.mds_service, context, quote_plus(self.entity_id)) http_resp = self.httpcli(method='GET', url=url, verify=self.verify_ssl) if http_resp.status_code >= 400: raise ConnectionError('HTTP Error: {}'.format(http_resp.text)) # verify signature on response msg = JsonWebToken().from_jwt(http_resp.text, keyjar=self.jwks_bundle[self.mds_owner]) if msg['iss'] != self.mds_owner: raise KeyError('Wrong iss') if federation: _ms = dict( [(fo, _ms) for fo, _ms in msg.items() if fo in federation]) else: _ms = msg.extra() try: del _ms['kid'] except KeyError: pass _sms = {} _smsu = {} for fo, item in _ms.items(): if item.startswith('https://') or item.startswith('http://'): _smsu[fo] = item else: _sms[fo] = item if _sms: req.update({'metadata_statements': _sms}) if _smsu: req.update({'metadata_statement_uris': _smsu}) return req
def add_sms_spec_to_request(self, req, federation='', loes=None, context='', url=''): """ Add signed metadata statements to the request :param req: The request so far :param federation: If only signed metadata statements from a specific set of federations should be included this is the set. :param loes: - not used - :param context: What kind of request/response it is: 'registration', 'discovery' or 'response'. The later being registration response. :param url: Just for testing !! :return: A possibly augmented request. """ # fetch the signed metadata statement collection if federation: if not isinstance(federation, list): federation = [federation] if not url: url = "{}/getms/{}/{}".format(self.mds_service, context, quote_plus(self.entity_id)) http_resp = self.httpcli(method='GET', url=url, verify=self.verify_ssl) if http_resp.status_code >= 400: raise ConnectionError('HTTP Error: {}'.format(http_resp.text)) # verify signature on response msg = JsonWebToken().from_jwt(http_resp.text, keyjar=self.jwks_bundle[self.mds_owner]) if msg['iss'] != self.mds_owner: raise KeyError('Wrong iss') if federation: _ms = dict( [(fo, _ms) for fo, _ms in msg.items() if fo in federation]) else: _ms = msg.extra() try: del _ms['kid'] except KeyError: pass _sms = {} _smsu = {} for fo, item in _ms.items(): if item.startswith('https://') or item.startswith('http://'): _smsu[fo] = item else: _sms[fo] = item if _sms: req.update({'metadata_statements': _sms}) if _smsu: req.update({'metadata_statement_uris': _smsu}) return req
[ "Add", "signed", "metadata", "statements", "to", "the", "request" ]
IdentityPython/fedoidcmsg
python
https://github.com/IdentityPython/fedoidcmsg/blob/d30107be02521fa6cdfe285da3b6b0cdd153c8cc/src/fedoidcmsg/entity.py#L367-L426
[ "def", "add_sms_spec_to_request", "(", "self", ",", "req", ",", "federation", "=", "''", ",", "loes", "=", "None", ",", "context", "=", "''", ",", "url", "=", "''", ")", ":", "# fetch the signed metadata statement collection", "if", "federation", ":", "if", "not", "isinstance", "(", "federation", ",", "list", ")", ":", "federation", "=", "[", "federation", "]", "if", "not", "url", ":", "url", "=", "\"{}/getms/{}/{}\"", ".", "format", "(", "self", ".", "mds_service", ",", "context", ",", "quote_plus", "(", "self", ".", "entity_id", ")", ")", "http_resp", "=", "self", ".", "httpcli", "(", "method", "=", "'GET'", ",", "url", "=", "url", ",", "verify", "=", "self", ".", "verify_ssl", ")", "if", "http_resp", ".", "status_code", ">=", "400", ":", "raise", "ConnectionError", "(", "'HTTP Error: {}'", ".", "format", "(", "http_resp", ".", "text", ")", ")", "# verify signature on response", "msg", "=", "JsonWebToken", "(", ")", ".", "from_jwt", "(", "http_resp", ".", "text", ",", "keyjar", "=", "self", ".", "jwks_bundle", "[", "self", ".", "mds_owner", "]", ")", "if", "msg", "[", "'iss'", "]", "!=", "self", ".", "mds_owner", ":", "raise", "KeyError", "(", "'Wrong iss'", ")", "if", "federation", ":", "_ms", "=", "dict", "(", "[", "(", "fo", ",", "_ms", ")", "for", "fo", ",", "_ms", "in", "msg", ".", "items", "(", ")", "if", "fo", "in", "federation", "]", ")", "else", ":", "_ms", "=", "msg", ".", "extra", "(", ")", "try", ":", "del", "_ms", "[", "'kid'", "]", "except", "KeyError", ":", "pass", "_sms", "=", "{", "}", "_smsu", "=", "{", "}", "for", "fo", ",", "item", "in", "_ms", ".", "items", "(", ")", ":", "if", "item", ".", "startswith", "(", "'https://'", ")", "or", "item", ".", "startswith", "(", "'http://'", ")", ":", "_smsu", "[", "fo", "]", "=", "item", "else", ":", "_sms", "[", "fo", "]", "=", "item", "if", "_sms", ":", "req", ".", "update", "(", "{", "'metadata_statements'", ":", "_sms", "}", ")", "if", "_smsu", ":", "req", ".", "update", "(", "{", "'metadata_statement_uris'", ":", "_smsu", "}", ")", "return", "req" ]
d30107be02521fa6cdfe285da3b6b0cdd153c8cc
test
FederationEntitySwamid.add_sms_spec_to_request
Add signed metadata statements to the request :param req: The request so far :param federation: If only signed metadata statements from a specific set of federations should be included this is the set. :param loes: - not used - :param context: What kind of request/response it is: 'registration', 'discovery' or 'response'. The later being registration response. :param url: Just for testing !! :return: A possibly augmented request.
src/fedoidcmsg/entity.py
def add_sms_spec_to_request(self, req, federation='', loes=None, context='', url=''): """ Add signed metadata statements to the request :param req: The request so far :param federation: If only signed metadata statements from a specific set of federations should be included this is the set. :param loes: - not used - :param context: What kind of request/response it is: 'registration', 'discovery' or 'response'. The later being registration response. :param url: Just for testing !! :return: A possibly augmented request. """ # fetch the signed metadata statement collection if federation: if not isinstance(federation, list): federation = [federation] if not url: url = "{}/getsmscol/{}/{}".format(self.mdss_endpoint, context, quote_plus(self.entity_id)) http_resp = self.httpcli(method='GET', url=url, verify=self.verify_ssl) if http_resp.status_code >= 400: raise ConnectionError('HTTP Error: {}'.format(http_resp.text)) msg = JsonWebToken().from_jwt(http_resp.text, keyjar=self.mdss_keys) if msg['iss'] != self.mdss_owner: raise KeyError('Wrong iss') if federation: _sms = dict( [(fo, _ms) for fo, _ms in msg.items() if fo in federation]) else: _sms = msg.extra() try: del _sms['kid'] except KeyError: pass req.update({'metadata_statement_uris': _sms}) return req
def add_sms_spec_to_request(self, req, federation='', loes=None, context='', url=''): """ Add signed metadata statements to the request :param req: The request so far :param federation: If only signed metadata statements from a specific set of federations should be included this is the set. :param loes: - not used - :param context: What kind of request/response it is: 'registration', 'discovery' or 'response'. The later being registration response. :param url: Just for testing !! :return: A possibly augmented request. """ # fetch the signed metadata statement collection if federation: if not isinstance(federation, list): federation = [federation] if not url: url = "{}/getsmscol/{}/{}".format(self.mdss_endpoint, context, quote_plus(self.entity_id)) http_resp = self.httpcli(method='GET', url=url, verify=self.verify_ssl) if http_resp.status_code >= 400: raise ConnectionError('HTTP Error: {}'.format(http_resp.text)) msg = JsonWebToken().from_jwt(http_resp.text, keyjar=self.mdss_keys) if msg['iss'] != self.mdss_owner: raise KeyError('Wrong iss') if federation: _sms = dict( [(fo, _ms) for fo, _ms in msg.items() if fo in federation]) else: _sms = msg.extra() try: del _sms['kid'] except KeyError: pass req.update({'metadata_statement_uris': _sms}) return req
[ "Add", "signed", "metadata", "statements", "to", "the", "request" ]
IdentityPython/fedoidcmsg
python
https://github.com/IdentityPython/fedoidcmsg/blob/d30107be02521fa6cdfe285da3b6b0cdd153c8cc/src/fedoidcmsg/entity.py#L457-L502
[ "def", "add_sms_spec_to_request", "(", "self", ",", "req", ",", "federation", "=", "''", ",", "loes", "=", "None", ",", "context", "=", "''", ",", "url", "=", "''", ")", ":", "# fetch the signed metadata statement collection", "if", "federation", ":", "if", "not", "isinstance", "(", "federation", ",", "list", ")", ":", "federation", "=", "[", "federation", "]", "if", "not", "url", ":", "url", "=", "\"{}/getsmscol/{}/{}\"", ".", "format", "(", "self", ".", "mdss_endpoint", ",", "context", ",", "quote_plus", "(", "self", ".", "entity_id", ")", ")", "http_resp", "=", "self", ".", "httpcli", "(", "method", "=", "'GET'", ",", "url", "=", "url", ",", "verify", "=", "self", ".", "verify_ssl", ")", "if", "http_resp", ".", "status_code", ">=", "400", ":", "raise", "ConnectionError", "(", "'HTTP Error: {}'", ".", "format", "(", "http_resp", ".", "text", ")", ")", "msg", "=", "JsonWebToken", "(", ")", ".", "from_jwt", "(", "http_resp", ".", "text", ",", "keyjar", "=", "self", ".", "mdss_keys", ")", "if", "msg", "[", "'iss'", "]", "!=", "self", ".", "mdss_owner", ":", "raise", "KeyError", "(", "'Wrong iss'", ")", "if", "federation", ":", "_sms", "=", "dict", "(", "[", "(", "fo", ",", "_ms", ")", "for", "fo", ",", "_ms", "in", "msg", ".", "items", "(", ")", "if", "fo", "in", "federation", "]", ")", "else", ":", "_sms", "=", "msg", ".", "extra", "(", ")", "try", ":", "del", "_sms", "[", "'kid'", "]", "except", "KeyError", ":", "pass", "req", ".", "update", "(", "{", "'metadata_statement_uris'", ":", "_sms", "}", ")", "return", "req" ]
d30107be02521fa6cdfe285da3b6b0cdd153c8cc
test
pretty_print
Prints the anagram results sorted by score to stdout. Args: input_word: the base word we searched on anagrams: generator of (word, score) from anagrams_in_word by_length: a boolean to declare printing by length instead of score
nagaram/cmdline.py
def pretty_print(input_word, anagrams, by_length=False): """Prints the anagram results sorted by score to stdout. Args: input_word: the base word we searched on anagrams: generator of (word, score) from anagrams_in_word by_length: a boolean to declare printing by length instead of score """ scores = {} if by_length: noun = "tiles" for word, score in anagrams: try: scores[len(word)].append("{0} ({1:d})".format(word, score)) except KeyError: scores[len(word)] = ["{0} ({1:d})".format(word, score)] else: noun = "points" for word, score in anagrams: try: scores[score].append(word) except KeyError: scores[score] = [word] print("Anagrams for {0}{1}:".format(input_word, " (score)" * by_length)) if not valid_scrabble_word(input_word): print("{0} is not possible in Scrabble.".format(input_word)) for key, value in sorted(scores.items(), reverse=True): print("{0:d} {1}: {2}".format(key, noun, ", ".join(value)))
def pretty_print(input_word, anagrams, by_length=False): """Prints the anagram results sorted by score to stdout. Args: input_word: the base word we searched on anagrams: generator of (word, score) from anagrams_in_word by_length: a boolean to declare printing by length instead of score """ scores = {} if by_length: noun = "tiles" for word, score in anagrams: try: scores[len(word)].append("{0} ({1:d})".format(word, score)) except KeyError: scores[len(word)] = ["{0} ({1:d})".format(word, score)] else: noun = "points" for word, score in anagrams: try: scores[score].append(word) except KeyError: scores[score] = [word] print("Anagrams for {0}{1}:".format(input_word, " (score)" * by_length)) if not valid_scrabble_word(input_word): print("{0} is not possible in Scrabble.".format(input_word)) for key, value in sorted(scores.items(), reverse=True): print("{0:d} {1}: {2}".format(key, noun, ", ".join(value)))
[ "Prints", "the", "anagram", "results", "sorted", "by", "score", "to", "stdout", "." ]
a-tal/nagaram
python
https://github.com/a-tal/nagaram/blob/2edcb0ef8cb569ebd1c398be826472b4831d6110/nagaram/cmdline.py#L14-L45
[ "def", "pretty_print", "(", "input_word", ",", "anagrams", ",", "by_length", "=", "False", ")", ":", "scores", "=", "{", "}", "if", "by_length", ":", "noun", "=", "\"tiles\"", "for", "word", ",", "score", "in", "anagrams", ":", "try", ":", "scores", "[", "len", "(", "word", ")", "]", ".", "append", "(", "\"{0} ({1:d})\"", ".", "format", "(", "word", ",", "score", ")", ")", "except", "KeyError", ":", "scores", "[", "len", "(", "word", ")", "]", "=", "[", "\"{0} ({1:d})\"", ".", "format", "(", "word", ",", "score", ")", "]", "else", ":", "noun", "=", "\"points\"", "for", "word", ",", "score", "in", "anagrams", ":", "try", ":", "scores", "[", "score", "]", ".", "append", "(", "word", ")", "except", "KeyError", ":", "scores", "[", "score", "]", "=", "[", "word", "]", "print", "(", "\"Anagrams for {0}{1}:\"", ".", "format", "(", "input_word", ",", "\" (score)\"", "*", "by_length", ")", ")", "if", "not", "valid_scrabble_word", "(", "input_word", ")", ":", "print", "(", "\"{0} is not possible in Scrabble.\"", ".", "format", "(", "input_word", ")", ")", "for", "key", ",", "value", "in", "sorted", "(", "scores", ".", "items", "(", ")", ",", "reverse", "=", "True", ")", ":", "print", "(", "\"{0:d} {1}: {2}\"", ".", "format", "(", "key", ",", "noun", ",", "\", \"", ".", "join", "(", "value", ")", ")", ")" ]
2edcb0ef8cb569ebd1c398be826472b4831d6110
test
argument_parser
Argparse logic, command line options. Args: args: sys.argv[1:], everything passed to the program after its name Returns: A tuple of: a list of words/letters to search a boolean to declare if we want to use the sowpods words file a boolean to declare if we want to output anagrams by length a string of starting characters to find anagrams based on a string of ending characters to find anagrams based on Raises: SystemExit if the user passes invalid arguments, --version or --help
nagaram/cmdline.py
def argument_parser(args): """Argparse logic, command line options. Args: args: sys.argv[1:], everything passed to the program after its name Returns: A tuple of: a list of words/letters to search a boolean to declare if we want to use the sowpods words file a boolean to declare if we want to output anagrams by length a string of starting characters to find anagrams based on a string of ending characters to find anagrams based on Raises: SystemExit if the user passes invalid arguments, --version or --help """ parser = argparse.ArgumentParser( prog="nagaram", description="Finds Scabble anagrams.", formatter_class=argparse.RawDescriptionHelpFormatter, add_help=False, ) parser.add_argument( "-h", "--help", dest="help", action="store_true", default=False, ) parser.add_argument( "--sowpods", dest="sowpods", action="store_true", default=False, ) parser.add_argument( "--length", "-l", dest="length", action="store_true", default=False, ) parser.add_argument( "--starts-with", "-s", dest="starts_with", metavar="chars", default="", nargs=1, type=str, ) parser.add_argument( "--ends-with", "-e", dest="ends_with", metavar="chars", default="", nargs=1, type=str, ) parser.add_argument( "--version", "-v", action="version", version="Nagaram {0} (Released: {1})".format( nagaram.__version__, nagaram.__release_date__, ) ) parser.add_argument( dest="wordlist", metavar="letters to find anagrams with (? for anything, _ for blanks)", nargs=argparse.REMAINDER, ) settings = parser.parse_args(args) if settings.help: raise SystemExit(nagaram.__doc__.strip()) if not settings.wordlist: raise SystemExit(parser.print_usage()) if settings.starts_with: settings.starts_with = settings.starts_with[0] if settings.ends_with: settings.ends_with = settings.ends_with[0] return (settings.wordlist, settings.sowpods, settings.length, settings.starts_with, settings.ends_with)
def argument_parser(args): """Argparse logic, command line options. Args: args: sys.argv[1:], everything passed to the program after its name Returns: A tuple of: a list of words/letters to search a boolean to declare if we want to use the sowpods words file a boolean to declare if we want to output anagrams by length a string of starting characters to find anagrams based on a string of ending characters to find anagrams based on Raises: SystemExit if the user passes invalid arguments, --version or --help """ parser = argparse.ArgumentParser( prog="nagaram", description="Finds Scabble anagrams.", formatter_class=argparse.RawDescriptionHelpFormatter, add_help=False, ) parser.add_argument( "-h", "--help", dest="help", action="store_true", default=False, ) parser.add_argument( "--sowpods", dest="sowpods", action="store_true", default=False, ) parser.add_argument( "--length", "-l", dest="length", action="store_true", default=False, ) parser.add_argument( "--starts-with", "-s", dest="starts_with", metavar="chars", default="", nargs=1, type=str, ) parser.add_argument( "--ends-with", "-e", dest="ends_with", metavar="chars", default="", nargs=1, type=str, ) parser.add_argument( "--version", "-v", action="version", version="Nagaram {0} (Released: {1})".format( nagaram.__version__, nagaram.__release_date__, ) ) parser.add_argument( dest="wordlist", metavar="letters to find anagrams with (? for anything, _ for blanks)", nargs=argparse.REMAINDER, ) settings = parser.parse_args(args) if settings.help: raise SystemExit(nagaram.__doc__.strip()) if not settings.wordlist: raise SystemExit(parser.print_usage()) if settings.starts_with: settings.starts_with = settings.starts_with[0] if settings.ends_with: settings.ends_with = settings.ends_with[0] return (settings.wordlist, settings.sowpods, settings.length, settings.starts_with, settings.ends_with)
[ "Argparse", "logic", "command", "line", "options", "." ]
a-tal/nagaram
python
https://github.com/a-tal/nagaram/blob/2edcb0ef8cb569ebd1c398be826472b4831d6110/nagaram/cmdline.py#L48-L145
[ "def", "argument_parser", "(", "args", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "prog", "=", "\"nagaram\"", ",", "description", "=", "\"Finds Scabble anagrams.\"", ",", "formatter_class", "=", "argparse", ".", "RawDescriptionHelpFormatter", ",", "add_help", "=", "False", ",", ")", "parser", ".", "add_argument", "(", "\"-h\"", ",", "\"--help\"", ",", "dest", "=", "\"help\"", ",", "action", "=", "\"store_true\"", ",", "default", "=", "False", ",", ")", "parser", ".", "add_argument", "(", "\"--sowpods\"", ",", "dest", "=", "\"sowpods\"", ",", "action", "=", "\"store_true\"", ",", "default", "=", "False", ",", ")", "parser", ".", "add_argument", "(", "\"--length\"", ",", "\"-l\"", ",", "dest", "=", "\"length\"", ",", "action", "=", "\"store_true\"", ",", "default", "=", "False", ",", ")", "parser", ".", "add_argument", "(", "\"--starts-with\"", ",", "\"-s\"", ",", "dest", "=", "\"starts_with\"", ",", "metavar", "=", "\"chars\"", ",", "default", "=", "\"\"", ",", "nargs", "=", "1", ",", "type", "=", "str", ",", ")", "parser", ".", "add_argument", "(", "\"--ends-with\"", ",", "\"-e\"", ",", "dest", "=", "\"ends_with\"", ",", "metavar", "=", "\"chars\"", ",", "default", "=", "\"\"", ",", "nargs", "=", "1", ",", "type", "=", "str", ",", ")", "parser", ".", "add_argument", "(", "\"--version\"", ",", "\"-v\"", ",", "action", "=", "\"version\"", ",", "version", "=", "\"Nagaram {0} (Released: {1})\"", ".", "format", "(", "nagaram", ".", "__version__", ",", "nagaram", ".", "__release_date__", ",", ")", ")", "parser", ".", "add_argument", "(", "dest", "=", "\"wordlist\"", ",", "metavar", "=", "\"letters to find anagrams with (? for anything, _ for blanks)\"", ",", "nargs", "=", "argparse", ".", "REMAINDER", ",", ")", "settings", "=", "parser", ".", "parse_args", "(", "args", ")", "if", "settings", ".", "help", ":", "raise", "SystemExit", "(", "nagaram", ".", "__doc__", ".", "strip", "(", ")", ")", "if", "not", "settings", ".", "wordlist", ":", "raise", "SystemExit", "(", "parser", ".", "print_usage", "(", ")", ")", "if", "settings", ".", "starts_with", ":", "settings", ".", "starts_with", "=", "settings", ".", "starts_with", "[", "0", "]", "if", "settings", ".", "ends_with", ":", "settings", ".", "ends_with", "=", "settings", ".", "ends_with", "[", "0", "]", "return", "(", "settings", ".", "wordlist", ",", "settings", ".", "sowpods", ",", "settings", ".", "length", ",", "settings", ".", "starts_with", ",", "settings", ".", "ends_with", ")" ]
2edcb0ef8cb569ebd1c398be826472b4831d6110
test
main
Main command line entry point.
nagaram/cmdline.py
def main(arguments=None): """Main command line entry point.""" if not arguments: arguments = sys.argv[1:] wordlist, sowpods, by_length, start, end = argument_parser(arguments) for word in wordlist: pretty_print( word, anagrams_in_word(word, sowpods, start, end), by_length, )
def main(arguments=None): """Main command line entry point.""" if not arguments: arguments = sys.argv[1:] wordlist, sowpods, by_length, start, end = argument_parser(arguments) for word in wordlist: pretty_print( word, anagrams_in_word(word, sowpods, start, end), by_length, )
[ "Main", "command", "line", "entry", "point", "." ]
a-tal/nagaram
python
https://github.com/a-tal/nagaram/blob/2edcb0ef8cb569ebd1c398be826472b4831d6110/nagaram/cmdline.py#L148-L160
[ "def", "main", "(", "arguments", "=", "None", ")", ":", "if", "not", "arguments", ":", "arguments", "=", "sys", ".", "argv", "[", "1", ":", "]", "wordlist", ",", "sowpods", ",", "by_length", ",", "start", ",", "end", "=", "argument_parser", "(", "arguments", ")", "for", "word", "in", "wordlist", ":", "pretty_print", "(", "word", ",", "anagrams_in_word", "(", "word", ",", "sowpods", ",", "start", ",", "end", ")", ",", "by_length", ",", ")" ]
2edcb0ef8cb569ebd1c398be826472b4831d6110
test
PacketProtocol.register_type
Registers a type name so that it may be used to send and receive packages. :param typename: Name of the packet type. A method with the same name and a "on_" prefix should be added to handle incomming packets. :raises ValueError: If there is a hash code collision.
anycall/packetprotocol.py
def register_type(self, typename): """ Registers a type name so that it may be used to send and receive packages. :param typename: Name of the packet type. A method with the same name and a "on_" prefix should be added to handle incomming packets. :raises ValueError: If there is a hash code collision. """ typekey = typehash(typename) if typekey in self._type_register: raise ValueError("Type name collision. Type %s has the same hash." % repr(self._type_register[typekey])) self._type_register[typekey] = typename
def register_type(self, typename): """ Registers a type name so that it may be used to send and receive packages. :param typename: Name of the packet type. A method with the same name and a "on_" prefix should be added to handle incomming packets. :raises ValueError: If there is a hash code collision. """ typekey = typehash(typename) if typekey in self._type_register: raise ValueError("Type name collision. Type %s has the same hash." % repr(self._type_register[typekey])) self._type_register[typekey] = typename
[ "Registers", "a", "type", "name", "so", "that", "it", "may", "be", "used", "to", "send", "and", "receive", "packages", ".", ":", "param", "typename", ":", "Name", "of", "the", "packet", "type", ".", "A", "method", "with", "the", "same", "name", "and", "a", "on_", "prefix", "should", "be", "added", "to", "handle", "incomming", "packets", ".", ":", "raises", "ValueError", ":", "If", "there", "is", "a", "hash", "code", "collision", "." ]
pydron/anycall
python
https://github.com/pydron/anycall/blob/43add96660258a14b24aa8e8413dffb1741b72d7/anycall/packetprotocol.py#L53-L65
[ "def", "register_type", "(", "self", ",", "typename", ")", ":", "typekey", "=", "typehash", "(", "typename", ")", "if", "typekey", "in", "self", ".", "_type_register", ":", "raise", "ValueError", "(", "\"Type name collision. Type %s has the same hash.\"", "%", "repr", "(", "self", ".", "_type_register", "[", "typekey", "]", ")", ")", "self", ".", "_type_register", "[", "typekey", "]", "=", "typename" ]
43add96660258a14b24aa8e8413dffb1741b72d7
test
PacketProtocol.dataReceived
Do not overwrite this method. Instead implement `on_...` methods for the registered typenames to handle incomming packets.
anycall/packetprotocol.py
def dataReceived(self, data): """ Do not overwrite this method. Instead implement `on_...` methods for the registered typenames to handle incomming packets. """ self._unprocessed_data.enqueue(data) while True: if len(self._unprocessed_data) < self._header.size: return # not yet enough data hdr_data = self._unprocessed_data.peek(self._header.size) packet_length, typekey = self._header.unpack(hdr_data) total_length = self._header.size + packet_length if len(self._unprocessed_data) < total_length: return # not yet enough data self._unprocessed_data.drop(self._header.size) packet = self._unprocessed_data.dequeue(packet_length) self._start_receive = None typename = self._type_register.get(typekey, None) if typename is None: self.on_unregistered_type(typekey, packet) else: self.packet_received(typename, packet)
def dataReceived(self, data): """ Do not overwrite this method. Instead implement `on_...` methods for the registered typenames to handle incomming packets. """ self._unprocessed_data.enqueue(data) while True: if len(self._unprocessed_data) < self._header.size: return # not yet enough data hdr_data = self._unprocessed_data.peek(self._header.size) packet_length, typekey = self._header.unpack(hdr_data) total_length = self._header.size + packet_length if len(self._unprocessed_data) < total_length: return # not yet enough data self._unprocessed_data.drop(self._header.size) packet = self._unprocessed_data.dequeue(packet_length) self._start_receive = None typename = self._type_register.get(typekey, None) if typename is None: self.on_unregistered_type(typekey, packet) else: self.packet_received(typename, packet)
[ "Do", "not", "overwrite", "this", "method", ".", "Instead", "implement", "on_", "...", "methods", "for", "the", "registered", "typenames", "to", "handle", "incomming", "packets", "." ]
pydron/anycall
python
https://github.com/pydron/anycall/blob/43add96660258a14b24aa8e8413dffb1741b72d7/anycall/packetprotocol.py#L73-L102
[ "def", "dataReceived", "(", "self", ",", "data", ")", ":", "self", ".", "_unprocessed_data", ".", "enqueue", "(", "data", ")", "while", "True", ":", "if", "len", "(", "self", ".", "_unprocessed_data", ")", "<", "self", ".", "_header", ".", "size", ":", "return", "# not yet enough data", "hdr_data", "=", "self", ".", "_unprocessed_data", ".", "peek", "(", "self", ".", "_header", ".", "size", ")", "packet_length", ",", "typekey", "=", "self", ".", "_header", ".", "unpack", "(", "hdr_data", ")", "total_length", "=", "self", ".", "_header", ".", "size", "+", "packet_length", "if", "len", "(", "self", ".", "_unprocessed_data", ")", "<", "total_length", ":", "return", "# not yet enough data", "self", ".", "_unprocessed_data", ".", "drop", "(", "self", ".", "_header", ".", "size", ")", "packet", "=", "self", ".", "_unprocessed_data", ".", "dequeue", "(", "packet_length", ")", "self", ".", "_start_receive", "=", "None", "typename", "=", "self", ".", "_type_register", ".", "get", "(", "typekey", ",", "None", ")", "if", "typename", "is", "None", ":", "self", ".", "on_unregistered_type", "(", "typekey", ",", "packet", ")", "else", ":", "self", ".", "packet_received", "(", "typename", ",", "packet", ")" ]
43add96660258a14b24aa8e8413dffb1741b72d7
test
PacketProtocol.send_packet
Send a packet. :param typename: A previously registered typename. :param packet: String with the content of the packet.
anycall/packetprotocol.py
def send_packet(self, typename, packet): """ Send a packet. :param typename: A previously registered typename. :param packet: String with the content of the packet. """ typekey = typehash(typename) if typename != self._type_register.get(typekey, None): raise ValueError("Cannot send packet with unregistered type %s." % repr(typename)) hdr = self._header.pack(len(packet), typekey) self.transport.writeSequence([hdr, packet])
def send_packet(self, typename, packet): """ Send a packet. :param typename: A previously registered typename. :param packet: String with the content of the packet. """ typekey = typehash(typename) if typename != self._type_register.get(typekey, None): raise ValueError("Cannot send packet with unregistered type %s." % repr(typename)) hdr = self._header.pack(len(packet), typekey) self.transport.writeSequence([hdr, packet])
[ "Send", "a", "packet", ".", ":", "param", "typename", ":", "A", "previously", "registered", "typename", ".", ":", "param", "packet", ":", "String", "with", "the", "content", "of", "the", "packet", "." ]
pydron/anycall
python
https://github.com/pydron/anycall/blob/43add96660258a14b24aa8e8413dffb1741b72d7/anycall/packetprotocol.py#L105-L118
[ "def", "send_packet", "(", "self", ",", "typename", ",", "packet", ")", ":", "typekey", "=", "typehash", "(", "typename", ")", "if", "typename", "!=", "self", ".", "_type_register", ".", "get", "(", "typekey", ",", "None", ")", ":", "raise", "ValueError", "(", "\"Cannot send packet with unregistered type %s.\"", "%", "repr", "(", "typename", ")", ")", "hdr", "=", "self", ".", "_header", ".", "pack", "(", "len", "(", "packet", ")", ",", "typekey", ")", "self", ".", "transport", ".", "writeSequence", "(", "[", "hdr", ",", "packet", "]", ")" ]
43add96660258a14b24aa8e8413dffb1741b72d7
test
PacketProtocol.on_unregistered_type
Invoked if a packet with an unregistered type was received. Default behaviour is to log and close the connection.
anycall/packetprotocol.py
def on_unregistered_type(self, typekey, packet): """ Invoked if a packet with an unregistered type was received. Default behaviour is to log and close the connection. """ log.msg("Missing handler for typekey %s in %s. Closing connection." % (typekey, type(self).__name__)) self.transport.loseConnection()
def on_unregistered_type(self, typekey, packet): """ Invoked if a packet with an unregistered type was received. Default behaviour is to log and close the connection. """ log.msg("Missing handler for typekey %s in %s. Closing connection." % (typekey, type(self).__name__)) self.transport.loseConnection()
[ "Invoked", "if", "a", "packet", "with", "an", "unregistered", "type", "was", "received", ".", "Default", "behaviour", "is", "to", "log", "and", "close", "the", "connection", "." ]
pydron/anycall
python
https://github.com/pydron/anycall/blob/43add96660258a14b24aa8e8413dffb1741b72d7/anycall/packetprotocol.py#L124-L131
[ "def", "on_unregistered_type", "(", "self", ",", "typekey", ",", "packet", ")", ":", "log", ".", "msg", "(", "\"Missing handler for typekey %s in %s. Closing connection.\"", "%", "(", "typekey", ",", "type", "(", "self", ")", ".", "__name__", ")", ")", "self", ".", "transport", ".", "loseConnection", "(", ")" ]
43add96660258a14b24aa8e8413dffb1741b72d7
test
create_tcp_rpc_system
Creates a TCP based :class:`RPCSystem`. :param port_range: List of ports to try. If `[0]`, an arbitrary free port will be used.
anycall/rpc.py
def create_tcp_rpc_system(hostname=None, port_range=(0,), ping_interval=1, ping_timeout=0.5): """ Creates a TCP based :class:`RPCSystem`. :param port_range: List of ports to try. If `[0]`, an arbitrary free port will be used. """ def ownid_factory(listeningport): port = listeningport.getHost().port return "%s:%s" %(hostname, port) def make_client_endpoint(peer): host, port = peer.split(":") if host == socket.getfqdn(): host = "localhost" return endpoints.TCP4ClientEndpoint(reactor, host, int(port), timeout=5) if hostname is None: hostname = socket.getfqdn() server_endpointA = TCP4ServerRangeEndpoint(reactor, port_range) pool = connectionpool.ConnectionPool(server_endpointA, make_client_endpoint, ownid_factory) return RPCSystem(pool, ping_interval=ping_interval, ping_timeout=ping_timeout)
def create_tcp_rpc_system(hostname=None, port_range=(0,), ping_interval=1, ping_timeout=0.5): """ Creates a TCP based :class:`RPCSystem`. :param port_range: List of ports to try. If `[0]`, an arbitrary free port will be used. """ def ownid_factory(listeningport): port = listeningport.getHost().port return "%s:%s" %(hostname, port) def make_client_endpoint(peer): host, port = peer.split(":") if host == socket.getfqdn(): host = "localhost" return endpoints.TCP4ClientEndpoint(reactor, host, int(port), timeout=5) if hostname is None: hostname = socket.getfqdn() server_endpointA = TCP4ServerRangeEndpoint(reactor, port_range) pool = connectionpool.ConnectionPool(server_endpointA, make_client_endpoint, ownid_factory) return RPCSystem(pool, ping_interval=ping_interval, ping_timeout=ping_timeout)
[ "Creates", "a", "TCP", "based", ":", "class", ":", "RPCSystem", ".", ":", "param", "port_range", ":", "List", "of", "ports", "to", "try", ".", "If", "[", "0", "]", "an", "arbitrary", "free", "port", "will", "be", "used", "." ]
pydron/anycall
python
https://github.com/pydron/anycall/blob/43add96660258a14b24aa8e8413dffb1741b72d7/anycall/rpc.py#L40-L63
[ "def", "create_tcp_rpc_system", "(", "hostname", "=", "None", ",", "port_range", "=", "(", "0", ",", ")", ",", "ping_interval", "=", "1", ",", "ping_timeout", "=", "0.5", ")", ":", "def", "ownid_factory", "(", "listeningport", ")", ":", "port", "=", "listeningport", ".", "getHost", "(", ")", ".", "port", "return", "\"%s:%s\"", "%", "(", "hostname", ",", "port", ")", "def", "make_client_endpoint", "(", "peer", ")", ":", "host", ",", "port", "=", "peer", ".", "split", "(", "\":\"", ")", "if", "host", "==", "socket", ".", "getfqdn", "(", ")", ":", "host", "=", "\"localhost\"", "return", "endpoints", ".", "TCP4ClientEndpoint", "(", "reactor", ",", "host", ",", "int", "(", "port", ")", ",", "timeout", "=", "5", ")", "if", "hostname", "is", "None", ":", "hostname", "=", "socket", ".", "getfqdn", "(", ")", "server_endpointA", "=", "TCP4ServerRangeEndpoint", "(", "reactor", ",", "port_range", ")", "pool", "=", "connectionpool", ".", "ConnectionPool", "(", "server_endpointA", ",", "make_client_endpoint", ",", "ownid_factory", ")", "return", "RPCSystem", "(", "pool", ",", "ping_interval", "=", "ping_interval", ",", "ping_timeout", "=", "ping_timeout", ")" ]
43add96660258a14b24aa8e8413dffb1741b72d7
test
RPCSystem.open
Opens the port. :returns: Deferred that callbacks when we are ready to make and receive calls.
anycall/rpc.py
def open(self): """ Opens the port. :returns: Deferred that callbacks when we are ready to make and receive calls. """ logging.debug("Opening rpc system") d = self._connectionpool.open(self._packet_received) def opened(_): logging.debug("RPC system is open") self._opened = True logging.debug("Starting ping loop") self._ping_loop.start(self._ping_interval, now=False) d.addCallback(opened) return d
def open(self): """ Opens the port. :returns: Deferred that callbacks when we are ready to make and receive calls. """ logging.debug("Opening rpc system") d = self._connectionpool.open(self._packet_received) def opened(_): logging.debug("RPC system is open") self._opened = True logging.debug("Starting ping loop") self._ping_loop.start(self._ping_interval, now=False) d.addCallback(opened) return d
[ "Opens", "the", "port", ".", ":", "returns", ":", "Deferred", "that", "callbacks", "when", "we", "are", "ready", "to", "make", "and", "receive", "calls", "." ]
pydron/anycall
python
https://github.com/pydron/anycall/blob/43add96660258a14b24aa8e8413dffb1741b72d7/anycall/rpc.py#L178-L194
[ "def", "open", "(", "self", ")", ":", "logging", ".", "debug", "(", "\"Opening rpc system\"", ")", "d", "=", "self", ".", "_connectionpool", ".", "open", "(", "self", ".", "_packet_received", ")", "def", "opened", "(", "_", ")", ":", "logging", ".", "debug", "(", "\"RPC system is open\"", ")", "self", ".", "_opened", "=", "True", "logging", ".", "debug", "(", "\"Starting ping loop\"", ")", "self", ".", "_ping_loop", ".", "start", "(", "self", ".", "_ping_interval", ",", "now", "=", "False", ")", "d", ".", "addCallback", "(", "opened", ")", "return", "d" ]
43add96660258a14b24aa8e8413dffb1741b72d7
test
RPCSystem.close
Stop listing for new connections and close all open connections. :returns: Deferred that calls back once everything is closed.
anycall/rpc.py
def close(self): """ Stop listing for new connections and close all open connections. :returns: Deferred that calls back once everything is closed. """ assert self._opened, "RPC System is not opened" logger.debug("Closing rpc system. Stopping ping loop") self._ping_loop.stop() if self._ping_current_iteration: self._ping_current_iteration.cancel() return self._connectionpool.close()
def close(self): """ Stop listing for new connections and close all open connections. :returns: Deferred that calls back once everything is closed. """ assert self._opened, "RPC System is not opened" logger.debug("Closing rpc system. Stopping ping loop") self._ping_loop.stop() if self._ping_current_iteration: self._ping_current_iteration.cancel() return self._connectionpool.close()
[ "Stop", "listing", "for", "new", "connections", "and", "close", "all", "open", "connections", ".", ":", "returns", ":", "Deferred", "that", "calls", "back", "once", "everything", "is", "closed", "." ]
pydron/anycall
python
https://github.com/pydron/anycall/blob/43add96660258a14b24aa8e8413dffb1741b72d7/anycall/rpc.py#L196-L207
[ "def", "close", "(", "self", ")", ":", "assert", "self", ".", "_opened", ",", "\"RPC System is not opened\"", "logger", ".", "debug", "(", "\"Closing rpc system. Stopping ping loop\"", ")", "self", ".", "_ping_loop", ".", "stop", "(", ")", "if", "self", ".", "_ping_current_iteration", ":", "self", ".", "_ping_current_iteration", ".", "cancel", "(", ")", "return", "self", ".", "_connectionpool", ".", "close", "(", ")" ]
43add96660258a14b24aa8e8413dffb1741b72d7
test
RPCSystem.get_function_url
Registers the given callable in the system (if it isn't already) and returns the URL that can be used to invoke the given function from remote.
anycall/rpc.py
def get_function_url(self, function): """ Registers the given callable in the system (if it isn't already) and returns the URL that can be used to invoke the given function from remote. """ assert self._opened, "RPC System is not opened" logging.debug("get_function_url(%s)" % repr(function)) if function in ~self._functions: functionid = self._functions[:function] else: functionid = uuid.uuid1() self._functions[functionid] = function return "anycall://%s/functions/%s" % (self._connectionpool.ownid, functionid.hex)
def get_function_url(self, function): """ Registers the given callable in the system (if it isn't already) and returns the URL that can be used to invoke the given function from remote. """ assert self._opened, "RPC System is not opened" logging.debug("get_function_url(%s)" % repr(function)) if function in ~self._functions: functionid = self._functions[:function] else: functionid = uuid.uuid1() self._functions[functionid] = function return "anycall://%s/functions/%s" % (self._connectionpool.ownid, functionid.hex)
[ "Registers", "the", "given", "callable", "in", "the", "system", "(", "if", "it", "isn", "t", "already", ")", "and", "returns", "the", "URL", "that", "can", "be", "used", "to", "invoke", "the", "given", "function", "from", "remote", "." ]
pydron/anycall
python
https://github.com/pydron/anycall/blob/43add96660258a14b24aa8e8413dffb1741b72d7/anycall/rpc.py#L209-L221
[ "def", "get_function_url", "(", "self", ",", "function", ")", ":", "assert", "self", ".", "_opened", ",", "\"RPC System is not opened\"", "logging", ".", "debug", "(", "\"get_function_url(%s)\"", "%", "repr", "(", "function", ")", ")", "if", "function", "in", "~", "self", ".", "_functions", ":", "functionid", "=", "self", ".", "_functions", "[", ":", "function", "]", "else", ":", "functionid", "=", "uuid", ".", "uuid1", "(", ")", "self", ".", "_functions", "[", "functionid", "]", "=", "function", "return", "\"anycall://%s/functions/%s\"", "%", "(", "self", ".", "_connectionpool", ".", "ownid", ",", "functionid", ".", "hex", ")" ]
43add96660258a14b24aa8e8413dffb1741b72d7
test
RPCSystem.create_function_stub
Create a callable that will invoke the given remote function. The stub will return a deferred even if the remote function does not.
anycall/rpc.py
def create_function_stub(self, url): """ Create a callable that will invoke the given remote function. The stub will return a deferred even if the remote function does not. """ assert self._opened, "RPC System is not opened" logging.debug("create_function_stub(%s)" % repr(url)) parseresult = urlparse.urlparse(url) scheme = parseresult.scheme path = parseresult.path.split("/") if scheme != "anycall": raise ValueError("Not an anycall URL: %s" % repr(url)) if len(path) != 3 or path[0] != "" or path[1] != "functions": raise ValueError("Not an URL for a remote function: %s" % repr(url)) try: functionid = uuid.UUID(path[2]) except ValueError: raise ValueError("Not a valid URL for a remote function: %s" % repr(url)) return _RPCFunctionStub(parseresult.netloc, functionid, self)
def create_function_stub(self, url): """ Create a callable that will invoke the given remote function. The stub will return a deferred even if the remote function does not. """ assert self._opened, "RPC System is not opened" logging.debug("create_function_stub(%s)" % repr(url)) parseresult = urlparse.urlparse(url) scheme = parseresult.scheme path = parseresult.path.split("/") if scheme != "anycall": raise ValueError("Not an anycall URL: %s" % repr(url)) if len(path) != 3 or path[0] != "" or path[1] != "functions": raise ValueError("Not an URL for a remote function: %s" % repr(url)) try: functionid = uuid.UUID(path[2]) except ValueError: raise ValueError("Not a valid URL for a remote function: %s" % repr(url)) return _RPCFunctionStub(parseresult.netloc, functionid, self)
[ "Create", "a", "callable", "that", "will", "invoke", "the", "given", "remote", "function", ".", "The", "stub", "will", "return", "a", "deferred", "even", "if", "the", "remote", "function", "does", "not", "." ]
pydron/anycall
python
https://github.com/pydron/anycall/blob/43add96660258a14b24aa8e8413dffb1741b72d7/anycall/rpc.py#L224-L244
[ "def", "create_function_stub", "(", "self", ",", "url", ")", ":", "assert", "self", ".", "_opened", ",", "\"RPC System is not opened\"", "logging", ".", "debug", "(", "\"create_function_stub(%s)\"", "%", "repr", "(", "url", ")", ")", "parseresult", "=", "urlparse", ".", "urlparse", "(", "url", ")", "scheme", "=", "parseresult", ".", "scheme", "path", "=", "parseresult", ".", "path", ".", "split", "(", "\"/\"", ")", "if", "scheme", "!=", "\"anycall\"", ":", "raise", "ValueError", "(", "\"Not an anycall URL: %s\"", "%", "repr", "(", "url", ")", ")", "if", "len", "(", "path", ")", "!=", "3", "or", "path", "[", "0", "]", "!=", "\"\"", "or", "path", "[", "1", "]", "!=", "\"functions\"", ":", "raise", "ValueError", "(", "\"Not an URL for a remote function: %s\"", "%", "repr", "(", "url", ")", ")", "try", ":", "functionid", "=", "uuid", ".", "UUID", "(", "path", "[", "2", "]", ")", "except", "ValueError", ":", "raise", "ValueError", "(", "\"Not a valid URL for a remote function: %s\"", "%", "repr", "(", "url", ")", ")", "return", "_RPCFunctionStub", "(", "parseresult", ".", "netloc", ",", "functionid", ",", "self", ")" ]
43add96660258a14b24aa8e8413dffb1741b72d7
test
RPCSystem._ping_loop_iteration
Called every `ping_interval` seconds. Invokes `_ping()` remotely for every ongoing call.
anycall/rpc.py
def _ping_loop_iteration(self): """ Called every `ping_interval` seconds. Invokes `_ping()` remotely for every ongoing call. """ deferredList = [] for peerid, callid in list(self._local_to_remote): if (peerid, callid) not in self._local_to_remote: continue # call finished in the meantime logger.debug("sending ping") d = self._invoke_function(peerid, self._PING, (self._connectionpool.ownid, callid), {}) #twistit.timeout_deferred(d, self._ping_timeout, "Lost communication to peer during call.") def failed(failure): if (peerid, callid) in self._local_to_remote: d = self._local_to_remote.pop((peerid, callid)) d.errback(failure) def success(value): logger.debug("received pong") return value d.addCallbacks(success, failed) deferredList.append(d) d = defer.DeferredList(deferredList) def done(_): self._ping_current_iteration = None self._ping_current_iteration = d d.addBoth(done) return d
def _ping_loop_iteration(self): """ Called every `ping_interval` seconds. Invokes `_ping()` remotely for every ongoing call. """ deferredList = [] for peerid, callid in list(self._local_to_remote): if (peerid, callid) not in self._local_to_remote: continue # call finished in the meantime logger.debug("sending ping") d = self._invoke_function(peerid, self._PING, (self._connectionpool.ownid, callid), {}) #twistit.timeout_deferred(d, self._ping_timeout, "Lost communication to peer during call.") def failed(failure): if (peerid, callid) in self._local_to_remote: d = self._local_to_remote.pop((peerid, callid)) d.errback(failure) def success(value): logger.debug("received pong") return value d.addCallbacks(success, failed) deferredList.append(d) d = defer.DeferredList(deferredList) def done(_): self._ping_current_iteration = None self._ping_current_iteration = d d.addBoth(done) return d
[ "Called", "every", "ping_interval", "seconds", ".", "Invokes", "_ping", "()", "remotely", "for", "every", "ongoing", "call", "." ]
pydron/anycall
python
https://github.com/pydron/anycall/blob/43add96660258a14b24aa8e8413dffb1741b72d7/anycall/rpc.py#L388-L423
[ "def", "_ping_loop_iteration", "(", "self", ")", ":", "deferredList", "=", "[", "]", "for", "peerid", ",", "callid", "in", "list", "(", "self", ".", "_local_to_remote", ")", ":", "if", "(", "peerid", ",", "callid", ")", "not", "in", "self", ".", "_local_to_remote", ":", "continue", "# call finished in the meantime", "logger", ".", "debug", "(", "\"sending ping\"", ")", "d", "=", "self", ".", "_invoke_function", "(", "peerid", ",", "self", ".", "_PING", ",", "(", "self", ".", "_connectionpool", ".", "ownid", ",", "callid", ")", ",", "{", "}", ")", "#twistit.timeout_deferred(d, self._ping_timeout, \"Lost communication to peer during call.\")", "def", "failed", "(", "failure", ")", ":", "if", "(", "peerid", ",", "callid", ")", "in", "self", ".", "_local_to_remote", ":", "d", "=", "self", ".", "_local_to_remote", ".", "pop", "(", "(", "peerid", ",", "callid", ")", ")", "d", ".", "errback", "(", "failure", ")", "def", "success", "(", "value", ")", ":", "logger", ".", "debug", "(", "\"received pong\"", ")", "return", "value", "d", ".", "addCallbacks", "(", "success", ",", "failed", ")", "deferredList", ".", "append", "(", "d", ")", "d", "=", "defer", ".", "DeferredList", "(", "deferredList", ")", "def", "done", "(", "_", ")", ":", "self", ".", "_ping_current_iteration", "=", "None", "self", ".", "_ping_current_iteration", "=", "d", "d", ".", "addBoth", "(", "done", ")", "return", "d" ]
43add96660258a14b24aa8e8413dffb1741b72d7
test
RPCSystem._ping
Called from remote to ask if a call made to here is still in progress.
anycall/rpc.py
def _ping(self, peerid, callid): """ Called from remote to ask if a call made to here is still in progress. """ if not (peerid, callid) in self._remote_to_local: logger.warn("No remote call %s from %s. Might just be unfoutunate timing." % (callid, peerid))
def _ping(self, peerid, callid): """ Called from remote to ask if a call made to here is still in progress. """ if not (peerid, callid) in self._remote_to_local: logger.warn("No remote call %s from %s. Might just be unfoutunate timing." % (callid, peerid))
[ "Called", "from", "remote", "to", "ask", "if", "a", "call", "made", "to", "here", "is", "still", "in", "progress", "." ]
pydron/anycall
python
https://github.com/pydron/anycall/blob/43add96660258a14b24aa8e8413dffb1741b72d7/anycall/rpc.py#L425-L430
[ "def", "_ping", "(", "self", ",", "peerid", ",", "callid", ")", ":", "if", "not", "(", "peerid", ",", "callid", ")", "in", "self", ".", "_remote_to_local", ":", "logger", ".", "warn", "(", "\"No remote call %s from %s. Might just be unfoutunate timing.\"", "%", "(", "callid", ",", "peerid", ")", ")" ]
43add96660258a14b24aa8e8413dffb1741b72d7
test
register_app_for_error_handling
Wraps a WSGI app and handles uncaught exceptions and defined exception and outputs a the exception in a structured format. Parameters: - wsgi_app is the app.wsgi_app of flask, - app_name should in correct format e.g. APP_NAME_1, - app_logger is the logger object
app_error_handler/application_error_handler.py
def register_app_for_error_handling(wsgi_app, app_name, app_logger, custom_logging_service=None): """Wraps a WSGI app and handles uncaught exceptions and defined exception and outputs a the exception in a structured format. Parameters: - wsgi_app is the app.wsgi_app of flask, - app_name should in correct format e.g. APP_NAME_1, - app_logger is the logger object""" logging_service = LoggingService(app_logger) if custom_logging_service is None else custom_logging_service exception_manager = ExceptionHandler(app_name, logging_service) def wrapper(environ, start_response): try: return wsgi_app(environ, start_response) except RootException as e: app_request = Request(environ) stack_trace = traceback.format_exc().splitlines()[-1] exception_manager.update_with_exception_data(e, app_request, stack_trace) except Exception: app_request = Request(environ) stack_trace = traceback.format_exc() e = RootException("FATAL_000", {}, {}, {}, status_code=500) e.error_message = "Unknown System Error" exception_manager.update_with_exception_data(e, app_request, stack_trace) error_details = exception_manager.construct_error_details() http_status_code = exception_manager.get_http_status_code() response = Response(json.dumps(error_details), status=http_status_code, content_type='application/json') return response(environ, start_response) return wrapper
def register_app_for_error_handling(wsgi_app, app_name, app_logger, custom_logging_service=None): """Wraps a WSGI app and handles uncaught exceptions and defined exception and outputs a the exception in a structured format. Parameters: - wsgi_app is the app.wsgi_app of flask, - app_name should in correct format e.g. APP_NAME_1, - app_logger is the logger object""" logging_service = LoggingService(app_logger) if custom_logging_service is None else custom_logging_service exception_manager = ExceptionHandler(app_name, logging_service) def wrapper(environ, start_response): try: return wsgi_app(environ, start_response) except RootException as e: app_request = Request(environ) stack_trace = traceback.format_exc().splitlines()[-1] exception_manager.update_with_exception_data(e, app_request, stack_trace) except Exception: app_request = Request(environ) stack_trace = traceback.format_exc() e = RootException("FATAL_000", {}, {}, {}, status_code=500) e.error_message = "Unknown System Error" exception_manager.update_with_exception_data(e, app_request, stack_trace) error_details = exception_manager.construct_error_details() http_status_code = exception_manager.get_http_status_code() response = Response(json.dumps(error_details), status=http_status_code, content_type='application/json') return response(environ, start_response) return wrapper
[ "Wraps", "a", "WSGI", "app", "and", "handles", "uncaught", "exceptions", "and", "defined", "exception", "and", "outputs", "a", "the", "exception", "in", "a", "structured", "format", ".", "Parameters", ":", "-", "wsgi_app", "is", "the", "app", ".", "wsgi_app", "of", "flask", "-", "app_name", "should", "in", "correct", "format", "e", ".", "g", ".", "APP_NAME_1", "-", "app_logger", "is", "the", "logger", "object" ]
raviparekh/webapp-error-handler
python
https://github.com/raviparekh/webapp-error-handler/blob/11e20bea464331e254034b02661c53fb19102d4a/app_error_handler/application_error_handler.py#L9-L39
[ "def", "register_app_for_error_handling", "(", "wsgi_app", ",", "app_name", ",", "app_logger", ",", "custom_logging_service", "=", "None", ")", ":", "logging_service", "=", "LoggingService", "(", "app_logger", ")", "if", "custom_logging_service", "is", "None", "else", "custom_logging_service", "exception_manager", "=", "ExceptionHandler", "(", "app_name", ",", "logging_service", ")", "def", "wrapper", "(", "environ", ",", "start_response", ")", ":", "try", ":", "return", "wsgi_app", "(", "environ", ",", "start_response", ")", "except", "RootException", "as", "e", ":", "app_request", "=", "Request", "(", "environ", ")", "stack_trace", "=", "traceback", ".", "format_exc", "(", ")", ".", "splitlines", "(", ")", "[", "-", "1", "]", "exception_manager", ".", "update_with_exception_data", "(", "e", ",", "app_request", ",", "stack_trace", ")", "except", "Exception", ":", "app_request", "=", "Request", "(", "environ", ")", "stack_trace", "=", "traceback", ".", "format_exc", "(", ")", "e", "=", "RootException", "(", "\"FATAL_000\"", ",", "{", "}", ",", "{", "}", ",", "{", "}", ",", "status_code", "=", "500", ")", "e", ".", "error_message", "=", "\"Unknown System Error\"", "exception_manager", ".", "update_with_exception_data", "(", "e", ",", "app_request", ",", "stack_trace", ")", "error_details", "=", "exception_manager", ".", "construct_error_details", "(", ")", "http_status_code", "=", "exception_manager", ".", "get_http_status_code", "(", ")", "response", "=", "Response", "(", "json", ".", "dumps", "(", "error_details", ")", ",", "status", "=", "http_status_code", ",", "content_type", "=", "'application/json'", ")", "return", "response", "(", "environ", ",", "start_response", ")", "return", "wrapper" ]
11e20bea464331e254034b02661c53fb19102d4a
test
_CommandCompleterMixin._cmdRegex
Get command regex string and completer dict.
nicfit/shell/command.py
def _cmdRegex(self, cmd_grp=None): """Get command regex string and completer dict.""" cmd_grp = cmd_grp or "cmd" help_opts = ("-h", "--help") cmd = self.name() names = "|".join([re.escape(cmd)] + [re.escape(a) for a in self.aliases()]) opts = [] for action in self.parser._actions: opts += [a for a in action.option_strings if a not in help_opts] opts_re = "|".join([re.escape(o) for o in opts]) if opts_re: opts_re = rf"(\s+(?P<{cmd_grp}_opts>{opts_re}))*" help_re = "|".join([re.escape(o) for o in help_opts]) help_re = rf"(\s+(?P<HELP_OPTS>{help_re}))*" completers = {} if opts_re: completers[f"{cmd_grp}_opts"] = WordCompleter(opts) # Singe Help completer added elsewhere return tuple([ rf"""(?P<{cmd_grp}>{names}){opts_re}{help_re}""", completers ])
def _cmdRegex(self, cmd_grp=None): """Get command regex string and completer dict.""" cmd_grp = cmd_grp or "cmd" help_opts = ("-h", "--help") cmd = self.name() names = "|".join([re.escape(cmd)] + [re.escape(a) for a in self.aliases()]) opts = [] for action in self.parser._actions: opts += [a for a in action.option_strings if a not in help_opts] opts_re = "|".join([re.escape(o) for o in opts]) if opts_re: opts_re = rf"(\s+(?P<{cmd_grp}_opts>{opts_re}))*" help_re = "|".join([re.escape(o) for o in help_opts]) help_re = rf"(\s+(?P<HELP_OPTS>{help_re}))*" completers = {} if opts_re: completers[f"{cmd_grp}_opts"] = WordCompleter(opts) # Singe Help completer added elsewhere return tuple([ rf"""(?P<{cmd_grp}>{names}){opts_re}{help_re}""", completers ])
[ "Get", "command", "regex", "string", "and", "completer", "dict", "." ]
nicfit/nicfit.py
python
https://github.com/nicfit/nicfit.py/blob/8313f8edbc5e7361ddad496d6d818324b5236c7a/nicfit/shell/command.py#L18-L47
[ "def", "_cmdRegex", "(", "self", ",", "cmd_grp", "=", "None", ")", ":", "cmd_grp", "=", "cmd_grp", "or", "\"cmd\"", "help_opts", "=", "(", "\"-h\"", ",", "\"--help\"", ")", "cmd", "=", "self", ".", "name", "(", ")", "names", "=", "\"|\"", ".", "join", "(", "[", "re", ".", "escape", "(", "cmd", ")", "]", "+", "[", "re", ".", "escape", "(", "a", ")", "for", "a", "in", "self", ".", "aliases", "(", ")", "]", ")", "opts", "=", "[", "]", "for", "action", "in", "self", ".", "parser", ".", "_actions", ":", "opts", "+=", "[", "a", "for", "a", "in", "action", ".", "option_strings", "if", "a", "not", "in", "help_opts", "]", "opts_re", "=", "\"|\"", ".", "join", "(", "[", "re", ".", "escape", "(", "o", ")", "for", "o", "in", "opts", "]", ")", "if", "opts_re", ":", "opts_re", "=", "rf\"(\\s+(?P<{cmd_grp}_opts>{opts_re}))*\"", "help_re", "=", "\"|\"", ".", "join", "(", "[", "re", ".", "escape", "(", "o", ")", "for", "o", "in", "help_opts", "]", ")", "help_re", "=", "rf\"(\\s+(?P<HELP_OPTS>{help_re}))*\"", "completers", "=", "{", "}", "if", "opts_re", ":", "completers", "[", "f\"{cmd_grp}_opts\"", "]", "=", "WordCompleter", "(", "opts", ")", "# Singe Help completer added elsewhere", "return", "tuple", "(", "[", "rf\"\"\"(?P<{cmd_grp}>{names}){opts_re}{help_re}\"\"\"", ",", "completers", "]", ")" ]
8313f8edbc5e7361ddad496d6d818324b5236c7a
test
NestedAMPBox.fromStringProto
Defers to `amp.AmpList`, then gets the element from the list.
txampext/nested.py
def fromStringProto(self, inString, proto): """ Defers to `amp.AmpList`, then gets the element from the list. """ value, = amp.AmpList.fromStringProto(self, inString, proto) return value
def fromStringProto(self, inString, proto): """ Defers to `amp.AmpList`, then gets the element from the list. """ value, = amp.AmpList.fromStringProto(self, inString, proto) return value
[ "Defers", "to", "amp", ".", "AmpList", "then", "gets", "the", "element", "from", "the", "list", "." ]
lvh/txampext
python
https://github.com/lvh/txampext/blob/a7d6cb9f1e9200dba597378cd40eb6a2096d4fd9/txampext/nested.py#L13-L18
[ "def", "fromStringProto", "(", "self", ",", "inString", ",", "proto", ")", ":", "value", ",", "=", "amp", ".", "AmpList", ".", "fromStringProto", "(", "self", ",", "inString", ",", "proto", ")", "return", "value" ]
a7d6cb9f1e9200dba597378cd40eb6a2096d4fd9
test
NestedAMPBox.toStringProto
Wraps the object in a list, and then defers to ``amp.AmpList``.
txampext/nested.py
def toStringProto(self, inObject, proto): """ Wraps the object in a list, and then defers to ``amp.AmpList``. """ return amp.AmpList.toStringProto(self, [inObject], proto)
def toStringProto(self, inObject, proto): """ Wraps the object in a list, and then defers to ``amp.AmpList``. """ return amp.AmpList.toStringProto(self, [inObject], proto)
[ "Wraps", "the", "object", "in", "a", "list", "and", "then", "defers", "to", "amp", ".", "AmpList", "." ]
lvh/txampext
python
https://github.com/lvh/txampext/blob/a7d6cb9f1e9200dba597378cd40eb6a2096d4fd9/txampext/nested.py#L21-L25
[ "def", "toStringProto", "(", "self", ",", "inObject", ",", "proto", ")", ":", "return", "amp", ".", "AmpList", ".", "toStringProto", "(", "self", ",", "[", "inObject", "]", ",", "proto", ")" ]
a7d6cb9f1e9200dba597378cd40eb6a2096d4fd9
test
unfurl
Return the body of a signed JWT, without verifying the signature. :param jwt: A signed JWT :return: The body of the JWT as a 'UTF-8' string
src/fedoidcmsg/__init__.py
def unfurl(jwt): """ Return the body of a signed JWT, without verifying the signature. :param jwt: A signed JWT :return: The body of the JWT as a 'UTF-8' string """ _rp_jwt = factory(jwt) return json.loads(_rp_jwt.jwt.part[1].decode('utf8'))
def unfurl(jwt): """ Return the body of a signed JWT, without verifying the signature. :param jwt: A signed JWT :return: The body of the JWT as a 'UTF-8' string """ _rp_jwt = factory(jwt) return json.loads(_rp_jwt.jwt.part[1].decode('utf8'))
[ "Return", "the", "body", "of", "a", "signed", "JWT", "without", "verifying", "the", "signature", ".", ":", "param", "jwt", ":", "A", "signed", "JWT", ":", "return", ":", "The", "body", "of", "the", "JWT", "as", "a", "UTF", "-", "8", "string" ]
IdentityPython/fedoidcmsg
python
https://github.com/IdentityPython/fedoidcmsg/blob/d30107be02521fa6cdfe285da3b6b0cdd153c8cc/src/fedoidcmsg/__init__.py#L117-L126
[ "def", "unfurl", "(", "jwt", ")", ":", "_rp_jwt", "=", "factory", "(", "jwt", ")", "return", "json", ".", "loads", "(", "_rp_jwt", ".", "jwt", ".", "part", "[", "1", "]", ".", "decode", "(", "'utf8'", ")", ")" ]
d30107be02521fa6cdfe285da3b6b0cdd153c8cc
test
keyjar_from_metadata_statements
Builds a keyJar instance based on the information in the 'signing_keys' claims in a list of metadata statements. :param iss: Owner of the signing keys :param msl: List of :py:class:`MetadataStatement` instances. :return: A :py:class:`oidcmsg.key_jar.KeyJar` instance
src/fedoidcmsg/__init__.py
def keyjar_from_metadata_statements(iss, msl): """ Builds a keyJar instance based on the information in the 'signing_keys' claims in a list of metadata statements. :param iss: Owner of the signing keys :param msl: List of :py:class:`MetadataStatement` instances. :return: A :py:class:`oidcmsg.key_jar.KeyJar` instance """ keyjar = KeyJar() for ms in msl: keyjar.import_jwks(ms['signing_keys'], iss) return keyjar
def keyjar_from_metadata_statements(iss, msl): """ Builds a keyJar instance based on the information in the 'signing_keys' claims in a list of metadata statements. :param iss: Owner of the signing keys :param msl: List of :py:class:`MetadataStatement` instances. :return: A :py:class:`oidcmsg.key_jar.KeyJar` instance """ keyjar = KeyJar() for ms in msl: keyjar.import_jwks(ms['signing_keys'], iss) return keyjar
[ "Builds", "a", "keyJar", "instance", "based", "on", "the", "information", "in", "the", "signing_keys", "claims", "in", "a", "list", "of", "metadata", "statements", ".", ":", "param", "iss", ":", "Owner", "of", "the", "signing", "keys", ":", "param", "msl", ":", "List", "of", ":", "py", ":", "class", ":", "MetadataStatement", "instances", ".", ":", "return", ":", "A", ":", "py", ":", "class", ":", "oidcmsg", ".", "key_jar", ".", "KeyJar", "instance" ]
IdentityPython/fedoidcmsg
python
https://github.com/IdentityPython/fedoidcmsg/blob/d30107be02521fa6cdfe285da3b6b0cdd153c8cc/src/fedoidcmsg/__init__.py#L129-L141
[ "def", "keyjar_from_metadata_statements", "(", "iss", ",", "msl", ")", ":", "keyjar", "=", "KeyJar", "(", ")", "for", "ms", "in", "msl", ":", "keyjar", ".", "import_jwks", "(", "ms", "[", "'signing_keys'", "]", ",", "iss", ")", "return", "keyjar" ]
d30107be02521fa6cdfe285da3b6b0cdd153c8cc
test
read_jwks_file
Reads a file containing a JWKS and populates a :py:class:`oidcmsg.key_jar.KeyJar` from it. :param jwks_file: file name of the JWKS file :return: A :py:class:`oidcmsg.key_jar.KeyJar` instance
src/fedoidcmsg/__init__.py
def read_jwks_file(jwks_file): """ Reads a file containing a JWKS and populates a :py:class:`oidcmsg.key_jar.KeyJar` from it. :param jwks_file: file name of the JWKS file :return: A :py:class:`oidcmsg.key_jar.KeyJar` instance """ _jwks = open(jwks_file, 'r').read() _kj = KeyJar() _kj.import_jwks(json.loads(_jwks), '') return _kj
def read_jwks_file(jwks_file): """ Reads a file containing a JWKS and populates a :py:class:`oidcmsg.key_jar.KeyJar` from it. :param jwks_file: file name of the JWKS file :return: A :py:class:`oidcmsg.key_jar.KeyJar` instance """ _jwks = open(jwks_file, 'r').read() _kj = KeyJar() _kj.import_jwks(json.loads(_jwks), '') return _kj
[ "Reads", "a", "file", "containing", "a", "JWKS", "and", "populates", "a", ":", "py", ":", "class", ":", "oidcmsg", ".", "key_jar", ".", "KeyJar", "from", "it", "." ]
IdentityPython/fedoidcmsg
python
https://github.com/IdentityPython/fedoidcmsg/blob/d30107be02521fa6cdfe285da3b6b0cdd153c8cc/src/fedoidcmsg/__init__.py#L144-L155
[ "def", "read_jwks_file", "(", "jwks_file", ")", ":", "_jwks", "=", "open", "(", "jwks_file", ",", "'r'", ")", ".", "read", "(", ")", "_kj", "=", "KeyJar", "(", ")", "_kj", ".", "import_jwks", "(", "json", ".", "loads", "(", "_jwks", ")", ",", "''", ")", "return", "_kj" ]
d30107be02521fa6cdfe285da3b6b0cdd153c8cc
test
is_lesser
Verify that an item *a* is <= then an item *b* :param a: An item :param b: Another item :return: True or False
src/fedoidcmsg/__init__.py
def is_lesser(a, b): """ Verify that an item *a* is <= then an item *b* :param a: An item :param b: Another item :return: True or False """ if type(a) != type(b): return False if isinstance(a, str) and isinstance(b, str): return a == b elif isinstance(a, bool) and isinstance(b, bool): return a == b elif isinstance(a, list) and isinstance(b, list): for element in a: flag = 0 for e in b: if is_lesser(element, e): flag = 1 break if not flag: return False return True elif isinstance(a, dict) and isinstance(b, dict): if is_lesser(list(a.keys()), list(b.keys())): for key, val in a.items(): if not is_lesser(val, b[key]): return False return True return False elif isinstance(a, int) and isinstance(b, int): return a <= b elif isinstance(a, float) and isinstance(b, float): return a <= b return False
def is_lesser(a, b): """ Verify that an item *a* is <= then an item *b* :param a: An item :param b: Another item :return: True or False """ if type(a) != type(b): return False if isinstance(a, str) and isinstance(b, str): return a == b elif isinstance(a, bool) and isinstance(b, bool): return a == b elif isinstance(a, list) and isinstance(b, list): for element in a: flag = 0 for e in b: if is_lesser(element, e): flag = 1 break if not flag: return False return True elif isinstance(a, dict) and isinstance(b, dict): if is_lesser(list(a.keys()), list(b.keys())): for key, val in a.items(): if not is_lesser(val, b[key]): return False return True return False elif isinstance(a, int) and isinstance(b, int): return a <= b elif isinstance(a, float) and isinstance(b, float): return a <= b return False
[ "Verify", "that", "an", "item", "*", "a", "*", "is", "<", "=", "then", "an", "item", "*", "b", "*", ":", "param", "a", ":", "An", "item", ":", "param", "b", ":", "Another", "item", ":", "return", ":", "True", "or", "False" ]
IdentityPython/fedoidcmsg
python
https://github.com/IdentityPython/fedoidcmsg/blob/d30107be02521fa6cdfe285da3b6b0cdd153c8cc/src/fedoidcmsg/__init__.py#L158-L196
[ "def", "is_lesser", "(", "a", ",", "b", ")", ":", "if", "type", "(", "a", ")", "!=", "type", "(", "b", ")", ":", "return", "False", "if", "isinstance", "(", "a", ",", "str", ")", "and", "isinstance", "(", "b", ",", "str", ")", ":", "return", "a", "==", "b", "elif", "isinstance", "(", "a", ",", "bool", ")", "and", "isinstance", "(", "b", ",", "bool", ")", ":", "return", "a", "==", "b", "elif", "isinstance", "(", "a", ",", "list", ")", "and", "isinstance", "(", "b", ",", "list", ")", ":", "for", "element", "in", "a", ":", "flag", "=", "0", "for", "e", "in", "b", ":", "if", "is_lesser", "(", "element", ",", "e", ")", ":", "flag", "=", "1", "break", "if", "not", "flag", ":", "return", "False", "return", "True", "elif", "isinstance", "(", "a", ",", "dict", ")", "and", "isinstance", "(", "b", ",", "dict", ")", ":", "if", "is_lesser", "(", "list", "(", "a", ".", "keys", "(", ")", ")", ",", "list", "(", "b", ".", "keys", "(", ")", ")", ")", ":", "for", "key", ",", "val", "in", "a", ".", "items", "(", ")", ":", "if", "not", "is_lesser", "(", "val", ",", "b", "[", "key", "]", ")", ":", "return", "False", "return", "True", "return", "False", "elif", "isinstance", "(", "a", ",", "int", ")", "and", "isinstance", "(", "b", ",", "int", ")", ":", "return", "a", "<=", "b", "elif", "isinstance", "(", "a", ",", "float", ")", "and", "isinstance", "(", "b", ",", "float", ")", ":", "return", "a", "<=", "b", "return", "False" ]
d30107be02521fa6cdfe285da3b6b0cdd153c8cc
test
MetadataStatement.verify
Verifies that an instance of this class adheres to the given restrictions. :param kwargs: A set of keyword arguments :return: True if it verifies OK otherwise False.
src/fedoidcmsg/__init__.py
def verify(self, **kwargs): """ Verifies that an instance of this class adheres to the given restrictions. :param kwargs: A set of keyword arguments :return: True if it verifies OK otherwise False. """ super(MetadataStatement, self).verify(**kwargs) if "signing_keys" in self: if 'signing_keys_uri' in self: raise VerificationError( 'You can only have one of "signing_keys" and ' '"signing_keys_uri" in a metadata statement') else: # signing_keys MUST be a JWKS kj = KeyJar() try: kj.import_jwks(self['signing_keys'], '') except Exception: raise VerificationError('"signing_keys" not a proper JWKS') if "metadata_statements" in self and "metadata_statement_uris" in self: s = set(self['metadata_statements'].keys()) t = set(self['metadata_statement_uris'].keys()) if s.intersection(t): raise VerificationError( 'You should not have the same key in "metadata_statements" ' 'and in "metadata_statement_uris"') return True
def verify(self, **kwargs): """ Verifies that an instance of this class adheres to the given restrictions. :param kwargs: A set of keyword arguments :return: True if it verifies OK otherwise False. """ super(MetadataStatement, self).verify(**kwargs) if "signing_keys" in self: if 'signing_keys_uri' in self: raise VerificationError( 'You can only have one of "signing_keys" and ' '"signing_keys_uri" in a metadata statement') else: # signing_keys MUST be a JWKS kj = KeyJar() try: kj.import_jwks(self['signing_keys'], '') except Exception: raise VerificationError('"signing_keys" not a proper JWKS') if "metadata_statements" in self and "metadata_statement_uris" in self: s = set(self['metadata_statements'].keys()) t = set(self['metadata_statement_uris'].keys()) if s.intersection(t): raise VerificationError( 'You should not have the same key in "metadata_statements" ' 'and in "metadata_statement_uris"') return True
[ "Verifies", "that", "an", "instance", "of", "this", "class", "adheres", "to", "the", "given", "restrictions", "." ]
IdentityPython/fedoidcmsg
python
https://github.com/IdentityPython/fedoidcmsg/blob/d30107be02521fa6cdfe285da3b6b0cdd153c8cc/src/fedoidcmsg/__init__.py#L59-L89
[ "def", "verify", "(", "self", ",", "*", "*", "kwargs", ")", ":", "super", "(", "MetadataStatement", ",", "self", ")", ".", "verify", "(", "*", "*", "kwargs", ")", "if", "\"signing_keys\"", "in", "self", ":", "if", "'signing_keys_uri'", "in", "self", ":", "raise", "VerificationError", "(", "'You can only have one of \"signing_keys\" and '", "'\"signing_keys_uri\" in a metadata statement'", ")", "else", ":", "# signing_keys MUST be a JWKS", "kj", "=", "KeyJar", "(", ")", "try", ":", "kj", ".", "import_jwks", "(", "self", "[", "'signing_keys'", "]", ",", "''", ")", "except", "Exception", ":", "raise", "VerificationError", "(", "'\"signing_keys\" not a proper JWKS'", ")", "if", "\"metadata_statements\"", "in", "self", "and", "\"metadata_statement_uris\"", "in", "self", ":", "s", "=", "set", "(", "self", "[", "'metadata_statements'", "]", ".", "keys", "(", ")", ")", "t", "=", "set", "(", "self", "[", "'metadata_statement_uris'", "]", ".", "keys", "(", ")", ")", "if", "s", ".", "intersection", "(", "t", ")", ":", "raise", "VerificationError", "(", "'You should not have the same key in \"metadata_statements\" '", "'and in \"metadata_statement_uris\"'", ")", "return", "True" ]
d30107be02521fa6cdfe285da3b6b0cdd153c8cc
test
KeyBundle._parse_remote_response
Parse simple JWKS or signed JWKS from the HTTP response. :param response: HTTP response from the 'jwks_uri' or 'signed_jwks_uri' endpoint :return: response parsed as JSON or None
src/fedoidcmsg/__init__.py
def _parse_remote_response(self, response): """ Parse simple JWKS or signed JWKS from the HTTP response. :param response: HTTP response from the 'jwks_uri' or 'signed_jwks_uri' endpoint :return: response parsed as JSON or None """ # Check if the content type is the right one. try: if response.headers["Content-Type"] == 'application/json': logger.debug( "Loaded JWKS: %s from %s" % (response.text, self.source)) try: return json.loads(response.text) except ValueError: return None elif response.headers["Content-Type"] == 'application/jwt': logger.debug( "Signed JWKS: %s from %s" % (response.text, self.source)) _jws = factory(response.text) _resp = _jws.verify_compact( response.text, keys=self.verify_keys.get_signing_key()) return _resp else: logger.error('Wrong content type: {}'.format( response.headers['Content-Type'])) raise ValueError('Content-type mismatch') except KeyError: pass
def _parse_remote_response(self, response): """ Parse simple JWKS or signed JWKS from the HTTP response. :param response: HTTP response from the 'jwks_uri' or 'signed_jwks_uri' endpoint :return: response parsed as JSON or None """ # Check if the content type is the right one. try: if response.headers["Content-Type"] == 'application/json': logger.debug( "Loaded JWKS: %s from %s" % (response.text, self.source)) try: return json.loads(response.text) except ValueError: return None elif response.headers["Content-Type"] == 'application/jwt': logger.debug( "Signed JWKS: %s from %s" % (response.text, self.source)) _jws = factory(response.text) _resp = _jws.verify_compact( response.text, keys=self.verify_keys.get_signing_key()) return _resp else: logger.error('Wrong content type: {}'.format( response.headers['Content-Type'])) raise ValueError('Content-type mismatch') except KeyError: pass
[ "Parse", "simple", "JWKS", "or", "signed", "JWKS", "from", "the", "HTTP", "response", "." ]
IdentityPython/fedoidcmsg
python
https://github.com/IdentityPython/fedoidcmsg/blob/d30107be02521fa6cdfe285da3b6b0cdd153c8cc/src/fedoidcmsg/__init__.py#L232-L261
[ "def", "_parse_remote_response", "(", "self", ",", "response", ")", ":", "# Check if the content type is the right one.", "try", ":", "if", "response", ".", "headers", "[", "\"Content-Type\"", "]", "==", "'application/json'", ":", "logger", ".", "debug", "(", "\"Loaded JWKS: %s from %s\"", "%", "(", "response", ".", "text", ",", "self", ".", "source", ")", ")", "try", ":", "return", "json", ".", "loads", "(", "response", ".", "text", ")", "except", "ValueError", ":", "return", "None", "elif", "response", ".", "headers", "[", "\"Content-Type\"", "]", "==", "'application/jwt'", ":", "logger", ".", "debug", "(", "\"Signed JWKS: %s from %s\"", "%", "(", "response", ".", "text", ",", "self", ".", "source", ")", ")", "_jws", "=", "factory", "(", "response", ".", "text", ")", "_resp", "=", "_jws", ".", "verify_compact", "(", "response", ".", "text", ",", "keys", "=", "self", ".", "verify_keys", ".", "get_signing_key", "(", ")", ")", "return", "_resp", "else", ":", "logger", ".", "error", "(", "'Wrong content type: {}'", ".", "format", "(", "response", ".", "headers", "[", "'Content-Type'", "]", ")", ")", "raise", "ValueError", "(", "'Content-type mismatch'", ")", "except", "KeyError", ":", "pass" ]
d30107be02521fa6cdfe285da3b6b0cdd153c8cc
test
dump
Performs a pg_dump backup. It runs with the current systemuser's privileges, unless you specify username and password. By default pg_dump connects to the value given in the PGHOST environment variable. You can either specify "hostname" and "port" or a socket path. pg_dump expects the pg_dump-utility to be on $PATCH. Should that not be case you are allowed to specify a custom location with "pg_dump_path" Format is p (plain / default), c = custom, d = directory, t=tar returns statuscode and shelloutput
pyque/db/postgresql.py
def dump(filename, dbname, username=None, password=None, host=None, port=None, tempdir='/tmp', pg_dump_path='pg_dump', format='p'): """Performs a pg_dump backup. It runs with the current systemuser's privileges, unless you specify username and password. By default pg_dump connects to the value given in the PGHOST environment variable. You can either specify "hostname" and "port" or a socket path. pg_dump expects the pg_dump-utility to be on $PATCH. Should that not be case you are allowed to specify a custom location with "pg_dump_path" Format is p (plain / default), c = custom, d = directory, t=tar returns statuscode and shelloutput """ filepath = os.path.join(tempdir, filename) cmd = pg_dump_path cmd += ' --format %s' % format cmd += ' --file ' + os.path.join(tempdir, filename) if username: cmd += ' --username %s' % username if host: cmd += ' --host %s' % host if port: cmd += ' --port %s' % port cmd += ' ' + dbname ## export pgpasswd if password: os.environ["PGPASSWORD"] = password ## run pgdump return sh(cmd)
def dump(filename, dbname, username=None, password=None, host=None, port=None, tempdir='/tmp', pg_dump_path='pg_dump', format='p'): """Performs a pg_dump backup. It runs with the current systemuser's privileges, unless you specify username and password. By default pg_dump connects to the value given in the PGHOST environment variable. You can either specify "hostname" and "port" or a socket path. pg_dump expects the pg_dump-utility to be on $PATCH. Should that not be case you are allowed to specify a custom location with "pg_dump_path" Format is p (plain / default), c = custom, d = directory, t=tar returns statuscode and shelloutput """ filepath = os.path.join(tempdir, filename) cmd = pg_dump_path cmd += ' --format %s' % format cmd += ' --file ' + os.path.join(tempdir, filename) if username: cmd += ' --username %s' % username if host: cmd += ' --host %s' % host if port: cmd += ' --port %s' % port cmd += ' ' + dbname ## export pgpasswd if password: os.environ["PGPASSWORD"] = password ## run pgdump return sh(cmd)
[ "Performs", "a", "pg_dump", "backup", "." ]
bmaeser/pyque
python
https://github.com/bmaeser/pyque/blob/856dceab8d89cf3771cf21e682466c29a85ae8eb/pyque/db/postgresql.py#L11-L52
[ "def", "dump", "(", "filename", ",", "dbname", ",", "username", "=", "None", ",", "password", "=", "None", ",", "host", "=", "None", ",", "port", "=", "None", ",", "tempdir", "=", "'/tmp'", ",", "pg_dump_path", "=", "'pg_dump'", ",", "format", "=", "'p'", ")", ":", "filepath", "=", "os", ".", "path", ".", "join", "(", "tempdir", ",", "filename", ")", "cmd", "=", "pg_dump_path", "cmd", "+=", "' --format %s'", "%", "format", "cmd", "+=", "' --file '", "+", "os", ".", "path", ".", "join", "(", "tempdir", ",", "filename", ")", "if", "username", ":", "cmd", "+=", "' --username %s'", "%", "username", "if", "host", ":", "cmd", "+=", "' --host %s'", "%", "host", "if", "port", ":", "cmd", "+=", "' --port %s'", "%", "port", "cmd", "+=", "' '", "+", "dbname", "## export pgpasswd", "if", "password", ":", "os", ".", "environ", "[", "\"PGPASSWORD\"", "]", "=", "password", "## run pgdump", "return", "sh", "(", "cmd", ")" ]
856dceab8d89cf3771cf21e682466c29a85ae8eb
test
_connection
returns a connected cursor to the database-server.
pyque/db/postgresql.py
def _connection(username=None, password=None, host=None, port=None, db=None): "returns a connected cursor to the database-server." c_opts = {} if username: c_opts['user'] = username if password: c_opts['password'] = password if host: c_opts['host'] = host if port: c_opts['port'] = port if db: c_opts['database'] = db dbc = psycopg2.connect(**c_opts) dbc.autocommit = True return dbc
def _connection(username=None, password=None, host=None, port=None, db=None): "returns a connected cursor to the database-server." c_opts = {} if username: c_opts['user'] = username if password: c_opts['password'] = password if host: c_opts['host'] = host if port: c_opts['port'] = port if db: c_opts['database'] = db dbc = psycopg2.connect(**c_opts) dbc.autocommit = True return dbc
[ "returns", "a", "connected", "cursor", "to", "the", "database", "-", "server", "." ]
bmaeser/pyque
python
https://github.com/bmaeser/pyque/blob/856dceab8d89cf3771cf21e682466c29a85ae8eb/pyque/db/postgresql.py#L55-L68
[ "def", "_connection", "(", "username", "=", "None", ",", "password", "=", "None", ",", "host", "=", "None", ",", "port", "=", "None", ",", "db", "=", "None", ")", ":", "c_opts", "=", "{", "}", "if", "username", ":", "c_opts", "[", "'user'", "]", "=", "username", "if", "password", ":", "c_opts", "[", "'password'", "]", "=", "password", "if", "host", ":", "c_opts", "[", "'host'", "]", "=", "host", "if", "port", ":", "c_opts", "[", "'port'", "]", "=", "port", "if", "db", ":", "c_opts", "[", "'database'", "]", "=", "db", "dbc", "=", "psycopg2", ".", "connect", "(", "*", "*", "c_opts", ")", "dbc", ".", "autocommit", "=", "True", "return", "dbc" ]
856dceab8d89cf3771cf21e682466c29a85ae8eb
test
db_list
returns a list of all databases on this server
pyque/db/postgresql.py
def db_list(username=None, password=None, host=None, port=None, maintain_db='postgres'): "returns a list of all databases on this server" conn = _connection(username=username, password=password, host=host, port=port, db=maintain_db) cur = conn.cursor() cur.execute('SELECT DATNAME from pg_database') rows = cur.fetchall() conn.close() result = [] for row in rows: result.append(row[0]) return result
def db_list(username=None, password=None, host=None, port=None, maintain_db='postgres'): "returns a list of all databases on this server" conn = _connection(username=username, password=password, host=host, port=port, db=maintain_db) cur = conn.cursor() cur.execute('SELECT DATNAME from pg_database') rows = cur.fetchall() conn.close() result = [] for row in rows: result.append(row[0]) return result
[ "returns", "a", "list", "of", "all", "databases", "on", "this", "server" ]
bmaeser/pyque
python
https://github.com/bmaeser/pyque/blob/856dceab8d89cf3771cf21e682466c29a85ae8eb/pyque/db/postgresql.py#L70-L88
[ "def", "db_list", "(", "username", "=", "None", ",", "password", "=", "None", ",", "host", "=", "None", ",", "port", "=", "None", ",", "maintain_db", "=", "'postgres'", ")", ":", "conn", "=", "_connection", "(", "username", "=", "username", ",", "password", "=", "password", ",", "host", "=", "host", ",", "port", "=", "port", ",", "db", "=", "maintain_db", ")", "cur", "=", "conn", ".", "cursor", "(", ")", "cur", ".", "execute", "(", "'SELECT DATNAME from pg_database'", ")", "rows", "=", "cur", ".", "fetchall", "(", ")", "conn", ".", "close", "(", ")", "result", "=", "[", "]", "for", "row", "in", "rows", ":", "result", ".", "append", "(", "row", "[", "0", "]", ")", "return", "result" ]
856dceab8d89cf3771cf21e682466c29a85ae8eb