repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_code_tokens
listlengths
15
672k
func_documentation_string
stringlengths
1
47.2k
func_documentation_tokens
listlengths
1
3.92k
split_name
stringclasses
1 value
func_code_url
stringlengths
85
339
72squared/redpipe
redpipe/pipelines.py
autoexec
def autoexec(pipe=None, name=None, exit_handler=None): """ create a pipeline with a context that will automatically execute the pipeline upon leaving the context if no exception was raised. :param pipe: :param name: :return: """ return pipeline(pipe=pipe, name=name, autoexec=True, exit_handler=exit_handler)
python
def autoexec(pipe=None, name=None, exit_handler=None): """ create a pipeline with a context that will automatically execute the pipeline upon leaving the context if no exception was raised. :param pipe: :param name: :return: """ return pipeline(pipe=pipe, name=name, autoexec=True, exit_handler=exit_handler)
[ "def", "autoexec", "(", "pipe", "=", "None", ",", "name", "=", "None", ",", "exit_handler", "=", "None", ")", ":", "return", "pipeline", "(", "pipe", "=", "pipe", ",", "name", "=", "name", ",", "autoexec", "=", "True", ",", "exit_handler", "=", "exit...
create a pipeline with a context that will automatically execute the pipeline upon leaving the context if no exception was raised. :param pipe: :param name: :return:
[ "create", "a", "pipeline", "with", "a", "context", "that", "will", "automatically", "execute", "the", "pipeline", "upon", "leaving", "the", "context", "if", "no", "exception", "was", "raised", "." ]
train
https://github.com/72squared/redpipe/blob/e6ee518bc9f3e2fee323c8c53d08997799bd9b1b/redpipe/pipelines.py#L451-L461
72squared/redpipe
redpipe/pipelines.py
Pipeline._pipeline
def _pipeline(self, name): """ Don't call this function directly. Used by the NestedPipeline class when it executes. :param name: :return: """ if name == self.connection_name: return self try: return self._pipelines[name] except KeyError: pipe = Pipeline(name=name, autoexec=True) self._pipelines[name] = pipe return pipe
python
def _pipeline(self, name): """ Don't call this function directly. Used by the NestedPipeline class when it executes. :param name: :return: """ if name == self.connection_name: return self try: return self._pipelines[name] except KeyError: pipe = Pipeline(name=name, autoexec=True) self._pipelines[name] = pipe return pipe
[ "def", "_pipeline", "(", "self", ",", "name", ")", ":", "if", "name", "==", "self", ".", "connection_name", ":", "return", "self", "try", ":", "return", "self", ".", "_pipelines", "[", "name", "]", "except", "KeyError", ":", "pipe", "=", "Pipeline", "(...
Don't call this function directly. Used by the NestedPipeline class when it executes. :param name: :return:
[ "Don", "t", "call", "this", "function", "directly", ".", "Used", "by", "the", "NestedPipeline", "class", "when", "it", "executes", ".", ":", "param", "name", ":", ":", "return", ":" ]
train
https://github.com/72squared/redpipe/blob/e6ee518bc9f3e2fee323c8c53d08997799bd9b1b/redpipe/pipelines.py#L111-L126
72squared/redpipe
redpipe/pipelines.py
Pipeline.execute
def execute(self): """ Invoke the redispy pipeline.execute() method and take all the values returned in sequential order of commands and map them to the Future objects we returned when each command was queued inside the pipeline. Also invoke all the callback functions queued up. :param raise_on_error: boolean :return: None """ stack = self._stack callbacks = self._callbacks promises = [] if stack: def process(): """ take all the commands and pass them to redis. this closure has the context of the stack :return: None """ # get the connection to redis pipe = ConnectionManager.get(self.connection_name) # keep track of all the commands call_stack = [] # build a corresponding list of the futures futures = [] # we need to do this because we need to make sure # all of these are callable. # there shouldn't be any non-callables. for item, args, kwargs, future in stack: f = getattr(pipe, item) if callable(f): futures.append(future) call_stack.append((f, args, kwargs)) # here's where we actually pass the commands to the # underlying redis-py pipeline() object. for f, args, kwargs in call_stack: f(*args, **kwargs) # execute the redis-py pipeline. # map all of the results into the futures. for i, v in enumerate(pipe.execute()): futures[i].set(v) promises.append(process) # collect all the other pipelines for other named connections attached. promises += [p.execute for p in self._pipelines.values()] if len(promises) == 1: promises[0]() else: # if there are no promises, this is basically a no-op. TaskManager.wait(*[TaskManager.promise(p) for p in promises]) for cb in callbacks: cb()
python
def execute(self): """ Invoke the redispy pipeline.execute() method and take all the values returned in sequential order of commands and map them to the Future objects we returned when each command was queued inside the pipeline. Also invoke all the callback functions queued up. :param raise_on_error: boolean :return: None """ stack = self._stack callbacks = self._callbacks promises = [] if stack: def process(): """ take all the commands and pass them to redis. this closure has the context of the stack :return: None """ # get the connection to redis pipe = ConnectionManager.get(self.connection_name) # keep track of all the commands call_stack = [] # build a corresponding list of the futures futures = [] # we need to do this because we need to make sure # all of these are callable. # there shouldn't be any non-callables. for item, args, kwargs, future in stack: f = getattr(pipe, item) if callable(f): futures.append(future) call_stack.append((f, args, kwargs)) # here's where we actually pass the commands to the # underlying redis-py pipeline() object. for f, args, kwargs in call_stack: f(*args, **kwargs) # execute the redis-py pipeline. # map all of the results into the futures. for i, v in enumerate(pipe.execute()): futures[i].set(v) promises.append(process) # collect all the other pipelines for other named connections attached. promises += [p.execute for p in self._pipelines.values()] if len(promises) == 1: promises[0]() else: # if there are no promises, this is basically a no-op. TaskManager.wait(*[TaskManager.promise(p) for p in promises]) for cb in callbacks: cb()
[ "def", "execute", "(", "self", ")", ":", "stack", "=", "self", ".", "_stack", "callbacks", "=", "self", ".", "_callbacks", "promises", "=", "[", "]", "if", "stack", ":", "def", "process", "(", ")", ":", "\"\"\"\n take all the commands and pass t...
Invoke the redispy pipeline.execute() method and take all the values returned in sequential order of commands and map them to the Future objects we returned when each command was queued inside the pipeline. Also invoke all the callback functions queued up. :param raise_on_error: boolean :return: None
[ "Invoke", "the", "redispy", "pipeline", ".", "execute", "()", "method", "and", "take", "all", "the", "values", "returned", "in", "sequential", "order", "of", "commands", "and", "map", "them", "to", "the", "Future", "objects", "we", "returned", "when", "each"...
train
https://github.com/72squared/redpipe/blob/e6ee518bc9f3e2fee323c8c53d08997799bd9b1b/redpipe/pipelines.py#L128-L189
72squared/redpipe
redpipe/pipelines.py
Pipeline.reset
def reset(self): """ cleanup method. get rid of the stack and callbacks. :return: """ self._stack = [] self._callbacks = [] pipes = self._pipelines self._pipelines = {} for pipe in pipes.values(): pipe.reset()
python
def reset(self): """ cleanup method. get rid of the stack and callbacks. :return: """ self._stack = [] self._callbacks = [] pipes = self._pipelines self._pipelines = {} for pipe in pipes.values(): pipe.reset()
[ "def", "reset", "(", "self", ")", ":", "self", ".", "_stack", "=", "[", "]", "self", ".", "_callbacks", "=", "[", "]", "pipes", "=", "self", ".", "_pipelines", "self", ".", "_pipelines", "=", "{", "}", "for", "pipe", "in", "pipes", ".", "values", ...
cleanup method. get rid of the stack and callbacks. :return:
[ "cleanup", "method", ".", "get", "rid", "of", "the", "stack", "and", "callbacks", ".", ":", "return", ":" ]
train
https://github.com/72squared/redpipe/blob/e6ee518bc9f3e2fee323c8c53d08997799bd9b1b/redpipe/pipelines.py#L221-L231
72squared/redpipe
redpipe/pipelines.py
NestedPipeline.execute
def execute(self): """ execute the commands inside the nested pipeline. This causes all queued up commands to be passed upstream to the parent, including callbacks. The state of this pipeline object gets cleaned up. :return: """ stack = self._stack callbacks = self._callbacks self._stack = [] self._callbacks = [] deferred = [] build = self._nested_future pipe = self._pipeline(self.connection_name) for item, args, kwargs, ref in stack: f = getattr(pipe, item) deferred.append(build(f(*args, **kwargs), ref)) inject_callbacks = getattr(self.parent, '_inject_callbacks') inject_callbacks(deferred + callbacks)
python
def execute(self): """ execute the commands inside the nested pipeline. This causes all queued up commands to be passed upstream to the parent, including callbacks. The state of this pipeline object gets cleaned up. :return: """ stack = self._stack callbacks = self._callbacks self._stack = [] self._callbacks = [] deferred = [] build = self._nested_future pipe = self._pipeline(self.connection_name) for item, args, kwargs, ref in stack: f = getattr(pipe, item) deferred.append(build(f(*args, **kwargs), ref)) inject_callbacks = getattr(self.parent, '_inject_callbacks') inject_callbacks(deferred + callbacks)
[ "def", "execute", "(", "self", ")", ":", "stack", "=", "self", ".", "_stack", "callbacks", "=", "self", ".", "_callbacks", "self", ".", "_stack", "=", "[", "]", "self", ".", "_callbacks", "=", "[", "]", "deferred", "=", "[", "]", "build", "=", "sel...
execute the commands inside the nested pipeline. This causes all queued up commands to be passed upstream to the parent, including callbacks. The state of this pipeline object gets cleaned up. :return:
[ "execute", "the", "commands", "inside", "the", "nested", "pipeline", ".", "This", "causes", "all", "queued", "up", "commands", "to", "be", "passed", "upstream", "to", "the", "parent", "including", "callbacks", ".", "The", "state", "of", "this", "pipeline", "...
train
https://github.com/72squared/redpipe/blob/e6ee518bc9f3e2fee323c8c53d08997799bd9b1b/redpipe/pipelines.py#L321-L344
inveniosoftware/dcxml
dcxml/xmlutils.py
dump_etree_helper
def dump_etree_helper(container_name, data, rules, nsmap, attrib): """Convert DataCite JSON format to DataCite XML. JSON should be validated before it is given to to_xml. """ output = etree.Element(container_name, nsmap=nsmap, attrib=attrib) for rule in rules: if rule not in data: continue element = rules[rule](rule, data[rule]) for e in element: output.append(e) return output
python
def dump_etree_helper(container_name, data, rules, nsmap, attrib): """Convert DataCite JSON format to DataCite XML. JSON should be validated before it is given to to_xml. """ output = etree.Element(container_name, nsmap=nsmap, attrib=attrib) for rule in rules: if rule not in data: continue element = rules[rule](rule, data[rule]) for e in element: output.append(e) return output
[ "def", "dump_etree_helper", "(", "container_name", ",", "data", ",", "rules", ",", "nsmap", ",", "attrib", ")", ":", "output", "=", "etree", ".", "Element", "(", "container_name", ",", "nsmap", "=", "nsmap", ",", "attrib", "=", "attrib", ")", "for", "rul...
Convert DataCite JSON format to DataCite XML. JSON should be validated before it is given to to_xml.
[ "Convert", "DataCite", "JSON", "format", "to", "DataCite", "XML", "." ]
train
https://github.com/inveniosoftware/dcxml/blob/9fed6123ec0f3f2e2f645ff91653a7e86a39138d/dcxml/xmlutils.py#L18-L33
inveniosoftware/dcxml
dcxml/xmlutils.py
etree_to_string
def etree_to_string(root, pretty_print=True, xml_declaration=True, encoding='utf-8'): """Dump XML etree as a string.""" return etree.tostring( root, pretty_print=pretty_print, xml_declaration=xml_declaration, encoding=encoding, ).decode('utf-8')
python
def etree_to_string(root, pretty_print=True, xml_declaration=True, encoding='utf-8'): """Dump XML etree as a string.""" return etree.tostring( root, pretty_print=pretty_print, xml_declaration=xml_declaration, encoding=encoding, ).decode('utf-8')
[ "def", "etree_to_string", "(", "root", ",", "pretty_print", "=", "True", ",", "xml_declaration", "=", "True", ",", "encoding", "=", "'utf-8'", ")", ":", "return", "etree", ".", "tostring", "(", "root", ",", "pretty_print", "=", "pretty_print", ",", "xml_decl...
Dump XML etree as a string.
[ "Dump", "XML", "etree", "as", "a", "string", "." ]
train
https://github.com/inveniosoftware/dcxml/blob/9fed6123ec0f3f2e2f645ff91653a7e86a39138d/dcxml/xmlutils.py#L36-L44
inveniosoftware/dcxml
dcxml/xmlutils.py
Rules.rule
def rule(self, key): """Decorate as a rule for a key in top level JSON.""" def register(f): self.rules[key] = f return f return register
python
def rule(self, key): """Decorate as a rule for a key in top level JSON.""" def register(f): self.rules[key] = f return f return register
[ "def", "rule", "(", "self", ",", "key", ")", ":", "def", "register", "(", "f", ")", ":", "self", ".", "rules", "[", "key", "]", "=", "f", "return", "f", "return", "register" ]
Decorate as a rule for a key in top level JSON.
[ "Decorate", "as", "a", "rule", "for", "a", "key", "in", "top", "level", "JSON", "." ]
train
https://github.com/inveniosoftware/dcxml/blob/9fed6123ec0f3f2e2f645ff91653a7e86a39138d/dcxml/xmlutils.py#L62-L67
openvax/datacache
datacache/database_table.py
DatabaseTable.from_dataframe
def from_dataframe(cls, name, df, indices, primary_key=None): """Infer table metadata from a DataFrame""" # ordered list (column_name, column_type) pairs column_types = [] # which columns have nullable values nullable = set() # tag cached database by dataframe's number of rows and columns for column_name in df.columns: values = df[column_name] if values.isnull().any(): nullable.add(column_name) column_db_type = db_type(values.dtype) column_types.append((column_name.replace(" ", "_"), column_db_type)) def make_rows(): return list(tuple(row) for row in df.values) return cls( name=name, column_types=column_types, make_rows=make_rows, indices=indices, nullable=nullable, primary_key=primary_key)
python
def from_dataframe(cls, name, df, indices, primary_key=None): """Infer table metadata from a DataFrame""" # ordered list (column_name, column_type) pairs column_types = [] # which columns have nullable values nullable = set() # tag cached database by dataframe's number of rows and columns for column_name in df.columns: values = df[column_name] if values.isnull().any(): nullable.add(column_name) column_db_type = db_type(values.dtype) column_types.append((column_name.replace(" ", "_"), column_db_type)) def make_rows(): return list(tuple(row) for row in df.values) return cls( name=name, column_types=column_types, make_rows=make_rows, indices=indices, nullable=nullable, primary_key=primary_key)
[ "def", "from_dataframe", "(", "cls", ",", "name", ",", "df", ",", "indices", ",", "primary_key", "=", "None", ")", ":", "# ordered list (column_name, column_type) pairs", "column_types", "=", "[", "]", "# which columns have nullable values", "nullable", "=", "set", ...
Infer table metadata from a DataFrame
[ "Infer", "table", "metadata", "from", "a", "DataFrame" ]
train
https://github.com/openvax/datacache/blob/73bcac02d37cf153710a07fbdc636aa55cb214ca/datacache/database_table.py#L43-L68
rmed/pyemtmad
pyemtmad/api/parking.py
ParkingApi.detail_parking
def detail_parking(self, **kwargs): """Obtain detailed info of a given parking. Args: lang (str): Language code (*es* or *en*). day (int): Day of the month in format DD. The number is automatically padded if it only has one digit. month (int): Month number in format MM. The number is automatically padded if it only has one digit. year (int): Year number in format YYYY. hour (int): Hour of the day in format hh. The number is automatically padded if it only has one digit. minute (int): Minute of the hour in format mm. The number is automatically padded if it only has one digit. parking (int): ID of the parking to query. family (str): Family code of the parking (3 chars). Returns: Status boolean and parsed response (list[ParkingDetails]), or message string in case of error. """ # Endpoint parameters date = util.datetime_string( kwargs.get('day', 1), kwargs.get('month', 1), kwargs.get('year', 1970), kwargs.get('hour', 0), kwargs.get('minute', 0) ) params = { 'language': util.language_code(kwargs.get('lang')), 'publicData': True, 'date': date, 'id': kwargs.get('parking'), 'family': kwargs.get('family') } # Request result = self.make_request('detail_parking', {}, **params) if not util.check_result(result): return False, result.get('message', 'UNKNOWN ERROR') # Parse values = util.response_list(result, 'Data') return True, [emtype.ParkingDetails(**a) for a in values]
python
def detail_parking(self, **kwargs): """Obtain detailed info of a given parking. Args: lang (str): Language code (*es* or *en*). day (int): Day of the month in format DD. The number is automatically padded if it only has one digit. month (int): Month number in format MM. The number is automatically padded if it only has one digit. year (int): Year number in format YYYY. hour (int): Hour of the day in format hh. The number is automatically padded if it only has one digit. minute (int): Minute of the hour in format mm. The number is automatically padded if it only has one digit. parking (int): ID of the parking to query. family (str): Family code of the parking (3 chars). Returns: Status boolean and parsed response (list[ParkingDetails]), or message string in case of error. """ # Endpoint parameters date = util.datetime_string( kwargs.get('day', 1), kwargs.get('month', 1), kwargs.get('year', 1970), kwargs.get('hour', 0), kwargs.get('minute', 0) ) params = { 'language': util.language_code(kwargs.get('lang')), 'publicData': True, 'date': date, 'id': kwargs.get('parking'), 'family': kwargs.get('family') } # Request result = self.make_request('detail_parking', {}, **params) if not util.check_result(result): return False, result.get('message', 'UNKNOWN ERROR') # Parse values = util.response_list(result, 'Data') return True, [emtype.ParkingDetails(**a) for a in values]
[ "def", "detail_parking", "(", "self", ",", "*", "*", "kwargs", ")", ":", "# Endpoint parameters", "date", "=", "util", ".", "datetime_string", "(", "kwargs", ".", "get", "(", "'day'", ",", "1", ")", ",", "kwargs", ".", "get", "(", "'month'", ",", "1", ...
Obtain detailed info of a given parking. Args: lang (str): Language code (*es* or *en*). day (int): Day of the month in format DD. The number is automatically padded if it only has one digit. month (int): Month number in format MM. The number is automatically padded if it only has one digit. year (int): Year number in format YYYY. hour (int): Hour of the day in format hh. The number is automatically padded if it only has one digit. minute (int): Minute of the hour in format mm. The number is automatically padded if it only has one digit. parking (int): ID of the parking to query. family (str): Family code of the parking (3 chars). Returns: Status boolean and parsed response (list[ParkingDetails]), or message string in case of error.
[ "Obtain", "detailed", "info", "of", "a", "given", "parking", "." ]
train
https://github.com/rmed/pyemtmad/blob/c21c42d0c7b50035dfed29540d7e64ab67833728/pyemtmad/api/parking.py#L39-L85
rmed/pyemtmad
pyemtmad/api/parking.py
ParkingApi.detail_poi
def detail_poi(self, **kwargs): """Obtain detailed info of a given POI. Args: family (str): Family code of the POI (3 chars). lang (str): Language code (*es* or *en*). id (int): Optional, ID of the POI to query. Passing value -1 will result in information from all POIs. Returns: Status boolean and parsed response (list[PoiDetails]), or message string in case of error. """ # Endpoint parameters params = { 'language': util.language_code(kwargs.get('lang')), 'family': kwargs.get('family') } if kwargs.get('id'): params['id'] = kwargs['id'] # Request result = self.make_request('detail_poi', {}, **params) if not util.check_result(result): return False, result.get('message', 'UNKNOWN ERROR') # Parse values = util.response_list(result, 'Data') return True, [emtype.PoiDetails(**a) for a in values]
python
def detail_poi(self, **kwargs): """Obtain detailed info of a given POI. Args: family (str): Family code of the POI (3 chars). lang (str): Language code (*es* or *en*). id (int): Optional, ID of the POI to query. Passing value -1 will result in information from all POIs. Returns: Status boolean and parsed response (list[PoiDetails]), or message string in case of error. """ # Endpoint parameters params = { 'language': util.language_code(kwargs.get('lang')), 'family': kwargs.get('family') } if kwargs.get('id'): params['id'] = kwargs['id'] # Request result = self.make_request('detail_poi', {}, **params) if not util.check_result(result): return False, result.get('message', 'UNKNOWN ERROR') # Parse values = util.response_list(result, 'Data') return True, [emtype.PoiDetails(**a) for a in values]
[ "def", "detail_poi", "(", "self", ",", "*", "*", "kwargs", ")", ":", "# Endpoint parameters", "params", "=", "{", "'language'", ":", "util", ".", "language_code", "(", "kwargs", ".", "get", "(", "'lang'", ")", ")", ",", "'family'", ":", "kwargs", ".", ...
Obtain detailed info of a given POI. Args: family (str): Family code of the POI (3 chars). lang (str): Language code (*es* or *en*). id (int): Optional, ID of the POI to query. Passing value -1 will result in information from all POIs. Returns: Status boolean and parsed response (list[PoiDetails]), or message string in case of error.
[ "Obtain", "detailed", "info", "of", "a", "given", "POI", "." ]
train
https://github.com/rmed/pyemtmad/blob/c21c42d0c7b50035dfed29540d7e64ab67833728/pyemtmad/api/parking.py#L87-L117
rmed/pyemtmad
pyemtmad/api/parking.py
ParkingApi.icon_description
def icon_description(self, **kwargs): """Obtain a list of elements that have an associated icon. Args: lang (str): Language code (*es* or *en*). Returns: Status boolean and parsed response (list[IconDescription]), or message string in case of error. """ # Endpoint parameters params = {'language': util.language_code(kwargs.get('lang'))} # Request result = self.make_request('icon_description', {}, **params) if not util.check_result(result): return False, result.get('message', 'UNKNOWN ERROR') # Parse values = util.response_list(result, 'Data') return True, [emtype.IconDescription(**a) for a in values]
python
def icon_description(self, **kwargs): """Obtain a list of elements that have an associated icon. Args: lang (str): Language code (*es* or *en*). Returns: Status boolean and parsed response (list[IconDescription]), or message string in case of error. """ # Endpoint parameters params = {'language': util.language_code(kwargs.get('lang'))} # Request result = self.make_request('icon_description', {}, **params) if not util.check_result(result): return False, result.get('message', 'UNKNOWN ERROR') # Parse values = util.response_list(result, 'Data') return True, [emtype.IconDescription(**a) for a in values]
[ "def", "icon_description", "(", "self", ",", "*", "*", "kwargs", ")", ":", "# Endpoint parameters", "params", "=", "{", "'language'", ":", "util", ".", "language_code", "(", "kwargs", ".", "get", "(", "'lang'", ")", ")", "}", "# Request", "result", "=", ...
Obtain a list of elements that have an associated icon. Args: lang (str): Language code (*es* or *en*). Returns: Status boolean and parsed response (list[IconDescription]), or message string in case of error.
[ "Obtain", "a", "list", "of", "elements", "that", "have", "an", "associated", "icon", "." ]
train
https://github.com/rmed/pyemtmad/blob/c21c42d0c7b50035dfed29540d7e64ab67833728/pyemtmad/api/parking.py#L119-L140
rmed/pyemtmad
pyemtmad/api/parking.py
ParkingApi.info_parking_poi
def info_parking_poi(self, **kwargs): """Obtain generic information on POIs and parkings. This returns a list of elements in a given radius from the coordinates. Args: radius (int): Radius of the search (in meters). latitude (double): Latitude in decimal degrees. longitude (double): Longitude in decimal degrees. lang (str): Language code (*es* or *en*). day (int): Day of the month in format DD. The number is automatically padded if it only has one digit. month (int): Month number in format MM. The number is automatically padded if it only has one digit. year (int): Year number in format YYYY. hour (int): Hour of the day in format hh. The number is automatically padded if it only has one digit. minute (int): Minute of the hour in format mm. The number is automatically padded if it only has one digit. poi_info (list[tuple]): List of tuples with the format ``(list[family], type, category)`` to query. Check the API documentation. min_free (list[int]): Number of free spaces to check. Must have the same length of ``poi_info``. field_codes (list[tuple]): List of tuples with the format ``(list[codes], name)``. Check the API documentation. Returns: Status boolean and parsed response (list[InfoParkingPoi]), or message string in case of error. """ # Endpoint parameters date = util.datetime_string( kwargs.get('day', 1), kwargs.get('month', 1), kwargs.get('year', 1970), kwargs.get('hour', 0), kwargs.get('minute', 0) ) family_categories = [] for element in kwargs.get('poi_info', []): family_categories.append({ 'poiCategory': { 'lstCategoryTypes': element[0] }, 'poiFamily': element[1], 'poiType': element[2] }) field_codes = [] for element in kwargs.get('field_codes', []): field_codes.append({ 'codes': { 'lstCodes': element[0] }, 'nameField': element[1] }) params = { 'TFamilyTTypeTCategory': { 'lstFamilyTypeCategory': family_categories }, 'coordinate': { 'latitude': str(kwargs.get('latitude', '0.0')), 'longitude': str(kwargs.get('longitude', '0.0')) }, 'dateTimeUse': date, 'language': util.language_code(kwargs.get('lang')), 'minimumPlacesAvailable': { 'lstminimumPlacesAvailable': kwargs.get('min_free', []) }, 'nameFieldCodes': { 'lstNameFieldCodes': field_codes }, 'radius': str(kwargs.get('radius', '0')) } # Request result = self.make_request('info_parking_poi', {}, **params) if not util.check_result(result): return False, result.get('message', 'UNKNOWN ERROR') # Parse values = util.response_list(result, 'Data') return True, [emtype.InfoParkingPoi(**a) for a in values]
python
def info_parking_poi(self, **kwargs): """Obtain generic information on POIs and parkings. This returns a list of elements in a given radius from the coordinates. Args: radius (int): Radius of the search (in meters). latitude (double): Latitude in decimal degrees. longitude (double): Longitude in decimal degrees. lang (str): Language code (*es* or *en*). day (int): Day of the month in format DD. The number is automatically padded if it only has one digit. month (int): Month number in format MM. The number is automatically padded if it only has one digit. year (int): Year number in format YYYY. hour (int): Hour of the day in format hh. The number is automatically padded if it only has one digit. minute (int): Minute of the hour in format mm. The number is automatically padded if it only has one digit. poi_info (list[tuple]): List of tuples with the format ``(list[family], type, category)`` to query. Check the API documentation. min_free (list[int]): Number of free spaces to check. Must have the same length of ``poi_info``. field_codes (list[tuple]): List of tuples with the format ``(list[codes], name)``. Check the API documentation. Returns: Status boolean and parsed response (list[InfoParkingPoi]), or message string in case of error. """ # Endpoint parameters date = util.datetime_string( kwargs.get('day', 1), kwargs.get('month', 1), kwargs.get('year', 1970), kwargs.get('hour', 0), kwargs.get('minute', 0) ) family_categories = [] for element in kwargs.get('poi_info', []): family_categories.append({ 'poiCategory': { 'lstCategoryTypes': element[0] }, 'poiFamily': element[1], 'poiType': element[2] }) field_codes = [] for element in kwargs.get('field_codes', []): field_codes.append({ 'codes': { 'lstCodes': element[0] }, 'nameField': element[1] }) params = { 'TFamilyTTypeTCategory': { 'lstFamilyTypeCategory': family_categories }, 'coordinate': { 'latitude': str(kwargs.get('latitude', '0.0')), 'longitude': str(kwargs.get('longitude', '0.0')) }, 'dateTimeUse': date, 'language': util.language_code(kwargs.get('lang')), 'minimumPlacesAvailable': { 'lstminimumPlacesAvailable': kwargs.get('min_free', []) }, 'nameFieldCodes': { 'lstNameFieldCodes': field_codes }, 'radius': str(kwargs.get('radius', '0')) } # Request result = self.make_request('info_parking_poi', {}, **params) if not util.check_result(result): return False, result.get('message', 'UNKNOWN ERROR') # Parse values = util.response_list(result, 'Data') return True, [emtype.InfoParkingPoi(**a) for a in values]
[ "def", "info_parking_poi", "(", "self", ",", "*", "*", "kwargs", ")", ":", "# Endpoint parameters", "date", "=", "util", ".", "datetime_string", "(", "kwargs", ".", "get", "(", "'day'", ",", "1", ")", ",", "kwargs", ".", "get", "(", "'month'", ",", "1"...
Obtain generic information on POIs and parkings. This returns a list of elements in a given radius from the coordinates. Args: radius (int): Radius of the search (in meters). latitude (double): Latitude in decimal degrees. longitude (double): Longitude in decimal degrees. lang (str): Language code (*es* or *en*). day (int): Day of the month in format DD. The number is automatically padded if it only has one digit. month (int): Month number in format MM. The number is automatically padded if it only has one digit. year (int): Year number in format YYYY. hour (int): Hour of the day in format hh. The number is automatically padded if it only has one digit. minute (int): Minute of the hour in format mm. The number is automatically padded if it only has one digit. poi_info (list[tuple]): List of tuples with the format ``(list[family], type, category)`` to query. Check the API documentation. min_free (list[int]): Number of free spaces to check. Must have the same length of ``poi_info``. field_codes (list[tuple]): List of tuples with the format ``(list[codes], name)``. Check the API documentation. Returns: Status boolean and parsed response (list[InfoParkingPoi]), or message string in case of error.
[ "Obtain", "generic", "information", "on", "POIs", "and", "parkings", "." ]
train
https://github.com/rmed/pyemtmad/blob/c21c42d0c7b50035dfed29540d7e64ab67833728/pyemtmad/api/parking.py#L142-L228
rmed/pyemtmad
pyemtmad/api/parking.py
ParkingApi.list_features
def list_features(self, **kwargs): """Obtain a list of parkings. Args: lang (str): Language code (*es* or *en*). Returns: Status boolean and parsed response (list[Parking]), or message string in case of error. """ # Endpoint parameters params = { 'language': util.language_code(kwargs.get('lang')), 'publicData': True } # Request result = self.make_request('list_features', {}, **params) if not util.check_result(result): return False, result.get('message', 'UNKNOWN ERROR') # Parse values = util.response_list(result, 'Data') return True, [emtype.ParkingFeature(**a) for a in values]
python
def list_features(self, **kwargs): """Obtain a list of parkings. Args: lang (str): Language code (*es* or *en*). Returns: Status boolean and parsed response (list[Parking]), or message string in case of error. """ # Endpoint parameters params = { 'language': util.language_code(kwargs.get('lang')), 'publicData': True } # Request result = self.make_request('list_features', {}, **params) if not util.check_result(result): return False, result.get('message', 'UNKNOWN ERROR') # Parse values = util.response_list(result, 'Data') return True, [emtype.ParkingFeature(**a) for a in values]
[ "def", "list_features", "(", "self", ",", "*", "*", "kwargs", ")", ":", "# Endpoint parameters", "params", "=", "{", "'language'", ":", "util", ".", "language_code", "(", "kwargs", ".", "get", "(", "'lang'", ")", ")", ",", "'publicData'", ":", "True", "}...
Obtain a list of parkings. Args: lang (str): Language code (*es* or *en*). Returns: Status boolean and parsed response (list[Parking]), or message string in case of error.
[ "Obtain", "a", "list", "of", "parkings", "." ]
train
https://github.com/rmed/pyemtmad/blob/c21c42d0c7b50035dfed29540d7e64ab67833728/pyemtmad/api/parking.py#L230-L254
rmed/pyemtmad
pyemtmad/api/parking.py
ParkingApi.list_parking
def list_parking(self, **kwargs): """Obtain a list of parkings. Args: lang (str): Language code (*es* or *en*). Returns: Status boolean and parsed response (list[Parking]), or message string in case of error. """ # Endpoint parameters url_args = {'lang': util.language_code(kwargs.get('lang'))} # Request result = self.make_request('list_parking', url_args) if not util.check_result(result): return False, result.get('message', 'UNKNOWN ERROR') # Parse values = util.response_list(result, 'Data') return True, [emtype.Parking(**a) for a in values]
python
def list_parking(self, **kwargs): """Obtain a list of parkings. Args: lang (str): Language code (*es* or *en*). Returns: Status boolean and parsed response (list[Parking]), or message string in case of error. """ # Endpoint parameters url_args = {'lang': util.language_code(kwargs.get('lang'))} # Request result = self.make_request('list_parking', url_args) if not util.check_result(result): return False, result.get('message', 'UNKNOWN ERROR') # Parse values = util.response_list(result, 'Data') return True, [emtype.Parking(**a) for a in values]
[ "def", "list_parking", "(", "self", ",", "*", "*", "kwargs", ")", ":", "# Endpoint parameters", "url_args", "=", "{", "'lang'", ":", "util", ".", "language_code", "(", "kwargs", ".", "get", "(", "'lang'", ")", ")", "}", "# Request", "result", "=", "self"...
Obtain a list of parkings. Args: lang (str): Language code (*es* or *en*). Returns: Status boolean and parsed response (list[Parking]), or message string in case of error.
[ "Obtain", "a", "list", "of", "parkings", "." ]
train
https://github.com/rmed/pyemtmad/blob/c21c42d0c7b50035dfed29540d7e64ab67833728/pyemtmad/api/parking.py#L256-L277
rmed/pyemtmad
pyemtmad/api/parking.py
ParkingApi.list_street_poi_parking
def list_street_poi_parking(self, **kwargs): """Obtain a list of addresses and POIs. This endpoint uses an address to perform the search Args: lang (str): Language code (*es* or *en*). address (str): Address in which to perform the search. Returns: Status boolean and parsed response (list[ParkingPoi]), or message string in case of error. """ # Endpoint parameters url_args = { 'language': util.language_code(kwargs.get('lang')), 'address': kwargs.get('address', '') } # Request result = self.make_request('list_street_poi_parking', url_args) if not util.check_result(result): return False, result.get('message', 'UNKNOWN ERROR') # Parse values = util.response_list(result, 'Data') return True, [emtype.ParkingPoi(**a) for a in values]
python
def list_street_poi_parking(self, **kwargs): """Obtain a list of addresses and POIs. This endpoint uses an address to perform the search Args: lang (str): Language code (*es* or *en*). address (str): Address in which to perform the search. Returns: Status boolean and parsed response (list[ParkingPoi]), or message string in case of error. """ # Endpoint parameters url_args = { 'language': util.language_code(kwargs.get('lang')), 'address': kwargs.get('address', '') } # Request result = self.make_request('list_street_poi_parking', url_args) if not util.check_result(result): return False, result.get('message', 'UNKNOWN ERROR') # Parse values = util.response_list(result, 'Data') return True, [emtype.ParkingPoi(**a) for a in values]
[ "def", "list_street_poi_parking", "(", "self", ",", "*", "*", "kwargs", ")", ":", "# Endpoint parameters", "url_args", "=", "{", "'language'", ":", "util", ".", "language_code", "(", "kwargs", ".", "get", "(", "'lang'", ")", ")", ",", "'address'", ":", "kw...
Obtain a list of addresses and POIs. This endpoint uses an address to perform the search Args: lang (str): Language code (*es* or *en*). address (str): Address in which to perform the search. Returns: Status boolean and parsed response (list[ParkingPoi]), or message string in case of error.
[ "Obtain", "a", "list", "of", "addresses", "and", "POIs", "." ]
train
https://github.com/rmed/pyemtmad/blob/c21c42d0c7b50035dfed29540d7e64ab67833728/pyemtmad/api/parking.py#L279-L306
rmed/pyemtmad
pyemtmad/api/parking.py
ParkingApi.list_types_poi
def list_types_poi(self, **kwargs): """Obtain a list of families, types and categories of POI. Args: lang (str): Language code (*es* or *en*). Returns: Status boolean and parsed response (list[ParkingPoiType]), or message string in case of error. """ # Endpoint parameters url_args = {'language': util.language_code(kwargs.get('lang'))} # Request result = self.make_request('list_poi_types', url_args) if not util.check_result(result): return False, result.get('message', 'UNKNOWN ERROR') # Parse values = util.response_list(result, 'Data') return True, [emtype.ParkingPoiType(**a) for a in values]
python
def list_types_poi(self, **kwargs): """Obtain a list of families, types and categories of POI. Args: lang (str): Language code (*es* or *en*). Returns: Status boolean and parsed response (list[ParkingPoiType]), or message string in case of error. """ # Endpoint parameters url_args = {'language': util.language_code(kwargs.get('lang'))} # Request result = self.make_request('list_poi_types', url_args) if not util.check_result(result): return False, result.get('message', 'UNKNOWN ERROR') # Parse values = util.response_list(result, 'Data') return True, [emtype.ParkingPoiType(**a) for a in values]
[ "def", "list_types_poi", "(", "self", ",", "*", "*", "kwargs", ")", ":", "# Endpoint parameters", "url_args", "=", "{", "'language'", ":", "util", ".", "language_code", "(", "kwargs", ".", "get", "(", "'lang'", ")", ")", "}", "# Request", "result", "=", ...
Obtain a list of families, types and categories of POI. Args: lang (str): Language code (*es* or *en*). Returns: Status boolean and parsed response (list[ParkingPoiType]), or message string in case of error.
[ "Obtain", "a", "list", "of", "families", "types", "and", "categories", "of", "POI", "." ]
train
https://github.com/rmed/pyemtmad/blob/c21c42d0c7b50035dfed29540d7e64ab67833728/pyemtmad/api/parking.py#L308-L329
llazzaro/analyzerdam
analyzerdam/yahooDAM.py
YahooDAM.readQuotes
def readQuotes(self, start, end): ''' read quotes from Yahoo Financial''' if self.symbol is None: LOG.debug('Symbol is None') return [] return self.__yf.getQuotes(self.symbol, start, end)
python
def readQuotes(self, start, end): ''' read quotes from Yahoo Financial''' if self.symbol is None: LOG.debug('Symbol is None') return [] return self.__yf.getQuotes(self.symbol, start, end)
[ "def", "readQuotes", "(", "self", ",", "start", ",", "end", ")", ":", "if", "self", ".", "symbol", "is", "None", ":", "LOG", ".", "debug", "(", "'Symbol is None'", ")", "return", "[", "]", "return", "self", ".", "__yf", ".", "getQuotes", "(", "self",...
read quotes from Yahoo Financial
[ "read", "quotes", "from", "Yahoo", "Financial" ]
train
https://github.com/llazzaro/analyzerdam/blob/c5bc7483dae23bd2e14bbf36147b7a43a0067bc0/analyzerdam/yahooDAM.py#L20-L26
rande/python-simple-ioc
ioc/helper.py
deepcopy
def deepcopy(value): """ The default copy.deepcopy seems to copy all objects and some are not `copy-able`. We only need to make sure the provided data is a copy per key, object does not need to be copied. """ if not isinstance(value, (dict, list, tuple)): return value if isinstance(value, dict): copy = {} for k, v in value.items(): copy[k] = deepcopy(v) if isinstance(value, tuple): copy = list(range(len(value))) for k in get_keys(list(value)): copy[k] = deepcopy(value[k]) copy = tuple(copy) if isinstance(value, list): copy = list(range(len(value))) for k in get_keys(value): copy[k] = deepcopy(value[k]) return copy
python
def deepcopy(value): """ The default copy.deepcopy seems to copy all objects and some are not `copy-able`. We only need to make sure the provided data is a copy per key, object does not need to be copied. """ if not isinstance(value, (dict, list, tuple)): return value if isinstance(value, dict): copy = {} for k, v in value.items(): copy[k] = deepcopy(v) if isinstance(value, tuple): copy = list(range(len(value))) for k in get_keys(list(value)): copy[k] = deepcopy(value[k]) copy = tuple(copy) if isinstance(value, list): copy = list(range(len(value))) for k in get_keys(value): copy[k] = deepcopy(value[k]) return copy
[ "def", "deepcopy", "(", "value", ")", ":", "if", "not", "isinstance", "(", "value", ",", "(", "dict", ",", "list", ",", "tuple", ")", ")", ":", "return", "value", "if", "isinstance", "(", "value", ",", "dict", ")", ":", "copy", "=", "{", "}", "fo...
The default copy.deepcopy seems to copy all objects and some are not `copy-able`. We only need to make sure the provided data is a copy per key, object does not need to be copied.
[ "The", "default", "copy", ".", "deepcopy", "seems", "to", "copy", "all", "objects", "and", "some", "are", "not", "copy", "-", "able", "." ]
train
https://github.com/rande/python-simple-ioc/blob/36ddf667c1213a07a53cd4cdd708d02494e5190b/ioc/helper.py#L20-L51
p3trus/slave
slave/lakeshore/ls370.py
LS370._factory_default
def _factory_default(self, confirm=False): """Resets the device to factory defaults. :param confirm: This function should not normally be used, to prevent accidental resets, a confirm value of `True` must be used. """ if confirm is True: self._write(('DFLT', Integer), 99) else: raise ValueError('Reset to factory defaults was not confirmed.')
python
def _factory_default(self, confirm=False): """Resets the device to factory defaults. :param confirm: This function should not normally be used, to prevent accidental resets, a confirm value of `True` must be used. """ if confirm is True: self._write(('DFLT', Integer), 99) else: raise ValueError('Reset to factory defaults was not confirmed.')
[ "def", "_factory_default", "(", "self", ",", "confirm", "=", "False", ")", ":", "if", "confirm", "is", "True", ":", "self", ".", "_write", "(", "(", "'DFLT'", ",", "Integer", ")", ",", "99", ")", "else", ":", "raise", "ValueError", "(", "'Reset to fact...
Resets the device to factory defaults. :param confirm: This function should not normally be used, to prevent accidental resets, a confirm value of `True` must be used.
[ "Resets", "the", "device", "to", "factory", "defaults", "." ]
train
https://github.com/p3trus/slave/blob/bdc74e73bd0f47b74a090c43aa2283c469cde3be/slave/lakeshore/ls370.py#L682-L692
twisted/mantissa
xmantissa/websession.py
usernameFromRequest
def usernameFromRequest(request): """ Take an HTTP request and return a username of the form <user>@<domain>. @type request: L{inevow.IRequest} @param request: A HTTP request @return: A C{str} """ username = request.args.get('username', [''])[0] if '@' not in username: username = '%s@%s' % ( username, request.getHeader('host').split(':')[0]) return username
python
def usernameFromRequest(request): """ Take an HTTP request and return a username of the form <user>@<domain>. @type request: L{inevow.IRequest} @param request: A HTTP request @return: A C{str} """ username = request.args.get('username', [''])[0] if '@' not in username: username = '%s@%s' % ( username, request.getHeader('host').split(':')[0]) return username
[ "def", "usernameFromRequest", "(", "request", ")", ":", "username", "=", "request", ".", "args", ".", "get", "(", "'username'", ",", "[", "''", "]", ")", "[", "0", "]", "if", "'@'", "not", "in", "username", ":", "username", "=", "'%s@%s'", "%", "(", ...
Take an HTTP request and return a username of the form <user>@<domain>. @type request: L{inevow.IRequest} @param request: A HTTP request @return: A C{str}
[ "Take", "an", "HTTP", "request", "and", "return", "a", "username", "of", "the", "form", "<user", ">", "@<domain", ">", "." ]
train
https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/websession.py#L34-L47
twisted/mantissa
xmantissa/websession.py
PersistentSessionWrapper.createSessionForKey
def createSessionForKey(self, key, user): """ Create a persistent session in the database. @type key: L{bytes} @param key: The persistent session identifier. @type user: L{bytes} @param user: The username the session will belong to. """ PersistentSession( store=self.store, sessionKey=key, authenticatedAs=user)
python
def createSessionForKey(self, key, user): """ Create a persistent session in the database. @type key: L{bytes} @param key: The persistent session identifier. @type user: L{bytes} @param user: The username the session will belong to. """ PersistentSession( store=self.store, sessionKey=key, authenticatedAs=user)
[ "def", "createSessionForKey", "(", "self", ",", "key", ",", "user", ")", ":", "PersistentSession", "(", "store", "=", "self", ".", "store", ",", "sessionKey", "=", "key", ",", "authenticatedAs", "=", "user", ")" ]
Create a persistent session in the database. @type key: L{bytes} @param key: The persistent session identifier. @type user: L{bytes} @param user: The username the session will belong to.
[ "Create", "a", "persistent", "session", "in", "the", "database", "." ]
train
https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/websession.py#L180-L193
twisted/mantissa
xmantissa/websession.py
PersistentSessionWrapper.authenticatedUserForKey
def authenticatedUserForKey(self, key): """ Find a persistent session for a user. @type key: L{bytes} @param key: The persistent session identifier. @rtype: L{bytes} or C{None} @return: The avatar ID the session belongs to, or C{None} if no such session exists. """ session = self.store.findFirst( PersistentSession, PersistentSession.sessionKey == key) if session is None: return None else: session.renew() return session.authenticatedAs
python
def authenticatedUserForKey(self, key): """ Find a persistent session for a user. @type key: L{bytes} @param key: The persistent session identifier. @rtype: L{bytes} or C{None} @return: The avatar ID the session belongs to, or C{None} if no such session exists. """ session = self.store.findFirst( PersistentSession, PersistentSession.sessionKey == key) if session is None: return None else: session.renew() return session.authenticatedAs
[ "def", "authenticatedUserForKey", "(", "self", ",", "key", ")", ":", "session", "=", "self", ".", "store", ".", "findFirst", "(", "PersistentSession", ",", "PersistentSession", ".", "sessionKey", "==", "key", ")", "if", "session", "is", "None", ":", "return"...
Find a persistent session for a user. @type key: L{bytes} @param key: The persistent session identifier. @rtype: L{bytes} or C{None} @return: The avatar ID the session belongs to, or C{None} if no such session exists.
[ "Find", "a", "persistent", "session", "for", "a", "user", "." ]
train
https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/websession.py#L196-L213
twisted/mantissa
xmantissa/websession.py
PersistentSessionWrapper.removeSessionWithKey
def removeSessionWithKey(self, key): """ Remove a persistent session, if it exists. @type key: L{bytes} @param key: The persistent session identifier. """ self.store.query( PersistentSession, PersistentSession.sessionKey == key).deleteFromStore()
python
def removeSessionWithKey(self, key): """ Remove a persistent session, if it exists. @type key: L{bytes} @param key: The persistent session identifier. """ self.store.query( PersistentSession, PersistentSession.sessionKey == key).deleteFromStore()
[ "def", "removeSessionWithKey", "(", "self", ",", "key", ")", ":", "self", ".", "store", ".", "query", "(", "PersistentSession", ",", "PersistentSession", ".", "sessionKey", "==", "key", ")", ".", "deleteFromStore", "(", ")" ]
Remove a persistent session, if it exists. @type key: L{bytes} @param key: The persistent session identifier.
[ "Remove", "a", "persistent", "session", "if", "it", "exists", "." ]
train
https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/websession.py#L216-L225
twisted/mantissa
xmantissa/websession.py
PersistentSessionWrapper._cleanSessions
def _cleanSessions(self): """ Clean expired sesisons. """ tooOld = extime.Time() - timedelta(seconds=PERSISTENT_SESSION_LIFETIME) self.store.query( PersistentSession, PersistentSession.lastUsed < tooOld).deleteFromStore() self._lastClean = self._clock.seconds()
python
def _cleanSessions(self): """ Clean expired sesisons. """ tooOld = extime.Time() - timedelta(seconds=PERSISTENT_SESSION_LIFETIME) self.store.query( PersistentSession, PersistentSession.lastUsed < tooOld).deleteFromStore() self._lastClean = self._clock.seconds()
[ "def", "_cleanSessions", "(", "self", ")", ":", "tooOld", "=", "extime", ".", "Time", "(", ")", "-", "timedelta", "(", "seconds", "=", "PERSISTENT_SESSION_LIFETIME", ")", "self", ".", "store", ".", "query", "(", "PersistentSession", ",", "PersistentSession", ...
Clean expired sesisons.
[ "Clean", "expired", "sesisons", "." ]
train
https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/websession.py#L228-L236
twisted/mantissa
xmantissa/websession.py
PersistentSessionWrapper._maybeCleanSessions
def _maybeCleanSessions(self): """ Clean expired sessions if it's been long enough since the last clean. """ sinceLast = self._clock.seconds() - self._lastClean if sinceLast > self.sessionCleanFrequency: self._cleanSessions()
python
def _maybeCleanSessions(self): """ Clean expired sessions if it's been long enough since the last clean. """ sinceLast = self._clock.seconds() - self._lastClean if sinceLast > self.sessionCleanFrequency: self._cleanSessions()
[ "def", "_maybeCleanSessions", "(", "self", ")", ":", "sinceLast", "=", "self", ".", "_clock", ".", "seconds", "(", ")", "-", "self", ".", "_lastClean", "if", "sinceLast", ">", "self", ".", "sessionCleanFrequency", ":", "self", ".", "_cleanSessions", "(", "...
Clean expired sessions if it's been long enough since the last clean.
[ "Clean", "expired", "sessions", "if", "it", "s", "been", "long", "enough", "since", "the", "last", "clean", "." ]
train
https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/websession.py#L239-L245
twisted/mantissa
xmantissa/websession.py
PersistentSessionWrapper.cookieDomainForRequest
def cookieDomainForRequest(self, request): """ Pick a domain to use when setting cookies. @type request: L{nevow.inevow.IRequest} @param request: Request to determine cookie domain for @rtype: C{str} or C{None} @return: Domain name to use when setting cookies, or C{None} to indicate that only the domain in the request should be used """ host = request.getHeader('host') if host is None: # This is a malformed request that we cannot possibly handle # safely, fall back to the default behaviour. return None host = host.split(':')[0] for domain in self._domains: suffix = "." + domain if host == domain: # The request is for a domain which is directly recognized. if self._enableSubdomains: # Subdomains are enabled, so the suffix is returned to # enable the cookie for this domain and all its subdomains. return suffix # Subdomains are not enabled, so None is returned to allow the # default restriction, which will enable this cookie only for # the domain in the request, to apply. return None if self._enableSubdomains and host.endswith(suffix): # The request is for a subdomain of a directly recognized # domain and subdomains are enabled. Drop the unrecognized # subdomain portion and return the suffix to enable the cookie # for this domain and all its subdomains. return suffix if self._enableSubdomains: # No directly recognized domain matched the request. If subdomains # are enabled, prefix the request domain with "." to make the # cookie valid for that domain and all its subdomains. This # probably isn't extremely useful. Perhaps it shouldn't work this # way. return "." + host # Subdomains are disabled and the domain from the request was not # recognized. Return None to get the default behavior. return None
python
def cookieDomainForRequest(self, request): """ Pick a domain to use when setting cookies. @type request: L{nevow.inevow.IRequest} @param request: Request to determine cookie domain for @rtype: C{str} or C{None} @return: Domain name to use when setting cookies, or C{None} to indicate that only the domain in the request should be used """ host = request.getHeader('host') if host is None: # This is a malformed request that we cannot possibly handle # safely, fall back to the default behaviour. return None host = host.split(':')[0] for domain in self._domains: suffix = "." + domain if host == domain: # The request is for a domain which is directly recognized. if self._enableSubdomains: # Subdomains are enabled, so the suffix is returned to # enable the cookie for this domain and all its subdomains. return suffix # Subdomains are not enabled, so None is returned to allow the # default restriction, which will enable this cookie only for # the domain in the request, to apply. return None if self._enableSubdomains and host.endswith(suffix): # The request is for a subdomain of a directly recognized # domain and subdomains are enabled. Drop the unrecognized # subdomain portion and return the suffix to enable the cookie # for this domain and all its subdomains. return suffix if self._enableSubdomains: # No directly recognized domain matched the request. If subdomains # are enabled, prefix the request domain with "." to make the # cookie valid for that domain and all its subdomains. This # probably isn't extremely useful. Perhaps it shouldn't work this # way. return "." + host # Subdomains are disabled and the domain from the request was not # recognized. Return None to get the default behavior. return None
[ "def", "cookieDomainForRequest", "(", "self", ",", "request", ")", ":", "host", "=", "request", ".", "getHeader", "(", "'host'", ")", "if", "host", "is", "None", ":", "# This is a malformed request that we cannot possibly handle", "# safely, fall back to the default behav...
Pick a domain to use when setting cookies. @type request: L{nevow.inevow.IRequest} @param request: Request to determine cookie domain for @rtype: C{str} or C{None} @return: Domain name to use when setting cookies, or C{None} to indicate that only the domain in the request should be used
[ "Pick", "a", "domain", "to", "use", "when", "setting", "cookies", "." ]
train
https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/websession.py#L248-L297
twisted/mantissa
xmantissa/websession.py
PersistentSessionWrapper.savorSessionCookie
def savorSessionCookie(self, request): """ Make the session cookie last as long as the persistent session. @type request: L{nevow.inevow.IRequest} @param request: The HTTP request object for the guard login URL. """ cookieValue = request.getSession().uid request.addCookie( self.cookieKey, cookieValue, path='/', max_age=PERSISTENT_SESSION_LIFETIME, domain=self.cookieDomainForRequest(request))
python
def savorSessionCookie(self, request): """ Make the session cookie last as long as the persistent session. @type request: L{nevow.inevow.IRequest} @param request: The HTTP request object for the guard login URL. """ cookieValue = request.getSession().uid request.addCookie( self.cookieKey, cookieValue, path='/', max_age=PERSISTENT_SESSION_LIFETIME, domain=self.cookieDomainForRequest(request))
[ "def", "savorSessionCookie", "(", "self", ",", "request", ")", ":", "cookieValue", "=", "request", ".", "getSession", "(", ")", ".", "uid", "request", ".", "addCookie", "(", "self", ".", "cookieKey", ",", "cookieValue", ",", "path", "=", "'/'", ",", "max...
Make the session cookie last as long as the persistent session. @type request: L{nevow.inevow.IRequest} @param request: The HTTP request object for the guard login URL.
[ "Make", "the", "session", "cookie", "last", "as", "long", "as", "the", "persistent", "session", "." ]
train
https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/websession.py#L300-L311
twisted/mantissa
xmantissa/websession.py
PersistentSessionWrapper.login
def login(self, request, session, creds, segments): """ Called to check the credentials of a user. Here we extend guard's implementation to preauthenticate users if they have a valid persistent session. @type request: L{nevow.inevow.IRequest} @param request: The HTTP request being handled. @type session: L{nevow.guard.GuardSession} @param session: The user's current session. @type creds: L{twisted.cred.credentials.ICredentials} @param creds: The credentials the user presented. @type segments: L{tuple} @param segments: The remaining segments of the URL. @return: A deferred firing with the user's avatar. """ self._maybeCleanSessions() if isinstance(creds, credentials.Anonymous): preauth = self.authenticatedUserForKey(session.uid) if preauth is not None: self.savorSessionCookie(request) creds = userbase.Preauthenticated(preauth) def cbLoginSuccess(input): """ User authenticated successfully. Create the persistent session, and associate it with the username. (XXX it doesn't work like this now) """ user = request.args.get('username') if user is not None: # create a database session and associate it with this user cookieValue = session.uid if request.args.get('rememberMe'): self.createSessionForKey(cookieValue, creds.username) self.savorSessionCookie(request) return input return ( guard.SessionWrapper.login( self, request, session, creds, segments) .addCallback(cbLoginSuccess))
python
def login(self, request, session, creds, segments): """ Called to check the credentials of a user. Here we extend guard's implementation to preauthenticate users if they have a valid persistent session. @type request: L{nevow.inevow.IRequest} @param request: The HTTP request being handled. @type session: L{nevow.guard.GuardSession} @param session: The user's current session. @type creds: L{twisted.cred.credentials.ICredentials} @param creds: The credentials the user presented. @type segments: L{tuple} @param segments: The remaining segments of the URL. @return: A deferred firing with the user's avatar. """ self._maybeCleanSessions() if isinstance(creds, credentials.Anonymous): preauth = self.authenticatedUserForKey(session.uid) if preauth is not None: self.savorSessionCookie(request) creds = userbase.Preauthenticated(preauth) def cbLoginSuccess(input): """ User authenticated successfully. Create the persistent session, and associate it with the username. (XXX it doesn't work like this now) """ user = request.args.get('username') if user is not None: # create a database session and associate it with this user cookieValue = session.uid if request.args.get('rememberMe'): self.createSessionForKey(cookieValue, creds.username) self.savorSessionCookie(request) return input return ( guard.SessionWrapper.login( self, request, session, creds, segments) .addCallback(cbLoginSuccess))
[ "def", "login", "(", "self", ",", "request", ",", "session", ",", "creds", ",", "segments", ")", ":", "self", ".", "_maybeCleanSessions", "(", ")", "if", "isinstance", "(", "creds", ",", "credentials", ".", "Anonymous", ")", ":", "preauth", "=", "self", ...
Called to check the credentials of a user. Here we extend guard's implementation to preauthenticate users if they have a valid persistent session. @type request: L{nevow.inevow.IRequest} @param request: The HTTP request being handled. @type session: L{nevow.guard.GuardSession} @param session: The user's current session. @type creds: L{twisted.cred.credentials.ICredentials} @param creds: The credentials the user presented. @type segments: L{tuple} @param segments: The remaining segments of the URL. @return: A deferred firing with the user's avatar.
[ "Called", "to", "check", "the", "credentials", "of", "a", "user", "." ]
train
https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/websession.py#L314-L362
twisted/mantissa
xmantissa/websession.py
PersistentSessionWrapper.explicitLogout
def explicitLogout(self, session): """ Handle a user-requested logout. Here we override guard's behaviour for the logout action to delete the persistent session. In this case the user has explicitly requested a logout, so the persistent session must be deleted to require the user to log in on the next request. @type session: L{nevow.guard.GuardSession} @param session: The session of the user logging out. """ guard.SessionWrapper.explicitLogout(self, session) self.removeSessionWithKey(session.uid)
python
def explicitLogout(self, session): """ Handle a user-requested logout. Here we override guard's behaviour for the logout action to delete the persistent session. In this case the user has explicitly requested a logout, so the persistent session must be deleted to require the user to log in on the next request. @type session: L{nevow.guard.GuardSession} @param session: The session of the user logging out. """ guard.SessionWrapper.explicitLogout(self, session) self.removeSessionWithKey(session.uid)
[ "def", "explicitLogout", "(", "self", ",", "session", ")", ":", "guard", ".", "SessionWrapper", ".", "explicitLogout", "(", "self", ",", "session", ")", "self", ".", "removeSessionWithKey", "(", "session", ".", "uid", ")" ]
Handle a user-requested logout. Here we override guard's behaviour for the logout action to delete the persistent session. In this case the user has explicitly requested a logout, so the persistent session must be deleted to require the user to log in on the next request. @type session: L{nevow.guard.GuardSession} @param session: The session of the user logging out.
[ "Handle", "a", "user", "-", "requested", "logout", "." ]
train
https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/websession.py#L365-L378
twisted/mantissa
xmantissa/websession.py
PersistentSessionWrapper.getCredentials
def getCredentials(self, request): """ Derive credentials from an HTTP request. Override SessionWrapper.getCredentials to add the Host: header to the credentials. This will make web-based virtual hosting work. @type request: L{nevow.inevow.IRequest} @param request: The request being handled. @rtype: L{twisted.cred.credentials.1ICredentials} @return: Credentials derived from the HTTP request. """ username = usernameFromRequest(request) password = request.args.get('password', [''])[0] return credentials.UsernamePassword(username, password)
python
def getCredentials(self, request): """ Derive credentials from an HTTP request. Override SessionWrapper.getCredentials to add the Host: header to the credentials. This will make web-based virtual hosting work. @type request: L{nevow.inevow.IRequest} @param request: The request being handled. @rtype: L{twisted.cred.credentials.1ICredentials} @return: Credentials derived from the HTTP request. """ username = usernameFromRequest(request) password = request.args.get('password', [''])[0] return credentials.UsernamePassword(username, password)
[ "def", "getCredentials", "(", "self", ",", "request", ")", ":", "username", "=", "usernameFromRequest", "(", "request", ")", "password", "=", "request", ".", "args", ".", "get", "(", "'password'", ",", "[", "''", "]", ")", "[", "0", "]", "return", "cre...
Derive credentials from an HTTP request. Override SessionWrapper.getCredentials to add the Host: header to the credentials. This will make web-based virtual hosting work. @type request: L{nevow.inevow.IRequest} @param request: The request being handled. @rtype: L{twisted.cred.credentials.1ICredentials} @return: Credentials derived from the HTTP request.
[ "Derive", "credentials", "from", "an", "HTTP", "request", "." ]
train
https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/websession.py#L381-L396
twisted/mantissa
xmantissa/webnav.py
setTabURLs
def setTabURLs(tabs, webTranslator): """ Sets the C{linkURL} attribute on each L{Tab} instance in C{tabs} that does not already have it set @param tabs: sequence of L{Tab} instances @param webTranslator: L{xmantissa.ixmantissa.IWebTranslator} implementor @return: None """ for tab in tabs: if not tab.linkURL: tab.linkURL = webTranslator.linkTo(tab.storeID) setTabURLs(tab.children, webTranslator)
python
def setTabURLs(tabs, webTranslator): """ Sets the C{linkURL} attribute on each L{Tab} instance in C{tabs} that does not already have it set @param tabs: sequence of L{Tab} instances @param webTranslator: L{xmantissa.ixmantissa.IWebTranslator} implementor @return: None """ for tab in tabs: if not tab.linkURL: tab.linkURL = webTranslator.linkTo(tab.storeID) setTabURLs(tab.children, webTranslator)
[ "def", "setTabURLs", "(", "tabs", ",", "webTranslator", ")", ":", "for", "tab", "in", "tabs", ":", "if", "not", "tab", ".", "linkURL", ":", "tab", ".", "linkURL", "=", "webTranslator", ".", "linkTo", "(", "tab", ".", "storeID", ")", "setTabURLs", "(", ...
Sets the C{linkURL} attribute on each L{Tab} instance in C{tabs} that does not already have it set @param tabs: sequence of L{Tab} instances @param webTranslator: L{xmantissa.ixmantissa.IWebTranslator} implementor @return: None
[ "Sets", "the", "C", "{", "linkURL", "}", "attribute", "on", "each", "L", "{", "Tab", "}", "instance", "in", "C", "{", "tabs", "}", "that", "does", "not", "already", "have", "it", "set" ]
train
https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/webnav.py#L147-L162
twisted/mantissa
xmantissa/webnav.py
getSelectedTab
def getSelectedTab(tabs, forURL): """ Returns the tab that should be selected when the current resource lives at C{forURL}. Call me after L{setTabURLs} @param tabs: sequence of L{Tab} instances @param forURL: L{nevow.url.URL} @return: L{Tab} instance """ flatTabs = [] def flatten(tabs): for t in tabs: flatTabs.append(t) flatten(t.children) flatten(tabs) forURL = '/' + forURL.path for t in flatTabs: if forURL == t.linkURL: return t flatTabs.sort(key=lambda t: len(t.linkURL), reverse=True) for t in flatTabs: if not t.linkURL.endswith('/'): linkURL = t.linkURL + '/' else: linkURL = t.linkURL if forURL.startswith(linkURL): return t
python
def getSelectedTab(tabs, forURL): """ Returns the tab that should be selected when the current resource lives at C{forURL}. Call me after L{setTabURLs} @param tabs: sequence of L{Tab} instances @param forURL: L{nevow.url.URL} @return: L{Tab} instance """ flatTabs = [] def flatten(tabs): for t in tabs: flatTabs.append(t) flatten(t.children) flatten(tabs) forURL = '/' + forURL.path for t in flatTabs: if forURL == t.linkURL: return t flatTabs.sort(key=lambda t: len(t.linkURL), reverse=True) for t in flatTabs: if not t.linkURL.endswith('/'): linkURL = t.linkURL + '/' else: linkURL = t.linkURL if forURL.startswith(linkURL): return t
[ "def", "getSelectedTab", "(", "tabs", ",", "forURL", ")", ":", "flatTabs", "=", "[", "]", "def", "flatten", "(", "tabs", ")", ":", "for", "t", "in", "tabs", ":", "flatTabs", ".", "append", "(", "t", ")", "flatten", "(", "t", ".", "children", ")", ...
Returns the tab that should be selected when the current resource lives at C{forURL}. Call me after L{setTabURLs} @param tabs: sequence of L{Tab} instances @param forURL: L{nevow.url.URL} @return: L{Tab} instance
[ "Returns", "the", "tab", "that", "should", "be", "selected", "when", "the", "current", "resource", "lives", "at", "C", "{", "forURL", "}", ".", "Call", "me", "after", "L", "{", "setTabURLs", "}" ]
train
https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/webnav.py#L164-L198
twisted/mantissa
xmantissa/webnav.py
startMenu
def startMenu(translator, navigation, tag): """ Drop-down menu-style navigation view. For each primary navigation element available, a copy of the I{tab} pattern will be loaded from the tag. It will have its I{href} slot filled with the URL for that navigation item. It will have its I{name} slot filled with the user-visible name of the navigation element. It will have its I{kids} slot filled with a list of secondary navigation for that element. For each secondary navigation element available beneath each primary navigation element, a copy of the I{subtabs} pattern will be loaded from the tag. It will have its I{kids} slot filled with a self-similar structure. @type translator: L{IWebTranslator} provider @type navigation: L{list} of L{Tab} @rtype: {nevow.stan.Tag} """ setTabURLs(navigation, translator) getp = IQ(tag).onePattern def fillSlots(tabs): for tab in tabs: if tab.children: kids = getp('subtabs').fillSlots('kids', fillSlots(tab.children)) else: kids = '' yield dictFillSlots(getp('tab'), dict(href=tab.linkURL, name=tab.name, kids=kids)) return tag.fillSlots('tabs', fillSlots(navigation))
python
def startMenu(translator, navigation, tag): """ Drop-down menu-style navigation view. For each primary navigation element available, a copy of the I{tab} pattern will be loaded from the tag. It will have its I{href} slot filled with the URL for that navigation item. It will have its I{name} slot filled with the user-visible name of the navigation element. It will have its I{kids} slot filled with a list of secondary navigation for that element. For each secondary navigation element available beneath each primary navigation element, a copy of the I{subtabs} pattern will be loaded from the tag. It will have its I{kids} slot filled with a self-similar structure. @type translator: L{IWebTranslator} provider @type navigation: L{list} of L{Tab} @rtype: {nevow.stan.Tag} """ setTabURLs(navigation, translator) getp = IQ(tag).onePattern def fillSlots(tabs): for tab in tabs: if tab.children: kids = getp('subtabs').fillSlots('kids', fillSlots(tab.children)) else: kids = '' yield dictFillSlots(getp('tab'), dict(href=tab.linkURL, name=tab.name, kids=kids)) return tag.fillSlots('tabs', fillSlots(navigation))
[ "def", "startMenu", "(", "translator", ",", "navigation", ",", "tag", ")", ":", "setTabURLs", "(", "navigation", ",", "translator", ")", "getp", "=", "IQ", "(", "tag", ")", ".", "onePattern", "def", "fillSlots", "(", "tabs", ")", ":", "for", "tab", "in...
Drop-down menu-style navigation view. For each primary navigation element available, a copy of the I{tab} pattern will be loaded from the tag. It will have its I{href} slot filled with the URL for that navigation item. It will have its I{name} slot filled with the user-visible name of the navigation element. It will have its I{kids} slot filled with a list of secondary navigation for that element. For each secondary navigation element available beneath each primary navigation element, a copy of the I{subtabs} pattern will be loaded from the tag. It will have its I{kids} slot filled with a self-similar structure. @type translator: L{IWebTranslator} provider @type navigation: L{list} of L{Tab} @rtype: {nevow.stan.Tag}
[ "Drop", "-", "down", "menu", "-", "style", "navigation", "view", "." ]
train
https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/webnav.py#L202-L236
twisted/mantissa
xmantissa/webnav.py
applicationNavigation
def applicationNavigation(ctx, translator, navigation): """ Horizontal, primary-only navigation view. For the navigation element currently being viewed, copies of the I{selected-app-tab} and I{selected-tab-contents} patterns will be loaded from the tag. For all other navigation elements, copies of the I{app-tab} and I{tab-contents} patterns will be loaded. For either case, the former pattern will have its I{name} slot filled with the name of the navigation element and its I{tab-contents} slot filled with the latter pattern. The latter pattern will have its I{href} slot filled with a link to the corresponding navigation element. The I{tabs} slot on the tag will be filled with all the I{selected-app-tab} or I{app-tab} pattern copies. @type ctx: L{nevow.context.WebContext} @type translator: L{IWebTranslator} provider @type navigation: L{list} of L{Tab} @rtype: {nevow.stan.Tag} """ setTabURLs(navigation, translator) selectedTab = getSelectedTab(navigation, url.URL.fromContext(ctx)) getp = IQ(ctx.tag).onePattern tabs = [] for tab in navigation: if tab == selectedTab or selectedTab in tab.children: p = 'selected-app-tab' contentp = 'selected-tab-contents' else: p = 'app-tab' contentp = 'tab-contents' childTabs = [] for subtab in tab.children: try: subtabp = getp("subtab") except NodeNotFound: continue childTabs.append( dictFillSlots(subtabp, { 'name': subtab.name, 'href': subtab.linkURL, 'tab-contents': getp("subtab-contents") })) tabs.append(dictFillSlots( getp(p), {'name': tab.name, 'tab-contents': getp(contentp).fillSlots( 'href', tab.linkURL), 'subtabs': childTabs})) ctx.tag.fillSlots('tabs', tabs) return ctx.tag
python
def applicationNavigation(ctx, translator, navigation): """ Horizontal, primary-only navigation view. For the navigation element currently being viewed, copies of the I{selected-app-tab} and I{selected-tab-contents} patterns will be loaded from the tag. For all other navigation elements, copies of the I{app-tab} and I{tab-contents} patterns will be loaded. For either case, the former pattern will have its I{name} slot filled with the name of the navigation element and its I{tab-contents} slot filled with the latter pattern. The latter pattern will have its I{href} slot filled with a link to the corresponding navigation element. The I{tabs} slot on the tag will be filled with all the I{selected-app-tab} or I{app-tab} pattern copies. @type ctx: L{nevow.context.WebContext} @type translator: L{IWebTranslator} provider @type navigation: L{list} of L{Tab} @rtype: {nevow.stan.Tag} """ setTabURLs(navigation, translator) selectedTab = getSelectedTab(navigation, url.URL.fromContext(ctx)) getp = IQ(ctx.tag).onePattern tabs = [] for tab in navigation: if tab == selectedTab or selectedTab in tab.children: p = 'selected-app-tab' contentp = 'selected-tab-contents' else: p = 'app-tab' contentp = 'tab-contents' childTabs = [] for subtab in tab.children: try: subtabp = getp("subtab") except NodeNotFound: continue childTabs.append( dictFillSlots(subtabp, { 'name': subtab.name, 'href': subtab.linkURL, 'tab-contents': getp("subtab-contents") })) tabs.append(dictFillSlots( getp(p), {'name': tab.name, 'tab-contents': getp(contentp).fillSlots( 'href', tab.linkURL), 'subtabs': childTabs})) ctx.tag.fillSlots('tabs', tabs) return ctx.tag
[ "def", "applicationNavigation", "(", "ctx", ",", "translator", ",", "navigation", ")", ":", "setTabURLs", "(", "navigation", ",", "translator", ")", "selectedTab", "=", "getSelectedTab", "(", "navigation", ",", "url", ".", "URL", ".", "fromContext", "(", "ctx"...
Horizontal, primary-only navigation view. For the navigation element currently being viewed, copies of the I{selected-app-tab} and I{selected-tab-contents} patterns will be loaded from the tag. For all other navigation elements, copies of the I{app-tab} and I{tab-contents} patterns will be loaded. For either case, the former pattern will have its I{name} slot filled with the name of the navigation element and its I{tab-contents} slot filled with the latter pattern. The latter pattern will have its I{href} slot filled with a link to the corresponding navigation element. The I{tabs} slot on the tag will be filled with all the I{selected-app-tab} or I{app-tab} pattern copies. @type ctx: L{nevow.context.WebContext} @type translator: L{IWebTranslator} provider @type navigation: L{list} of L{Tab} @rtype: {nevow.stan.Tag}
[ "Horizontal", "primary", "-", "only", "navigation", "view", "." ]
train
https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/webnav.py#L251-L310
twisted/mantissa
xmantissa/webnav.py
Tab.pathFromItem
def pathFromItem(self, item, avatar): """ @param item: A thing that we linked to, and such. @return: a list of [child, grandchild, great-grandchild, ...] that indicates a path from me to the navigation for that item, or [] if there is no path from here to there. """ for subnav in self.children: subpath = subnav.pathFromItem(item, avatar) if subpath: subpath.insert(0, self) return subpath else: myItem = self.loadForAvatar(avatar) if myItem is item: return [self] return []
python
def pathFromItem(self, item, avatar): """ @param item: A thing that we linked to, and such. @return: a list of [child, grandchild, great-grandchild, ...] that indicates a path from me to the navigation for that item, or [] if there is no path from here to there. """ for subnav in self.children: subpath = subnav.pathFromItem(item, avatar) if subpath: subpath.insert(0, self) return subpath else: myItem = self.loadForAvatar(avatar) if myItem is item: return [self] return []
[ "def", "pathFromItem", "(", "self", ",", "item", ",", "avatar", ")", ":", "for", "subnav", "in", "self", ".", "children", ":", "subpath", "=", "subnav", ".", "pathFromItem", "(", "item", ",", "avatar", ")", "if", "subpath", ":", "subpath", ".", "insert...
@param item: A thing that we linked to, and such. @return: a list of [child, grandchild, great-grandchild, ...] that indicates a path from me to the navigation for that item, or [] if there is no path from here to there.
[ "@param", "item", ":", "A", "thing", "that", "we", "linked", "to", "and", "such", "." ]
train
https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/webnav.py#L83-L100
twisted/mantissa
xmantissa/terminal.py
_generate
def _generate(): """ Generate a new SSH key pair. """ privateKey = rsa.generate_private_key( public_exponent=65537, key_size=4096, backend=default_backend()) return Key(privateKey).toString('openssh')
python
def _generate(): """ Generate a new SSH key pair. """ privateKey = rsa.generate_private_key( public_exponent=65537, key_size=4096, backend=default_backend()) return Key(privateKey).toString('openssh')
[ "def", "_generate", "(", ")", ":", "privateKey", "=", "rsa", ".", "generate_private_key", "(", "public_exponent", "=", "65537", ",", "key_size", "=", "4096", ",", "backend", "=", "default_backend", "(", ")", ")", "return", "Key", "(", "privateKey", ")", "....
Generate a new SSH key pair.
[ "Generate", "a", "new", "SSH", "key", "pair", "." ]
train
https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/terminal.py#L43-L51
twisted/mantissa
xmantissa/terminal.py
SecureShellConfiguration.getFactory
def getFactory(self): """ Create an L{SSHFactory} which allows access to Mantissa accounts. """ privateKey = Key.fromString(data=self.hostKey) public = privateKey.public() factory = SSHFactory() factory.publicKeys = {'ssh-rsa': public} factory.privateKeys = {'ssh-rsa': privateKey} factory.portal = Portal( IRealm(self.store), [ICredentialsChecker(self.store)]) return factory
python
def getFactory(self): """ Create an L{SSHFactory} which allows access to Mantissa accounts. """ privateKey = Key.fromString(data=self.hostKey) public = privateKey.public() factory = SSHFactory() factory.publicKeys = {'ssh-rsa': public} factory.privateKeys = {'ssh-rsa': privateKey} factory.portal = Portal( IRealm(self.store), [ICredentialsChecker(self.store)]) return factory
[ "def", "getFactory", "(", "self", ")", ":", "privateKey", "=", "Key", ".", "fromString", "(", "data", "=", "self", ".", "hostKey", ")", "public", "=", "privateKey", ".", "public", "(", ")", "factory", "=", "SSHFactory", "(", ")", "factory", ".", "publi...
Create an L{SSHFactory} which allows access to Mantissa accounts.
[ "Create", "an", "L", "{", "SSHFactory", "}", "which", "allows", "access", "to", "Mantissa", "accounts", "." ]
train
https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/terminal.py#L104-L115
twisted/mantissa
xmantissa/terminal.py
ShellServer._draw
def _draw(self): """ Call the drawing API for the main menu widget with the current known terminal size and the terminal. """ self._window.draw(self._width, self._height, self.terminal)
python
def _draw(self): """ Call the drawing API for the main menu widget with the current known terminal size and the terminal. """ self._window.draw(self._width, self._height, self.terminal)
[ "def", "_draw", "(", "self", ")", ":", "self", ".", "_window", ".", "draw", "(", "self", ".", "_width", ",", "self", ".", "_height", ",", "self", ".", "terminal", ")" ]
Call the drawing API for the main menu widget with the current known terminal size and the terminal.
[ "Call", "the", "drawing", "API", "for", "the", "main", "menu", "widget", "with", "the", "current", "known", "terminal", "size", "and", "the", "terminal", "." ]
train
https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/terminal.py#L181-L186
twisted/mantissa
xmantissa/terminal.py
ShellServer.reactivate
def reactivate(self): """ Called when a sub-protocol is finished. This disconnects the sub-protocol and redraws the main menu UI. """ self._protocol.connectionLost(None) self._protocol = None self.terminal.reset() self._window.filthy() self._window.repaint()
python
def reactivate(self): """ Called when a sub-protocol is finished. This disconnects the sub-protocol and redraws the main menu UI. """ self._protocol.connectionLost(None) self._protocol = None self.terminal.reset() self._window.filthy() self._window.repaint()
[ "def", "reactivate", "(", "self", ")", ":", "self", ".", "_protocol", ".", "connectionLost", "(", "None", ")", "self", ".", "_protocol", "=", "None", "self", ".", "terminal", ".", "reset", "(", ")", "self", ".", "_window", ".", "filthy", "(", ")", "s...
Called when a sub-protocol is finished. This disconnects the sub-protocol and redraws the main menu UI.
[ "Called", "when", "a", "sub", "-", "protocol", "is", "finished", ".", "This", "disconnects", "the", "sub", "-", "protocol", "and", "redraws", "the", "main", "menu", "UI", "." ]
train
https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/terminal.py#L220-L229
twisted/mantissa
xmantissa/terminal.py
ShellServer.switchTo
def switchTo(self, app): """ Use the given L{ITerminalServerFactory} to create a new L{ITerminalProtocol} and connect it to C{self.terminal} (such that it cannot actually disconnect, but can do most anything else). Control of the terminal is delegated to it until it gives up that control by disconnecting itself from the terminal. @type app: L{ITerminalServerFactory} provider @param app: The factory which will be used to create a protocol instance. """ viewer = _AuthenticatedShellViewer(list(getAccountNames(self._store))) self._protocol = app.buildTerminalProtocol(viewer) self._protocol.makeConnection(_ReturnToMenuWrapper(self, self.terminal))
python
def switchTo(self, app): """ Use the given L{ITerminalServerFactory} to create a new L{ITerminalProtocol} and connect it to C{self.terminal} (such that it cannot actually disconnect, but can do most anything else). Control of the terminal is delegated to it until it gives up that control by disconnecting itself from the terminal. @type app: L{ITerminalServerFactory} provider @param app: The factory which will be used to create a protocol instance. """ viewer = _AuthenticatedShellViewer(list(getAccountNames(self._store))) self._protocol = app.buildTerminalProtocol(viewer) self._protocol.makeConnection(_ReturnToMenuWrapper(self, self.terminal))
[ "def", "switchTo", "(", "self", ",", "app", ")", ":", "viewer", "=", "_AuthenticatedShellViewer", "(", "list", "(", "getAccountNames", "(", "self", ".", "_store", ")", ")", ")", "self", ".", "_protocol", "=", "app", ".", "buildTerminalProtocol", "(", "view...
Use the given L{ITerminalServerFactory} to create a new L{ITerminalProtocol} and connect it to C{self.terminal} (such that it cannot actually disconnect, but can do most anything else). Control of the terminal is delegated to it until it gives up that control by disconnecting itself from the terminal. @type app: L{ITerminalServerFactory} provider @param app: The factory which will be used to create a protocol instance.
[ "Use", "the", "given", "L", "{", "ITerminalServerFactory", "}", "to", "create", "a", "new", "L", "{", "ITerminalProtocol", "}", "and", "connect", "it", "to", "C", "{", "self", ".", "terminal", "}", "(", "such", "that", "it", "cannot", "actually", "discon...
train
https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/terminal.py#L232-L246
twisted/mantissa
xmantissa/terminal.py
ShellServer.keystrokeReceived
def keystrokeReceived(self, keyID, modifier): """ Forward input events to the application-supplied protocol if one is currently active, otherwise forward them to the main menu UI. """ if self._protocol is not None: self._protocol.keystrokeReceived(keyID, modifier) else: self._window.keystrokeReceived(keyID, modifier)
python
def keystrokeReceived(self, keyID, modifier): """ Forward input events to the application-supplied protocol if one is currently active, otherwise forward them to the main menu UI. """ if self._protocol is not None: self._protocol.keystrokeReceived(keyID, modifier) else: self._window.keystrokeReceived(keyID, modifier)
[ "def", "keystrokeReceived", "(", "self", ",", "keyID", ",", "modifier", ")", ":", "if", "self", ".", "_protocol", "is", "not", "None", ":", "self", ".", "_protocol", ".", "keystrokeReceived", "(", "keyID", ",", "modifier", ")", "else", ":", "self", ".", ...
Forward input events to the application-supplied protocol if one is currently active, otherwise forward them to the main menu UI.
[ "Forward", "input", "events", "to", "the", "application", "-", "supplied", "protocol", "if", "one", "is", "currently", "active", "otherwise", "forward", "them", "to", "the", "main", "menu", "UI", "." ]
train
https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/terminal.py#L249-L257
twisted/mantissa
xmantissa/terminal.py
ShellAccount.indirect
def indirect(self, interface): """ Create an L{IConchUser} avatar which will use L{ShellServer} to interact with the connection. """ if interface is IConchUser: componentized = Componentized() user = _BetterTerminalUser(componentized, None) session = _BetterTerminalSession(componentized) session.transportFactory = TerminalSessionTransport session.chainedProtocolFactory = lambda: ServerProtocol(ShellServer, self.store) componentized.setComponent(IConchUser, user) componentized.setComponent(ISession, session) return user raise NotImplementedError(interface)
python
def indirect(self, interface): """ Create an L{IConchUser} avatar which will use L{ShellServer} to interact with the connection. """ if interface is IConchUser: componentized = Componentized() user = _BetterTerminalUser(componentized, None) session = _BetterTerminalSession(componentized) session.transportFactory = TerminalSessionTransport session.chainedProtocolFactory = lambda: ServerProtocol(ShellServer, self.store) componentized.setComponent(IConchUser, user) componentized.setComponent(ISession, session) return user raise NotImplementedError(interface)
[ "def", "indirect", "(", "self", ",", "interface", ")", ":", "if", "interface", "is", "IConchUser", ":", "componentized", "=", "Componentized", "(", ")", "user", "=", "_BetterTerminalUser", "(", "componentized", ",", "None", ")", "session", "=", "_BetterTermina...
Create an L{IConchUser} avatar which will use L{ShellServer} to interact with the connection.
[ "Create", "an", "L", "{", "IConchUser", "}", "avatar", "which", "will", "use", "L", "{", "ShellServer", "}", "to", "interact", "with", "the", "connection", "." ]
train
https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/terminal.py#L313-L331
jwodder/doapi
doapi/floating_ip.py
FloatingIP.fetch
def fetch(self): """ Fetch & return a new `FloatingIP` object representing the floating IP's current state :rtype: FloatingIP :raises DOAPIError: if the API endpoint replies with an error (e.g., if the floating IP no longer exists) """ api = self.doapi_manager return api._floating_ip(api.request(self.url)["floating_ip"])
python
def fetch(self): """ Fetch & return a new `FloatingIP` object representing the floating IP's current state :rtype: FloatingIP :raises DOAPIError: if the API endpoint replies with an error (e.g., if the floating IP no longer exists) """ api = self.doapi_manager return api._floating_ip(api.request(self.url)["floating_ip"])
[ "def", "fetch", "(", "self", ")", ":", "api", "=", "self", ".", "doapi_manager", "return", "api", ".", "_floating_ip", "(", "api", ".", "request", "(", "self", ".", "url", ")", "[", "\"floating_ip\"", "]", ")" ]
Fetch & return a new `FloatingIP` object representing the floating IP's current state :rtype: FloatingIP :raises DOAPIError: if the API endpoint replies with an error (e.g., if the floating IP no longer exists)
[ "Fetch", "&", "return", "a", "new", "FloatingIP", "object", "representing", "the", "floating", "IP", "s", "current", "state" ]
train
https://github.com/jwodder/doapi/blob/b1306de86a01d8ae7b9c1fe2699765bb82e4f310/doapi/floating_ip.py#L60-L70
jwodder/doapi
doapi/floating_ip.py
FloatingIP.assign
def assign(self, droplet_id): """ Assign the floating IP to a droplet :param droplet_id: the droplet to assign the floating IP to as either an ID or a `Droplet` object :type droplet_id: integer or `Droplet` :return: an `Action` representing the in-progress operation on the floating IP :rtype: Action :raises DOAPIError: if the API endpoint replies with an error """ if isinstance(droplet_id, Droplet): droplet_id = droplet_id.id return self.act(type='assign', droplet_id=droplet_id)
python
def assign(self, droplet_id): """ Assign the floating IP to a droplet :param droplet_id: the droplet to assign the floating IP to as either an ID or a `Droplet` object :type droplet_id: integer or `Droplet` :return: an `Action` representing the in-progress operation on the floating IP :rtype: Action :raises DOAPIError: if the API endpoint replies with an error """ if isinstance(droplet_id, Droplet): droplet_id = droplet_id.id return self.act(type='assign', droplet_id=droplet_id)
[ "def", "assign", "(", "self", ",", "droplet_id", ")", ":", "if", "isinstance", "(", "droplet_id", ",", "Droplet", ")", ":", "droplet_id", "=", "droplet_id", ".", "id", "return", "self", ".", "act", "(", "type", "=", "'assign'", ",", "droplet_id", "=", ...
Assign the floating IP to a droplet :param droplet_id: the droplet to assign the floating IP to as either an ID or a `Droplet` object :type droplet_id: integer or `Droplet` :return: an `Action` representing the in-progress operation on the floating IP :rtype: Action :raises DOAPIError: if the API endpoint replies with an error
[ "Assign", "the", "floating", "IP", "to", "a", "droplet" ]
train
https://github.com/jwodder/doapi/blob/b1306de86a01d8ae7b9c1fe2699765bb82e4f310/doapi/floating_ip.py#L81-L95
jwodder/doapi
doapi/ssh_key.py
SSHKey._id
def _id(self): r""" The `SSHKey`'s ``id`` field, or if that is not defined, its ``fingerprint`` field. If neither field is defined, accessing this attribute raises a `TypeError`. """ if self.get("id") is not None: return self.id elif self.get("fingerprint") is not None: return self.fingerprint else: raise TypeError('SSHKey has neither .id nor .fingerprint')
python
def _id(self): r""" The `SSHKey`'s ``id`` field, or if that is not defined, its ``fingerprint`` field. If neither field is defined, accessing this attribute raises a `TypeError`. """ if self.get("id") is not None: return self.id elif self.get("fingerprint") is not None: return self.fingerprint else: raise TypeError('SSHKey has neither .id nor .fingerprint')
[ "def", "_id", "(", "self", ")", ":", "if", "self", ".", "get", "(", "\"id\"", ")", "is", "not", "None", ":", "return", "self", ".", "id", "elif", "self", ".", "get", "(", "\"fingerprint\"", ")", "is", "not", "None", ":", "return", "self", ".", "f...
r""" The `SSHKey`'s ``id`` field, or if that is not defined, its ``fingerprint`` field. If neither field is defined, accessing this attribute raises a `TypeError`.
[ "r", "The", "SSHKey", "s", "id", "field", "or", "if", "that", "is", "not", "defined", "its", "fingerprint", "field", ".", "If", "neither", "field", "is", "defined", "accessing", "this", "attribute", "raises", "a", "TypeError", "." ]
train
https://github.com/jwodder/doapi/blob/b1306de86a01d8ae7b9c1fe2699765bb82e4f310/doapi/ssh_key.py#L40-L51
jwodder/doapi
doapi/ssh_key.py
SSHKey.fetch
def fetch(self): """ Fetch & return a new `SSHKey` object representing the SSH key's current state :rtype: SSHKey :raises DOAPIError: if the API endpoint replies with an error (e.g., if the SSH key no longer exists) """ api = self.doapi_manager return api._ssh_key(api.request(self.url)["ssh_key"])
python
def fetch(self): """ Fetch & return a new `SSHKey` object representing the SSH key's current state :rtype: SSHKey :raises DOAPIError: if the API endpoint replies with an error (e.g., if the SSH key no longer exists) """ api = self.doapi_manager return api._ssh_key(api.request(self.url)["ssh_key"])
[ "def", "fetch", "(", "self", ")", ":", "api", "=", "self", ".", "doapi_manager", "return", "api", ".", "_ssh_key", "(", "api", ".", "request", "(", "self", ".", "url", ")", "[", "\"ssh_key\"", "]", ")" ]
Fetch & return a new `SSHKey` object representing the SSH key's current state :rtype: SSHKey :raises DOAPIError: if the API endpoint replies with an error (e.g., if the SSH key no longer exists)
[ "Fetch", "&", "return", "a", "new", "SSHKey", "object", "representing", "the", "SSH", "key", "s", "current", "state" ]
train
https://github.com/jwodder/doapi/blob/b1306de86a01d8ae7b9c1fe2699765bb82e4f310/doapi/ssh_key.py#L58-L68
jwodder/doapi
doapi/ssh_key.py
SSHKey.update_ssh_key
def update_ssh_key(self, name): # The `_ssh_key` is to avoid conflicts with MutableMapping.update. """ Update (i.e., rename) the SSH key :param str name: the new name for the SSH key :return: an updated `SSHKey` object :rtype: SSHKey :raises DOAPIError: if the API endpoint replies with an error """ api = self.doapi_manager return api._ssh_key(api.request(self.url, method='PUT', data={"name": name})["ssh_key"])
python
def update_ssh_key(self, name): # The `_ssh_key` is to avoid conflicts with MutableMapping.update. """ Update (i.e., rename) the SSH key :param str name: the new name for the SSH key :return: an updated `SSHKey` object :rtype: SSHKey :raises DOAPIError: if the API endpoint replies with an error """ api = self.doapi_manager return api._ssh_key(api.request(self.url, method='PUT', data={"name": name})["ssh_key"])
[ "def", "update_ssh_key", "(", "self", ",", "name", ")", ":", "# The `_ssh_key` is to avoid conflicts with MutableMapping.update.", "api", "=", "self", ".", "doapi_manager", "return", "api", ".", "_ssh_key", "(", "api", ".", "request", "(", "self", ".", "url", ",",...
Update (i.e., rename) the SSH key :param str name: the new name for the SSH key :return: an updated `SSHKey` object :rtype: SSHKey :raises DOAPIError: if the API endpoint replies with an error
[ "Update", "(", "i", ".", "e", ".", "rename", ")", "the", "SSH", "key" ]
train
https://github.com/jwodder/doapi/blob/b1306de86a01d8ae7b9c1fe2699765bb82e4f310/doapi/ssh_key.py#L70-L82
truemped/tornadotools
tornadotools/mongrel2/request.py
MongrelRequest.parse
def parse(msg): """ Helper method for parsing a Mongrel2 request string and returning a new `MongrelRequest` instance. """ sender, conn_id, path, rest = msg.split(' ', 3) headers, rest = tnetstring.pop(rest) body, _ = tnetstring.pop(rest) if type(headers) is str: headers = json.loads(headers) return MongrelRequest(sender, conn_id, path, headers, body)
python
def parse(msg): """ Helper method for parsing a Mongrel2 request string and returning a new `MongrelRequest` instance. """ sender, conn_id, path, rest = msg.split(' ', 3) headers, rest = tnetstring.pop(rest) body, _ = tnetstring.pop(rest) if type(headers) is str: headers = json.loads(headers) return MongrelRequest(sender, conn_id, path, headers, body)
[ "def", "parse", "(", "msg", ")", ":", "sender", ",", "conn_id", ",", "path", ",", "rest", "=", "msg", ".", "split", "(", "' '", ",", "3", ")", "headers", ",", "rest", "=", "tnetstring", ".", "pop", "(", "rest", ")", "body", ",", "_", "=", "tnet...
Helper method for parsing a Mongrel2 request string and returning a new `MongrelRequest` instance.
[ "Helper", "method", "for", "parsing", "a", "Mongrel2", "request", "string", "and", "returning", "a", "new", "MongrelRequest", "instance", "." ]
train
https://github.com/truemped/tornadotools/blob/d22632b83810afc353fa886fbc9e265bee78653f/tornadotools/mongrel2/request.py#L45-L57
truemped/tornadotools
tornadotools/mongrel2/request.py
MongrelRequest.should_close
def should_close(self): """ Check whether the HTTP connection of this request should be closed after the request is finished. We check for the `Connection` HTTP header and for the HTTP Version (only `HTTP/1.1` supports keep-alive. """ if self.headers.get('connection') == 'close': return True elif 'content-length' in self.headers or \ self.headers.get('METHOD') in ['HEAD', 'GET']: return self.headers.get('connection') != 'keep-alive' elif self.headers.get('VERSION') == 'HTTP/1.0': return True else: return False
python
def should_close(self): """ Check whether the HTTP connection of this request should be closed after the request is finished. We check for the `Connection` HTTP header and for the HTTP Version (only `HTTP/1.1` supports keep-alive. """ if self.headers.get('connection') == 'close': return True elif 'content-length' in self.headers or \ self.headers.get('METHOD') in ['HEAD', 'GET']: return self.headers.get('connection') != 'keep-alive' elif self.headers.get('VERSION') == 'HTTP/1.0': return True else: return False
[ "def", "should_close", "(", "self", ")", ":", "if", "self", ".", "headers", ".", "get", "(", "'connection'", ")", "==", "'close'", ":", "return", "True", "elif", "'content-length'", "in", "self", ".", "headers", "or", "self", ".", "headers", ".", "get", ...
Check whether the HTTP connection of this request should be closed after the request is finished. We check for the `Connection` HTTP header and for the HTTP Version (only `HTTP/1.1` supports keep-alive.
[ "Check", "whether", "the", "HTTP", "connection", "of", "this", "request", "should", "be", "closed", "after", "the", "request", "is", "finished", "." ]
train
https://github.com/truemped/tornadotools/blob/d22632b83810afc353fa886fbc9e265bee78653f/tornadotools/mongrel2/request.py#L63-L79
p3trus/slave
slave/quantum_design/ppms.py
PPMS.system_status
def system_status(self): """The system status codes.""" flag, timestamp, status = self._query(('GETDAT? 1', (Integer, Float, Integer))) return { # convert unix timestamp to datetime object 'timestamp': datetime.datetime.fromtimestamp(timestamp), # bit 0-3 represent the temperature controller status 'temperature': STATUS_TEMPERATURE[status & 0xf], # bit 4-7 represent the magnet status 'magnet': STATUS_MAGNET[(status >> 4) & 0xf], # bit 8-11 represent the chamber status 'chamber': STATUS_CHAMBER[(status >> 8) & 0xf], # bit 12-15 represent the sample position status 'sample_position': STATUS_SAMPLE_POSITION[(status >> 12) & 0xf], }
python
def system_status(self): """The system status codes.""" flag, timestamp, status = self._query(('GETDAT? 1', (Integer, Float, Integer))) return { # convert unix timestamp to datetime object 'timestamp': datetime.datetime.fromtimestamp(timestamp), # bit 0-3 represent the temperature controller status 'temperature': STATUS_TEMPERATURE[status & 0xf], # bit 4-7 represent the magnet status 'magnet': STATUS_MAGNET[(status >> 4) & 0xf], # bit 8-11 represent the chamber status 'chamber': STATUS_CHAMBER[(status >> 8) & 0xf], # bit 12-15 represent the sample position status 'sample_position': STATUS_SAMPLE_POSITION[(status >> 12) & 0xf], }
[ "def", "system_status", "(", "self", ")", ":", "flag", ",", "timestamp", ",", "status", "=", "self", ".", "_query", "(", "(", "'GETDAT? 1'", ",", "(", "Integer", ",", "Float", ",", "Integer", ")", ")", ")", "return", "{", "# convert unix timestamp to datet...
The system status codes.
[ "The", "system", "status", "codes", "." ]
train
https://github.com/p3trus/slave/blob/bdc74e73bd0f47b74a090c43aa2283c469cde3be/slave/quantum_design/ppms.py#L422-L436
p3trus/slave
slave/quantum_design/ppms.py
PPMS.beep
def beep(self, duration, frequency): """Generates a beep. :param duration: The duration in seconds, in the range 0.1 to 5. :param frequency: The frequency in Hz, in the range 500 to 5000. """ cmd = 'BEEP', [Float(min=0.1, max=5.0), Integer(min=500, max=5000)] self._write(cmd, duration, frequency)
python
def beep(self, duration, frequency): """Generates a beep. :param duration: The duration in seconds, in the range 0.1 to 5. :param frequency: The frequency in Hz, in the range 500 to 5000. """ cmd = 'BEEP', [Float(min=0.1, max=5.0), Integer(min=500, max=5000)] self._write(cmd, duration, frequency)
[ "def", "beep", "(", "self", ",", "duration", ",", "frequency", ")", ":", "cmd", "=", "'BEEP'", ",", "[", "Float", "(", "min", "=", "0.1", ",", "max", "=", "5.0", ")", ",", "Integer", "(", "min", "=", "500", ",", "max", "=", "5000", ")", "]", ...
Generates a beep. :param duration: The duration in seconds, in the range 0.1 to 5. :param frequency: The frequency in Hz, in the range 500 to 5000.
[ "Generates", "a", "beep", "." ]
train
https://github.com/p3trus/slave/blob/bdc74e73bd0f47b74a090c43aa2283c469cde3be/slave/quantum_design/ppms.py#L444-L452
p3trus/slave
slave/quantum_design/ppms.py
PPMS.move
def move(self, position, slowdown=0): """Move to the specified sample position. :param position: The target position. :param slowdown: The slowdown code, an integer in the range 0 to 14, used to scale the stepper motor speed. 0, the default, is the fastest rate and 14 the slowest. """ cmd = 'MOVE', [Float, Integer, Integer(min=0, max=14)] self._write(cmd, position, 0, slowdown)
python
def move(self, position, slowdown=0): """Move to the specified sample position. :param position: The target position. :param slowdown: The slowdown code, an integer in the range 0 to 14, used to scale the stepper motor speed. 0, the default, is the fastest rate and 14 the slowest. """ cmd = 'MOVE', [Float, Integer, Integer(min=0, max=14)] self._write(cmd, position, 0, slowdown)
[ "def", "move", "(", "self", ",", "position", ",", "slowdown", "=", "0", ")", ":", "cmd", "=", "'MOVE'", ",", "[", "Float", ",", "Integer", ",", "Integer", "(", "min", "=", "0", ",", "max", "=", "14", ")", "]", "self", ".", "_write", "(", "cmd",...
Move to the specified sample position. :param position: The target position. :param slowdown: The slowdown code, an integer in the range 0 to 14, used to scale the stepper motor speed. 0, the default, is the fastest rate and 14 the slowest.
[ "Move", "to", "the", "specified", "sample", "position", "." ]
train
https://github.com/p3trus/slave/blob/bdc74e73bd0f47b74a090c43aa2283c469cde3be/slave/quantum_design/ppms.py#L499-L509
p3trus/slave
slave/quantum_design/ppms.py
PPMS.move_to_limit
def move_to_limit(self, position): """Move to limit switch and define it as position. :param position: The new position of the limit switch. """ cmd = 'MOVE', [Float, Integer] self._write(cmd, position, 1)
python
def move_to_limit(self, position): """Move to limit switch and define it as position. :param position: The new position of the limit switch. """ cmd = 'MOVE', [Float, Integer] self._write(cmd, position, 1)
[ "def", "move_to_limit", "(", "self", ",", "position", ")", ":", "cmd", "=", "'MOVE'", ",", "[", "Float", ",", "Integer", "]", "self", ".", "_write", "(", "cmd", ",", "position", ",", "1", ")" ]
Move to limit switch and define it as position. :param position: The new position of the limit switch.
[ "Move", "to", "limit", "switch", "and", "define", "it", "as", "position", "." ]
train
https://github.com/p3trus/slave/blob/bdc74e73bd0f47b74a090c43aa2283c469cde3be/slave/quantum_design/ppms.py#L511-L518
p3trus/slave
slave/quantum_design/ppms.py
PPMS.redefine_position
def redefine_position(self, position): """Redefines the current position to the new position. :param position: The new position. """ cmd = 'MOVE', [Float, Integer] self._write(cmd, position, 2)
python
def redefine_position(self, position): """Redefines the current position to the new position. :param position: The new position. """ cmd = 'MOVE', [Float, Integer] self._write(cmd, position, 2)
[ "def", "redefine_position", "(", "self", ",", "position", ")", ":", "cmd", "=", "'MOVE'", ",", "[", "Float", ",", "Integer", "]", "self", ".", "_write", "(", "cmd", ",", "position", ",", "2", ")" ]
Redefines the current position to the new position. :param position: The new position.
[ "Redefines", "the", "current", "position", "to", "the", "new", "position", "." ]
train
https://github.com/p3trus/slave/blob/bdc74e73bd0f47b74a090c43aa2283c469cde3be/slave/quantum_design/ppms.py#L520-L527
p3trus/slave
slave/quantum_design/ppms.py
PPMS.scan_temperature
def scan_temperature(self, measure, temperature, rate, delay=1): """Performs a temperature scan. Measures until the target temperature is reached. :param measure: A callable called repeatedly until stability at target temperature is reached. :param temperature: The target temperature in kelvin. :param rate: The sweep rate in kelvin per minute. :param delay: The time delay between each call to measure in seconds. """ if not hasattr(measure, '__call__'): raise TypeError('measure parameter not callable.') self.set_temperature(temperature, rate, 'no overshoot', wait_for_stability=False) start = datetime.datetime.now() while True: # The PPMS needs some time to update the status code, we therefore ignore it for 10s. if (self.system_status['temperature'] == 'normal stability at target temperature' and (datetime.datetime.now() - start > datetime.timedelta(seconds=10))): break measure() time.sleep(delay)
python
def scan_temperature(self, measure, temperature, rate, delay=1): """Performs a temperature scan. Measures until the target temperature is reached. :param measure: A callable called repeatedly until stability at target temperature is reached. :param temperature: The target temperature in kelvin. :param rate: The sweep rate in kelvin per minute. :param delay: The time delay between each call to measure in seconds. """ if not hasattr(measure, '__call__'): raise TypeError('measure parameter not callable.') self.set_temperature(temperature, rate, 'no overshoot', wait_for_stability=False) start = datetime.datetime.now() while True: # The PPMS needs some time to update the status code, we therefore ignore it for 10s. if (self.system_status['temperature'] == 'normal stability at target temperature' and (datetime.datetime.now() - start > datetime.timedelta(seconds=10))): break measure() time.sleep(delay)
[ "def", "scan_temperature", "(", "self", ",", "measure", ",", "temperature", ",", "rate", ",", "delay", "=", "1", ")", ":", "if", "not", "hasattr", "(", "measure", ",", "'__call__'", ")", ":", "raise", "TypeError", "(", "'measure parameter not callable.'", ")...
Performs a temperature scan. Measures until the target temperature is reached. :param measure: A callable called repeatedly until stability at target temperature is reached. :param temperature: The target temperature in kelvin. :param rate: The sweep rate in kelvin per minute. :param delay: The time delay between each call to measure in seconds.
[ "Performs", "a", "temperature", "scan", "." ]
train
https://github.com/p3trus/slave/blob/bdc74e73bd0f47b74a090c43aa2283c469cde3be/slave/quantum_design/ppms.py#L529-L552
p3trus/slave
slave/quantum_design/ppms.py
PPMS.scan_field
def scan_field(self, measure, field, rate, mode='persistent', delay=1): """Performs a field scan. Measures until the target field is reached. :param measure: A callable called repeatedly until stability at the target field is reached. :param field: The target field in Oersted. .. note:: The conversion is 1 Oe = 0.1 mT. :param rate: The field rate in Oersted per minute. :param mode: The state of the magnet at the end of the charging process, either 'persistent' or 'driven'. :param delay: The time delay between each call to measure in seconds. :raises TypeError: if measure parameter is not callable. """ if not hasattr(measure, '__call__'): raise TypeError('measure parameter not callable.') self.set_field(field, rate, approach='linear', mode=mode, wait_for_stability=False) if self.system_status['magnet'].startswith('persist'): # The persistent switch takes some time to open. While it's opening, # the status does not change. switch_heat_time = datetime.timedelta(seconds=self.magnet_config[5]) start = datetime.datetime.now() while True: now = datetime.datetime.now() if now - start > switch_heat_time: break measure() time.sleep(delay) while True: status = self.system_status['magnet'] if status in ('persistent, stable', 'driven, stable'): break measure() time.sleep(delay)
python
def scan_field(self, measure, field, rate, mode='persistent', delay=1): """Performs a field scan. Measures until the target field is reached. :param measure: A callable called repeatedly until stability at the target field is reached. :param field: The target field in Oersted. .. note:: The conversion is 1 Oe = 0.1 mT. :param rate: The field rate in Oersted per minute. :param mode: The state of the magnet at the end of the charging process, either 'persistent' or 'driven'. :param delay: The time delay between each call to measure in seconds. :raises TypeError: if measure parameter is not callable. """ if not hasattr(measure, '__call__'): raise TypeError('measure parameter not callable.') self.set_field(field, rate, approach='linear', mode=mode, wait_for_stability=False) if self.system_status['magnet'].startswith('persist'): # The persistent switch takes some time to open. While it's opening, # the status does not change. switch_heat_time = datetime.timedelta(seconds=self.magnet_config[5]) start = datetime.datetime.now() while True: now = datetime.datetime.now() if now - start > switch_heat_time: break measure() time.sleep(delay) while True: status = self.system_status['magnet'] if status in ('persistent, stable', 'driven, stable'): break measure() time.sleep(delay)
[ "def", "scan_field", "(", "self", ",", "measure", ",", "field", ",", "rate", ",", "mode", "=", "'persistent'", ",", "delay", "=", "1", ")", ":", "if", "not", "hasattr", "(", "measure", ",", "'__call__'", ")", ":", "raise", "TypeError", "(", "'measure p...
Performs a field scan. Measures until the target field is reached. :param measure: A callable called repeatedly until stability at the target field is reached. :param field: The target field in Oersted. .. note:: The conversion is 1 Oe = 0.1 mT. :param rate: The field rate in Oersted per minute. :param mode: The state of the magnet at the end of the charging process, either 'persistent' or 'driven'. :param delay: The time delay between each call to measure in seconds. :raises TypeError: if measure parameter is not callable.
[ "Performs", "a", "field", "scan", "." ]
train
https://github.com/p3trus/slave/blob/bdc74e73bd0f47b74a090c43aa2283c469cde3be/slave/quantum_design/ppms.py#L554-L592
p3trus/slave
slave/quantum_design/ppms.py
PPMS.set_field
def set_field(self, field, rate, approach='linear', mode='persistent', wait_for_stability=True, delay=1): """Sets the magnetic field. :param field: The target field in Oersted. .. note:: The conversion is 1 Oe = 0.1 mT. :param rate: The field rate in Oersted per minute. :param approach: The approach mode, either 'linear', 'no overshoot' or 'oscillate'. :param mode: The state of the magnet at the end of the charging process, either 'persistent' or 'driven'. :param wait_for_stability: If `True`, the function call blocks until the target field is reached and stable. :param delay: Specifies the frequency in seconds how often the magnet status is checked. (This has no effect if wait_for_stability is `False`). """ self.target_field = field, rate, approach, mode if wait_for_stability and self.system_status['magnet'].startswith('persist'): # Wait until the persistent switch heats up. time.sleep(self.magnet_config[5]) while wait_for_stability: status = self.system_status['magnet'] if status in ('persistent, stable', 'driven, stable'): break time.sleep(delay)
python
def set_field(self, field, rate, approach='linear', mode='persistent', wait_for_stability=True, delay=1): """Sets the magnetic field. :param field: The target field in Oersted. .. note:: The conversion is 1 Oe = 0.1 mT. :param rate: The field rate in Oersted per minute. :param approach: The approach mode, either 'linear', 'no overshoot' or 'oscillate'. :param mode: The state of the magnet at the end of the charging process, either 'persistent' or 'driven'. :param wait_for_stability: If `True`, the function call blocks until the target field is reached and stable. :param delay: Specifies the frequency in seconds how often the magnet status is checked. (This has no effect if wait_for_stability is `False`). """ self.target_field = field, rate, approach, mode if wait_for_stability and self.system_status['magnet'].startswith('persist'): # Wait until the persistent switch heats up. time.sleep(self.magnet_config[5]) while wait_for_stability: status = self.system_status['magnet'] if status in ('persistent, stable', 'driven, stable'): break time.sleep(delay)
[ "def", "set_field", "(", "self", ",", "field", ",", "rate", ",", "approach", "=", "'linear'", ",", "mode", "=", "'persistent'", ",", "wait_for_stability", "=", "True", ",", "delay", "=", "1", ")", ":", "self", ".", "target_field", "=", "field", ",", "r...
Sets the magnetic field. :param field: The target field in Oersted. .. note:: The conversion is 1 Oe = 0.1 mT. :param rate: The field rate in Oersted per minute. :param approach: The approach mode, either 'linear', 'no overshoot' or 'oscillate'. :param mode: The state of the magnet at the end of the charging process, either 'persistent' or 'driven'. :param wait_for_stability: If `True`, the function call blocks until the target field is reached and stable. :param delay: Specifies the frequency in seconds how often the magnet status is checked. (This has no effect if wait_for_stability is `False`).
[ "Sets", "the", "magnetic", "field", "." ]
train
https://github.com/p3trus/slave/blob/bdc74e73bd0f47b74a090c43aa2283c469cde3be/slave/quantum_design/ppms.py#L594-L623
p3trus/slave
slave/quantum_design/ppms.py
PPMS.set_temperature
def set_temperature(self, temperature, rate, mode='fast', wait_for_stability=True, delay=1): """Sets the temperature. :param temperature: The target temperature in kelvin. :param rate: The sweep rate in kelvin per minute. :param mode: The sweep mode, either 'fast' or 'no overshoot'. :param wait_for_stability: If wait_for_stability is `True`, the function call blocks until the target temperature is reached and stable. :param delay: The delay specifies the frequency how often the status is checked. """ self.target_temperature = temperature, rate, mode start = datetime.datetime.now() while wait_for_stability: # The PPMS needs some time to update the status code, we therefore ignore it for 10s. if (self.system_status['temperature'] == 'normal stability at target temperature' and (datetime.datetime.now() - start > datetime.timedelta(seconds=10))): break time.sleep(delay)
python
def set_temperature(self, temperature, rate, mode='fast', wait_for_stability=True, delay=1): """Sets the temperature. :param temperature: The target temperature in kelvin. :param rate: The sweep rate in kelvin per minute. :param mode: The sweep mode, either 'fast' or 'no overshoot'. :param wait_for_stability: If wait_for_stability is `True`, the function call blocks until the target temperature is reached and stable. :param delay: The delay specifies the frequency how often the status is checked. """ self.target_temperature = temperature, rate, mode start = datetime.datetime.now() while wait_for_stability: # The PPMS needs some time to update the status code, we therefore ignore it for 10s. if (self.system_status['temperature'] == 'normal stability at target temperature' and (datetime.datetime.now() - start > datetime.timedelta(seconds=10))): break time.sleep(delay)
[ "def", "set_temperature", "(", "self", ",", "temperature", ",", "rate", ",", "mode", "=", "'fast'", ",", "wait_for_stability", "=", "True", ",", "delay", "=", "1", ")", ":", "self", ".", "target_temperature", "=", "temperature", ",", "rate", ",", "mode", ...
Sets the temperature. :param temperature: The target temperature in kelvin. :param rate: The sweep rate in kelvin per minute. :param mode: The sweep mode, either 'fast' or 'no overshoot'. :param wait_for_stability: If wait_for_stability is `True`, the function call blocks until the target temperature is reached and stable. :param delay: The delay specifies the frequency how often the status is checked.
[ "Sets", "the", "temperature", "." ]
train
https://github.com/p3trus/slave/blob/bdc74e73bd0f47b74a090c43aa2283c469cde3be/slave/quantum_design/ppms.py#L625-L643
inveniosoftware/invenio-openaire
invenio_openaire/cli.py
loadgrants
def loadgrants(source=None, setspec=None, all_grants=False): """Harvest grants from OpenAIRE. :param source: Load the grants from a local sqlite db (offline). The value of the parameter should be a path to the local file. :type source: str :param setspec: Harvest specific set through OAI-PMH Creates a remote connection to OpenAIRE. :type setspec: str :param all_grants: Harvest all sets through OAI-PMH, as specified in the configuration OPENAIRE_GRANTS_SPEC. Sets are harvested sequentially in the order specified in the configuration. Creates a remote connection to OpenAIRE. :type all_grants: bool """ assert all_grants or setspec or source, \ "Either '--all', '--setspec' or '--source' is required parameter." if all_grants: harvest_all_openaire_projects.delay() elif setspec: click.echo("Remote grants loading sent to queue.") harvest_openaire_projects.delay(setspec=setspec) else: # if source loader = LocalOAIRELoader(source=source) loader._connect() cnt = loader._count() click.echo("Sending grants to queue.") with click.progressbar(loader.iter_grants(), length=cnt) as grants_bar: for grant_json in grants_bar: register_grant.delay(grant_json)
python
def loadgrants(source=None, setspec=None, all_grants=False): """Harvest grants from OpenAIRE. :param source: Load the grants from a local sqlite db (offline). The value of the parameter should be a path to the local file. :type source: str :param setspec: Harvest specific set through OAI-PMH Creates a remote connection to OpenAIRE. :type setspec: str :param all_grants: Harvest all sets through OAI-PMH, as specified in the configuration OPENAIRE_GRANTS_SPEC. Sets are harvested sequentially in the order specified in the configuration. Creates a remote connection to OpenAIRE. :type all_grants: bool """ assert all_grants or setspec or source, \ "Either '--all', '--setspec' or '--source' is required parameter." if all_grants: harvest_all_openaire_projects.delay() elif setspec: click.echo("Remote grants loading sent to queue.") harvest_openaire_projects.delay(setspec=setspec) else: # if source loader = LocalOAIRELoader(source=source) loader._connect() cnt = loader._count() click.echo("Sending grants to queue.") with click.progressbar(loader.iter_grants(), length=cnt) as grants_bar: for grant_json in grants_bar: register_grant.delay(grant_json)
[ "def", "loadgrants", "(", "source", "=", "None", ",", "setspec", "=", "None", ",", "all_grants", "=", "False", ")", ":", "assert", "all_grants", "or", "setspec", "or", "source", ",", "\"Either '--all', '--setspec' or '--source' is required parameter.\"", "if", "all_...
Harvest grants from OpenAIRE. :param source: Load the grants from a local sqlite db (offline). The value of the parameter should be a path to the local file. :type source: str :param setspec: Harvest specific set through OAI-PMH Creates a remote connection to OpenAIRE. :type setspec: str :param all_grants: Harvest all sets through OAI-PMH, as specified in the configuration OPENAIRE_GRANTS_SPEC. Sets are harvested sequentially in the order specified in the configuration. Creates a remote connection to OpenAIRE. :type all_grants: bool
[ "Harvest", "grants", "from", "OpenAIRE", "." ]
train
https://github.com/inveniosoftware/invenio-openaire/blob/71860effff6abe7f658d3a11894e064202ef1c36/invenio_openaire/cli.py#L75-L105
inveniosoftware/invenio-openaire
invenio_openaire/cli.py
registergrant
def registergrant(source=None, setspec=None): """Harvest grants from OpenAIRE.""" with open(source, 'r') as fp: data = json.load(fp) register_grant(data)
python
def registergrant(source=None, setspec=None): """Harvest grants from OpenAIRE.""" with open(source, 'r') as fp: data = json.load(fp) register_grant(data)
[ "def", "registergrant", "(", "source", "=", "None", ",", "setspec", "=", "None", ")", ":", "with", "open", "(", "source", ",", "'r'", ")", "as", "fp", ":", "data", "=", "json", ".", "load", "(", "fp", ")", "register_grant", "(", "data", ")" ]
Harvest grants from OpenAIRE.
[ "Harvest", "grants", "from", "OpenAIRE", "." ]
train
https://github.com/inveniosoftware/invenio-openaire/blob/71860effff6abe7f658d3a11894e064202ef1c36/invenio_openaire/cli.py#L115-L119
inveniosoftware/invenio-openaire
invenio_openaire/cli.py
dumpgrants
def dumpgrants(destination, as_json=None, setspec=None): """Harvest grants from OpenAIRE and store them locally.""" if os.path.isfile(destination): click.confirm("Database '{0}' already exists." "Do you want to write to it?".format(destination), abort=True) # no cover dumper = OAIREDumper(destination, setspec=setspec) dumper.dump(as_json=as_json)
python
def dumpgrants(destination, as_json=None, setspec=None): """Harvest grants from OpenAIRE and store them locally.""" if os.path.isfile(destination): click.confirm("Database '{0}' already exists." "Do you want to write to it?".format(destination), abort=True) # no cover dumper = OAIREDumper(destination, setspec=setspec) dumper.dump(as_json=as_json)
[ "def", "dumpgrants", "(", "destination", ",", "as_json", "=", "None", ",", "setspec", "=", "None", ")", ":", "if", "os", ".", "path", ".", "isfile", "(", "destination", ")", ":", "click", ".", "confirm", "(", "\"Database '{0}' already exists.\"", "\"Do you w...
Harvest grants from OpenAIRE and store them locally.
[ "Harvest", "grants", "from", "OpenAIRE", "and", "store", "them", "locally", "." ]
train
https://github.com/inveniosoftware/invenio-openaire/blob/71860effff6abe7f658d3a11894e064202ef1c36/invenio_openaire/cli.py#L137-L145
twisted/mantissa
axiom/plugins/offeringcmd.py
SetFrontPage.postOptions
def postOptions(self): """ Find an installed offering and set the site front page to its application's front page. """ o = self.store.findFirst( offering.InstalledOffering, (offering.InstalledOffering.offeringName == self["name"])) if o is None: raise usage.UsageError("No offering of that name" " is installed.") fp = self.store.findUnique(publicweb.FrontPage) fp.defaultApplication = o.application
python
def postOptions(self): """ Find an installed offering and set the site front page to its application's front page. """ o = self.store.findFirst( offering.InstalledOffering, (offering.InstalledOffering.offeringName == self["name"])) if o is None: raise usage.UsageError("No offering of that name" " is installed.") fp = self.store.findUnique(publicweb.FrontPage) fp.defaultApplication = o.application
[ "def", "postOptions", "(", "self", ")", ":", "o", "=", "self", ".", "store", ".", "findFirst", "(", "offering", ".", "InstalledOffering", ",", "(", "offering", ".", "InstalledOffering", ".", "offeringName", "==", "self", "[", "\"name\"", "]", ")", ")", "...
Find an installed offering and set the site front page to its application's front page.
[ "Find", "an", "installed", "offering", "and", "set", "the", "site", "front", "page", "to", "its", "application", "s", "front", "page", "." ]
train
https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/axiom/plugins/offeringcmd.py#L45-L58
twisted/mantissa
xmantissa/liveform.py
_legacySpecialCases
def _legacySpecialCases(form, patterns, parameter): """ Create a view object for the given parameter. This function implements the remaining view construction logic which has not yet been converted to the C{viewFactory}-style expressed in L{_LiveFormMixin.form}. @type form: L{_LiveFormMixin} @param form: The form fragment which contains the given parameter. @type patterns: L{PatternDictionary} @type parameter: L{Parameter}, L{ChoiceParameter}, or L{ListParameter}. """ p = patterns[parameter.type + '-input-container'] if parameter.type == TEXTAREA_INPUT: p = dictFillSlots(p, dict(label=parameter.label, name=parameter.name, value=parameter.default or '')) elif parameter.type == MULTI_TEXT_INPUT: subInputs = list() for i in xrange(parameter.count): subInputs.append(dictFillSlots(patterns['input'], dict(name=parameter.name + '_' + str(i), type='text', value=parameter.defaults[i]))) p = dictFillSlots(p, dict(label=parameter.label or parameter.name, inputs=subInputs)) else: if parameter.default is not None: value = parameter.default else: value = '' if parameter.type == CHECKBOX_INPUT and parameter.default: inputPattern = 'checked-checkbox-input' else: inputPattern = 'input' p = dictFillSlots( p, dict(label=parameter.label or parameter.name, input=dictFillSlots(patterns[inputPattern], dict(name=parameter.name, type=parameter.type, value=value)))) p(**{'class' : 'liveform_'+parameter.name}) if parameter.description: description = patterns['description'].fillSlots( 'description', parameter.description) else: description = '' return dictFillSlots( patterns['parameter-input'], dict(input=p, description=description))
python
def _legacySpecialCases(form, patterns, parameter): """ Create a view object for the given parameter. This function implements the remaining view construction logic which has not yet been converted to the C{viewFactory}-style expressed in L{_LiveFormMixin.form}. @type form: L{_LiveFormMixin} @param form: The form fragment which contains the given parameter. @type patterns: L{PatternDictionary} @type parameter: L{Parameter}, L{ChoiceParameter}, or L{ListParameter}. """ p = patterns[parameter.type + '-input-container'] if parameter.type == TEXTAREA_INPUT: p = dictFillSlots(p, dict(label=parameter.label, name=parameter.name, value=parameter.default or '')) elif parameter.type == MULTI_TEXT_INPUT: subInputs = list() for i in xrange(parameter.count): subInputs.append(dictFillSlots(patterns['input'], dict(name=parameter.name + '_' + str(i), type='text', value=parameter.defaults[i]))) p = dictFillSlots(p, dict(label=parameter.label or parameter.name, inputs=subInputs)) else: if parameter.default is not None: value = parameter.default else: value = '' if parameter.type == CHECKBOX_INPUT and parameter.default: inputPattern = 'checked-checkbox-input' else: inputPattern = 'input' p = dictFillSlots( p, dict(label=parameter.label or parameter.name, input=dictFillSlots(patterns[inputPattern], dict(name=parameter.name, type=parameter.type, value=value)))) p(**{'class' : 'liveform_'+parameter.name}) if parameter.description: description = patterns['description'].fillSlots( 'description', parameter.description) else: description = '' return dictFillSlots( patterns['parameter-input'], dict(input=p, description=description))
[ "def", "_legacySpecialCases", "(", "form", ",", "patterns", ",", "parameter", ")", ":", "p", "=", "patterns", "[", "parameter", ".", "type", "+", "'-input-container'", "]", "if", "parameter", ".", "type", "==", "TEXTAREA_INPUT", ":", "p", "=", "dictFillSlots...
Create a view object for the given parameter. This function implements the remaining view construction logic which has not yet been converted to the C{viewFactory}-style expressed in L{_LiveFormMixin.form}. @type form: L{_LiveFormMixin} @param form: The form fragment which contains the given parameter. @type patterns: L{PatternDictionary} @type parameter: L{Parameter}, L{ChoiceParameter}, or L{ListParameter}.
[ "Create", "a", "view", "object", "for", "the", "given", "parameter", "." ]
train
https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/liveform.py#L746-L805
twisted/mantissa
xmantissa/liveform.py
_textParameterToView
def _textParameterToView(parameter): """ Return a L{TextParameterView} adapter for C{TEXT_INPUT}, C{PASSWORD_INPUT}, and C{FORM_INPUT} L{Parameter} instances. """ if parameter.type == TEXT_INPUT: return TextParameterView(parameter) if parameter.type == PASSWORD_INPUT: return PasswordParameterView(parameter) if parameter.type == FORM_INPUT: return FormInputParameterView(parameter) return None
python
def _textParameterToView(parameter): """ Return a L{TextParameterView} adapter for C{TEXT_INPUT}, C{PASSWORD_INPUT}, and C{FORM_INPUT} L{Parameter} instances. """ if parameter.type == TEXT_INPUT: return TextParameterView(parameter) if parameter.type == PASSWORD_INPUT: return PasswordParameterView(parameter) if parameter.type == FORM_INPUT: return FormInputParameterView(parameter) return None
[ "def", "_textParameterToView", "(", "parameter", ")", ":", "if", "parameter", ".", "type", "==", "TEXT_INPUT", ":", "return", "TextParameterView", "(", "parameter", ")", "if", "parameter", ".", "type", "==", "PASSWORD_INPUT", ":", "return", "PasswordParameterView"...
Return a L{TextParameterView} adapter for C{TEXT_INPUT}, C{PASSWORD_INPUT}, and C{FORM_INPUT} L{Parameter} instances.
[ "Return", "a", "L", "{", "TextParameterView", "}", "adapter", "for", "C", "{", "TEXT_INPUT", "}", "C", "{", "PASSWORD_INPUT", "}", "and", "C", "{", "FORM_INPUT", "}", "L", "{", "Parameter", "}", "instances", "." ]
train
https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/liveform.py#L1217-L1228
twisted/mantissa
xmantissa/liveform.py
_SelectiveCoercer.fromInputs
def fromInputs(self, inputs): """ Extract the inputs associated with the child forms of this parameter from the given dictionary and coerce them using C{self.coercer}. @type inputs: C{dict} mapping C{unicode} to C{list} of C{unicode} @param inputs: The contents of a form post, in the conventional structure. @rtype: L{Deferred} @return: The structured data associated with this parameter represented by the post data. """ try: values = inputs[self.name] except KeyError: raise ConfigurationError( "Missing value for input: " + self.name) return self.coerceMany(values)
python
def fromInputs(self, inputs): """ Extract the inputs associated with the child forms of this parameter from the given dictionary and coerce them using C{self.coercer}. @type inputs: C{dict} mapping C{unicode} to C{list} of C{unicode} @param inputs: The contents of a form post, in the conventional structure. @rtype: L{Deferred} @return: The structured data associated with this parameter represented by the post data. """ try: values = inputs[self.name] except KeyError: raise ConfigurationError( "Missing value for input: " + self.name) return self.coerceMany(values)
[ "def", "fromInputs", "(", "self", ",", "inputs", ")", ":", "try", ":", "values", "=", "inputs", "[", "self", ".", "name", "]", "except", "KeyError", ":", "raise", "ConfigurationError", "(", "\"Missing value for input: \"", "+", "self", ".", "name", ")", "r...
Extract the inputs associated with the child forms of this parameter from the given dictionary and coerce them using C{self.coercer}. @type inputs: C{dict} mapping C{unicode} to C{list} of C{unicode} @param inputs: The contents of a form post, in the conventional structure. @rtype: L{Deferred} @return: The structured data associated with this parameter represented by the post data.
[ "Extract", "the", "inputs", "associated", "with", "the", "child", "forms", "of", "this", "parameter", "from", "the", "given", "dictionary", "and", "coerce", "them", "using", "C", "{", "self", ".", "coercer", "}", "." ]
train
https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/liveform.py#L56-L74
twisted/mantissa
xmantissa/liveform.py
Parameter.clone
def clone(self, default): """ Make a copy of this parameter, supplying a different default. @type default: C{unicode} or C{NoneType} @param default: A value which will be initially presented in the view as the value for this parameter, or C{None} if no such value is to be presented. @rtype: L{Parameter} """ return self.__class__( self.name, self.type, self.coercer, self.label, self.description, default, self.viewFactory)
python
def clone(self, default): """ Make a copy of this parameter, supplying a different default. @type default: C{unicode} or C{NoneType} @param default: A value which will be initially presented in the view as the value for this parameter, or C{None} if no such value is to be presented. @rtype: L{Parameter} """ return self.__class__( self.name, self.type, self.coercer, self.label, self.description, default, self.viewFactory)
[ "def", "clone", "(", "self", ",", "default", ")", ":", "return", "self", ".", "__class__", "(", "self", ".", "name", ",", "self", ".", "type", ",", "self", ".", "coercer", ",", "self", ".", "label", ",", "self", ".", "description", ",", "default", ...
Make a copy of this parameter, supplying a different default. @type default: C{unicode} or C{NoneType} @param default: A value which will be initially presented in the view as the value for this parameter, or C{None} if no such value is to be presented. @rtype: L{Parameter}
[ "Make", "a", "copy", "of", "this", "parameter", "supplying", "a", "different", "default", "." ]
train
https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/liveform.py#L140-L158
twisted/mantissa
xmantissa/liveform.py
ListChangeParameter._prepareSubForm
def _prepareSubForm(self, liveForm): """ Utility for turning liveforms into subforms, and compacting them as necessary. @param liveForm: a liveform. @type liveForm: L{LiveForm} @return: a sub form. @rtype: L{LiveForm} """ liveForm = liveForm.asSubForm(self.name) # XXX Why did this work??? # if we are compact, tell the liveform so it can tell its parameters # also if self._parameterIsCompact: liveForm.compact() return liveForm
python
def _prepareSubForm(self, liveForm): """ Utility for turning liveforms into subforms, and compacting them as necessary. @param liveForm: a liveform. @type liveForm: L{LiveForm} @return: a sub form. @rtype: L{LiveForm} """ liveForm = liveForm.asSubForm(self.name) # XXX Why did this work??? # if we are compact, tell the liveform so it can tell its parameters # also if self._parameterIsCompact: liveForm.compact() return liveForm
[ "def", "_prepareSubForm", "(", "self", ",", "liveForm", ")", ":", "liveForm", "=", "liveForm", ".", "asSubForm", "(", "self", ".", "name", ")", "# XXX Why did this work???", "# if we are compact, tell the liveform so it can tell its parameters", "# also", "if", "self", ...
Utility for turning liveforms into subforms, and compacting them as necessary. @param liveForm: a liveform. @type liveForm: L{LiveForm} @return: a sub form. @rtype: L{LiveForm}
[ "Utility", "for", "turning", "liveforms", "into", "subforms", "and", "compacting", "them", "as", "necessary", "." ]
train
https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/liveform.py#L334-L350
twisted/mantissa
xmantissa/liveform.py
ListChangeParameter._cloneDefaultedParameter
def _cloneDefaultedParameter(self, original, default): """ Make a copy of the parameter C{original}, supplying C{default} as the default value. @type original: L{Parameter} or L{ChoiceParameter} @param original: A liveform parameter. @param default: An alternate default value for the parameter. @rtype: L{Parameter} or L{ChoiceParameter} @return: A new parameter. """ if isinstance(original, ChoiceParameter): default = [Option(o.description, o.value, o.value in default) for o in original.choices] return original.clone(default)
python
def _cloneDefaultedParameter(self, original, default): """ Make a copy of the parameter C{original}, supplying C{default} as the default value. @type original: L{Parameter} or L{ChoiceParameter} @param original: A liveform parameter. @param default: An alternate default value for the parameter. @rtype: L{Parameter} or L{ChoiceParameter} @return: A new parameter. """ if isinstance(original, ChoiceParameter): default = [Option(o.description, o.value, o.value in default) for o in original.choices] return original.clone(default)
[ "def", "_cloneDefaultedParameter", "(", "self", ",", "original", ",", "default", ")", ":", "if", "isinstance", "(", "original", ",", "ChoiceParameter", ")", ":", "default", "=", "[", "Option", "(", "o", ".", "description", ",", "o", ".", "value", ",", "o...
Make a copy of the parameter C{original}, supplying C{default} as the default value. @type original: L{Parameter} or L{ChoiceParameter} @param original: A liveform parameter. @param default: An alternate default value for the parameter. @rtype: L{Parameter} or L{ChoiceParameter} @return: A new parameter.
[ "Make", "a", "copy", "of", "the", "parameter", "C", "{", "original", "}", "supplying", "C", "{", "default", "}", "as", "the", "default", "value", "." ]
train
https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/liveform.py#L353-L369
twisted/mantissa
xmantissa/liveform.py
ListChangeParameter._idForObject
def _idForObject(self, defaultObject): """ Generate an opaque identifier which can be used to talk about C{defaultObject}. @rtype: C{int} """ identifier = self._allocateID() self._idsToObjects[identifier] = defaultObject return identifier
python
def _idForObject(self, defaultObject): """ Generate an opaque identifier which can be used to talk about C{defaultObject}. @rtype: C{int} """ identifier = self._allocateID() self._idsToObjects[identifier] = defaultObject return identifier
[ "def", "_idForObject", "(", "self", ",", "defaultObject", ")", ":", "identifier", "=", "self", ".", "_allocateID", "(", ")", "self", ".", "_idsToObjects", "[", "identifier", "]", "=", "defaultObject", "return", "identifier" ]
Generate an opaque identifier which can be used to talk about C{defaultObject}. @rtype: C{int}
[ "Generate", "an", "opaque", "identifier", "which", "can", "be", "used", "to", "talk", "about", "C", "{", "defaultObject", "}", "." ]
train
https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/liveform.py#L383-L392
twisted/mantissa
xmantissa/liveform.py
ListChangeParameter._newIdentifier
def _newIdentifier(self): """ Make a new identifier for an as-yet uncreated model object. @rtype: C{int} """ id = self._allocateID() self._idsToObjects[id] = self._NO_OBJECT_MARKER self._lastValues[id] = None return id
python
def _newIdentifier(self): """ Make a new identifier for an as-yet uncreated model object. @rtype: C{int} """ id = self._allocateID() self._idsToObjects[id] = self._NO_OBJECT_MARKER self._lastValues[id] = None return id
[ "def", "_newIdentifier", "(", "self", ")", ":", "id", "=", "self", ".", "_allocateID", "(", ")", "self", ".", "_idsToObjects", "[", "id", "]", "=", "self", ".", "_NO_OBJECT_MARKER", "self", ".", "_lastValues", "[", "id", "]", "=", "None", "return", "id...
Make a new identifier for an as-yet uncreated model object. @rtype: C{int}
[ "Make", "a", "new", "identifier", "for", "an", "as", "-", "yet", "uncreated", "model", "object", "." ]
train
https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/liveform.py#L404-L413
twisted/mantissa
xmantissa/liveform.py
ListChangeParameter._makeALiveForm
def _makeALiveForm(self, parameters, identifier, removable=True): """ Make a live form with the parameters C{parameters}, which will be used to edit the values/model object with identifier C{identifier}. @type parameters: C{list} @param parameters: list of L{Parameter} instances. @type identifier: C{int} @type removable: C{bool} @rtype: L{repeatedLiveFormWrapper} """ liveForm = self.liveFormFactory(lambda **k: None, parameters, self.name) liveForm = self._prepareSubForm(liveForm) liveForm = self.repeatedLiveFormWrapper(liveForm, identifier, removable) liveForm.docFactory = webtheme.getLoader(liveForm.fragmentName) return liveForm
python
def _makeALiveForm(self, parameters, identifier, removable=True): """ Make a live form with the parameters C{parameters}, which will be used to edit the values/model object with identifier C{identifier}. @type parameters: C{list} @param parameters: list of L{Parameter} instances. @type identifier: C{int} @type removable: C{bool} @rtype: L{repeatedLiveFormWrapper} """ liveForm = self.liveFormFactory(lambda **k: None, parameters, self.name) liveForm = self._prepareSubForm(liveForm) liveForm = self.repeatedLiveFormWrapper(liveForm, identifier, removable) liveForm.docFactory = webtheme.getLoader(liveForm.fragmentName) return liveForm
[ "def", "_makeALiveForm", "(", "self", ",", "parameters", ",", "identifier", ",", "removable", "=", "True", ")", ":", "liveForm", "=", "self", ".", "liveFormFactory", "(", "lambda", "*", "*", "k", ":", "None", ",", "parameters", ",", "self", ".", "name", ...
Make a live form with the parameters C{parameters}, which will be used to edit the values/model object with identifier C{identifier}. @type parameters: C{list} @param parameters: list of L{Parameter} instances. @type identifier: C{int} @type removable: C{bool} @rtype: L{repeatedLiveFormWrapper}
[ "Make", "a", "live", "form", "with", "the", "parameters", "C", "{", "parameters", "}", "which", "will", "be", "used", "to", "edit", "the", "values", "/", "model", "object", "with", "identifier", "C", "{", "identifier", "}", "." ]
train
https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/liveform.py#L416-L434
twisted/mantissa
xmantissa/liveform.py
ListChangeParameter._makeDefaultLiveForm
def _makeDefaultLiveForm(self, (defaults, identifier)): """ Make a liveform suitable for editing the set of default values C{defaults}. @type defaults: C{dict} @param defaults: Mapping of parameter names to values. @rtype: L{repeatedLiveFormWrapper} """ parameters = [self._cloneDefaultedParameter(p, defaults[p.name]) for p in self.parameters] return self._makeALiveForm(parameters, identifier)
python
def _makeDefaultLiveForm(self, (defaults, identifier)): """ Make a liveform suitable for editing the set of default values C{defaults}. @type defaults: C{dict} @param defaults: Mapping of parameter names to values. @rtype: L{repeatedLiveFormWrapper} """ parameters = [self._cloneDefaultedParameter(p, defaults[p.name]) for p in self.parameters] return self._makeALiveForm(parameters, identifier)
[ "def", "_makeDefaultLiveForm", "(", "self", ",", "(", "defaults", ",", "identifier", ")", ")", ":", "parameters", "=", "[", "self", ".", "_cloneDefaultedParameter", "(", "p", ",", "defaults", "[", "p", ".", "name", "]", ")", "for", "p", "in", "self", "...
Make a liveform suitable for editing the set of default values C{defaults}. @type defaults: C{dict} @param defaults: Mapping of parameter names to values. @rtype: L{repeatedLiveFormWrapper}
[ "Make", "a", "liveform", "suitable", "for", "editing", "the", "set", "of", "default", "values", "C", "{", "defaults", "}", "." ]
train
https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/liveform.py#L437-L448
twisted/mantissa
xmantissa/liveform.py
ListChangeParameter.getInitialLiveForms
def getInitialLiveForms(self): """ Make and return as many L{LiveForm} instances as are necessary to hold our default values. @return: some subforms. @rtype: C{list} of L{LiveForm} """ liveForms = [] if self._defaultStuff: for values in self._defaultStuff: liveForms.append(self._makeDefaultLiveForm(values)) else: # or only one, for the first new thing liveForms.append( self._makeALiveForm( self.parameters, self._newIdentifier(), False)) return liveForms
python
def getInitialLiveForms(self): """ Make and return as many L{LiveForm} instances as are necessary to hold our default values. @return: some subforms. @rtype: C{list} of L{LiveForm} """ liveForms = [] if self._defaultStuff: for values in self._defaultStuff: liveForms.append(self._makeDefaultLiveForm(values)) else: # or only one, for the first new thing liveForms.append( self._makeALiveForm( self.parameters, self._newIdentifier(), False)) return liveForms
[ "def", "getInitialLiveForms", "(", "self", ")", ":", "liveForms", "=", "[", "]", "if", "self", ".", "_defaultStuff", ":", "for", "values", "in", "self", ".", "_defaultStuff", ":", "liveForms", ".", "append", "(", "self", ".", "_makeDefaultLiveForm", "(", "...
Make and return as many L{LiveForm} instances as are necessary to hold our default values. @return: some subforms. @rtype: C{list} of L{LiveForm}
[ "Make", "and", "return", "as", "many", "L", "{", "LiveForm", "}", "instances", "as", "are", "necessary", "to", "hold", "our", "default", "values", "." ]
train
https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/liveform.py#L451-L468
twisted/mantissa
xmantissa/liveform.py
ListChangeParameter._coerceSingleRepetition
def _coerceSingleRepetition(self, dataSet): """ Make a new liveform with our parameters, and get it to coerce our data for us. """ # make a liveform because there is some logic in _coerced form = LiveForm(lambda **k: None, self.parameters, self.name) return form.fromInputs(dataSet)
python
def _coerceSingleRepetition(self, dataSet): """ Make a new liveform with our parameters, and get it to coerce our data for us. """ # make a liveform because there is some logic in _coerced form = LiveForm(lambda **k: None, self.parameters, self.name) return form.fromInputs(dataSet)
[ "def", "_coerceSingleRepetition", "(", "self", ",", "dataSet", ")", ":", "# make a liveform because there is some logic in _coerced", "form", "=", "LiveForm", "(", "lambda", "*", "*", "k", ":", "None", ",", "self", ".", "parameters", ",", "self", ".", "name", ")...
Make a new liveform with our parameters, and get it to coerce our data for us.
[ "Make", "a", "new", "liveform", "with", "our", "parameters", "and", "get", "it", "to", "coerce", "our", "data", "for", "us", "." ]
train
https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/liveform.py#L481-L488
twisted/mantissa
xmantissa/liveform.py
ListChangeParameter._extractCreations
def _extractCreations(self, dataSets): """ Find the elements of C{dataSets} which represent the creation of new objects. @param dataSets: C{list} of C{dict} mapping C{unicode} form submission keys to form submission values. @return: iterator of C{tuple}s with the first element giving the opaque identifier of an object which is to be created and the second element giving a C{dict} of all the other creation arguments. """ for dataSet in dataSets: modelObject = self._objectFromID(dataSet[self._IDENTIFIER_KEY]) if modelObject is self._NO_OBJECT_MARKER: dataCopy = dataSet.copy() identifier = dataCopy.pop(self._IDENTIFIER_KEY) yield identifier, dataCopy
python
def _extractCreations(self, dataSets): """ Find the elements of C{dataSets} which represent the creation of new objects. @param dataSets: C{list} of C{dict} mapping C{unicode} form submission keys to form submission values. @return: iterator of C{tuple}s with the first element giving the opaque identifier of an object which is to be created and the second element giving a C{dict} of all the other creation arguments. """ for dataSet in dataSets: modelObject = self._objectFromID(dataSet[self._IDENTIFIER_KEY]) if modelObject is self._NO_OBJECT_MARKER: dataCopy = dataSet.copy() identifier = dataCopy.pop(self._IDENTIFIER_KEY) yield identifier, dataCopy
[ "def", "_extractCreations", "(", "self", ",", "dataSets", ")", ":", "for", "dataSet", "in", "dataSets", ":", "modelObject", "=", "self", ".", "_objectFromID", "(", "dataSet", "[", "self", ".", "_IDENTIFIER_KEY", "]", ")", "if", "modelObject", "is", "self", ...
Find the elements of C{dataSets} which represent the creation of new objects. @param dataSets: C{list} of C{dict} mapping C{unicode} form submission keys to form submission values. @return: iterator of C{tuple}s with the first element giving the opaque identifier of an object which is to be created and the second element giving a C{dict} of all the other creation arguments.
[ "Find", "the", "elements", "of", "C", "{", "dataSets", "}", "which", "represent", "the", "creation", "of", "new", "objects", "." ]
train
https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/liveform.py#L491-L508
twisted/mantissa
xmantissa/liveform.py
ListChangeParameter._coerceAll
def _coerceAll(self, inputs): """ XXX """ def associate(result, obj): return (obj, result) coerceDeferreds = [] for obj, dataSet in inputs: oneCoerce = self._coerceSingleRepetition(dataSet) oneCoerce.addCallback(associate, obj) coerceDeferreds.append(oneCoerce) return gatherResults(coerceDeferreds)
python
def _coerceAll(self, inputs): """ XXX """ def associate(result, obj): return (obj, result) coerceDeferreds = [] for obj, dataSet in inputs: oneCoerce = self._coerceSingleRepetition(dataSet) oneCoerce.addCallback(associate, obj) coerceDeferreds.append(oneCoerce) return gatherResults(coerceDeferreds)
[ "def", "_coerceAll", "(", "self", ",", "inputs", ")", ":", "def", "associate", "(", "result", ",", "obj", ")", ":", "return", "(", "obj", ",", "result", ")", "coerceDeferreds", "=", "[", "]", "for", "obj", ",", "dataSet", "in", "inputs", ":", "oneCoe...
XXX
[ "XXX" ]
train
https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/liveform.py#L531-L543
twisted/mantissa
xmantissa/liveform.py
ListChangeParameter.coercer
def coercer(self, dataSets): """ Coerce all of the repetitions and sort them into creations, edits and deletions. @rtype: L{ListChanges} @return: An object describing all of the creations, modifications, and deletions represented by C{dataSets}. """ # Xxx - This does a slightly complex (hey, it's like 20 lines, how # complex could it really be?) thing to figure out which elements are # newly created, which elements were edited, and which elements no # longer exist. It might be simpler if the client kept track of this # and passed a three-tuple of lists (or whatever - some separate data # structures) to the server, so everything would be all figured out # already. This would require the client # (Mantissa.LiveForm.RepeatableForm) to be more aware of what events # the user is triggering in the browser so that it could keep state for # adds/deletes/edits separately from DOM and widget objects. This # would remove the need for RepeatedLiveFormWrapper. def makeSetter(identifier, values): def setter(defaultObject): self._idsToObjects[identifier] = defaultObject self._lastValues[identifier] = values return setter created = self._coerceAll(self._extractCreations(dataSets)) edited = self._coerceAll(self._extractEdits(dataSets)) coerceDeferred = gatherResults([created, edited]) def cbCoerced((created, edited)): receivedIdentifiers = set() createObjects = [] for (identifier, dataSet) in created: receivedIdentifiers.add(identifier) createObjects.append( CreateObject(dataSet, makeSetter(identifier, dataSet))) editObjects = [] for (identifier, dataSet) in edited: receivedIdentifiers.add(identifier) lastValues = self._lastValues[identifier] if dataSet != lastValues: modelObject = self._objectFromID(identifier) editObjects.append(EditObject(modelObject, dataSet)) self._lastValues[identifier] = dataSet deleted = [] for identifier in set(self._idsToObjects) - receivedIdentifiers: existing = self._objectFromID(identifier) if existing is not self._NO_OBJECT_MARKER: deleted.append(existing) self._idsToObjects.pop(identifier) return ListChanges(createObjects, editObjects, deleted) coerceDeferred.addCallback(cbCoerced) return coerceDeferred
python
def coercer(self, dataSets): """ Coerce all of the repetitions and sort them into creations, edits and deletions. @rtype: L{ListChanges} @return: An object describing all of the creations, modifications, and deletions represented by C{dataSets}. """ # Xxx - This does a slightly complex (hey, it's like 20 lines, how # complex could it really be?) thing to figure out which elements are # newly created, which elements were edited, and which elements no # longer exist. It might be simpler if the client kept track of this # and passed a three-tuple of lists (or whatever - some separate data # structures) to the server, so everything would be all figured out # already. This would require the client # (Mantissa.LiveForm.RepeatableForm) to be more aware of what events # the user is triggering in the browser so that it could keep state for # adds/deletes/edits separately from DOM and widget objects. This # would remove the need for RepeatedLiveFormWrapper. def makeSetter(identifier, values): def setter(defaultObject): self._idsToObjects[identifier] = defaultObject self._lastValues[identifier] = values return setter created = self._coerceAll(self._extractCreations(dataSets)) edited = self._coerceAll(self._extractEdits(dataSets)) coerceDeferred = gatherResults([created, edited]) def cbCoerced((created, edited)): receivedIdentifiers = set() createObjects = [] for (identifier, dataSet) in created: receivedIdentifiers.add(identifier) createObjects.append( CreateObject(dataSet, makeSetter(identifier, dataSet))) editObjects = [] for (identifier, dataSet) in edited: receivedIdentifiers.add(identifier) lastValues = self._lastValues[identifier] if dataSet != lastValues: modelObject = self._objectFromID(identifier) editObjects.append(EditObject(modelObject, dataSet)) self._lastValues[identifier] = dataSet deleted = [] for identifier in set(self._idsToObjects) - receivedIdentifiers: existing = self._objectFromID(identifier) if existing is not self._NO_OBJECT_MARKER: deleted.append(existing) self._idsToObjects.pop(identifier) return ListChanges(createObjects, editObjects, deleted) coerceDeferred.addCallback(cbCoerced) return coerceDeferred
[ "def", "coercer", "(", "self", ",", "dataSets", ")", ":", "# Xxx - This does a slightly complex (hey, it's like 20 lines, how", "# complex could it really be?) thing to figure out which elements are", "# newly created, which elements were edited, and which elements no", "# longer exist. It mi...
Coerce all of the repetitions and sort them into creations, edits and deletions. @rtype: L{ListChanges} @return: An object describing all of the creations, modifications, and deletions represented by C{dataSets}.
[ "Coerce", "all", "of", "the", "repetitions", "and", "sort", "them", "into", "creations", "edits", "and", "deletions", "." ]
train
https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/liveform.py#L546-L604
twisted/mantissa
xmantissa/liveform.py
ListParameter.fromInputs
def fromInputs(self, inputs): """ Extract the inputs associated with this parameter from the given dictionary and coerce them using C{self.coercer}. @type inputs: C{dict} mapping C{str} to C{list} of C{str} @param inputs: The contents of a form post, in the conventional structure. @rtype: L{Deferred} @return: A Deferred which will be called back with a list of the structured data associated with this parameter. """ outputs = [] for i in xrange(self.count): name = self.name + '_' + str(i) try: value = inputs[name][0] except KeyError: raise ConfigurationError( "Missing value for field %d of %s" % (i, self.name)) else: outputs.append(maybeDeferred(self.coercer, value)) return gatherResults(outputs)
python
def fromInputs(self, inputs): """ Extract the inputs associated with this parameter from the given dictionary and coerce them using C{self.coercer}. @type inputs: C{dict} mapping C{str} to C{list} of C{str} @param inputs: The contents of a form post, in the conventional structure. @rtype: L{Deferred} @return: A Deferred which will be called back with a list of the structured data associated with this parameter. """ outputs = [] for i in xrange(self.count): name = self.name + '_' + str(i) try: value = inputs[name][0] except KeyError: raise ConfigurationError( "Missing value for field %d of %s" % (i, self.name)) else: outputs.append(maybeDeferred(self.coercer, value)) return gatherResults(outputs)
[ "def", "fromInputs", "(", "self", ",", "inputs", ")", ":", "outputs", "=", "[", "]", "for", "i", "in", "xrange", "(", "self", ".", "count", ")", ":", "name", "=", "self", ".", "name", "+", "'_'", "+", "str", "(", "i", ")", "try", ":", "value", ...
Extract the inputs associated with this parameter from the given dictionary and coerce them using C{self.coercer}. @type inputs: C{dict} mapping C{str} to C{list} of C{str} @param inputs: The contents of a form post, in the conventional structure. @rtype: L{Deferred} @return: A Deferred which will be called back with a list of the structured data associated with this parameter.
[ "Extract", "the", "inputs", "associated", "with", "this", "parameter", "from", "the", "given", "dictionary", "and", "coerce", "them", "using", "C", "{", "self", ".", "coercer", "}", "." ]
train
https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/liveform.py#L624-L647
twisted/mantissa
xmantissa/liveform.py
ChoiceParameter.clone
def clone(self, choices): """ Make a copy of this parameter, supply different choices. @param choices: A sequence of L{Option} instances. @type choices: C{list} @rtype: L{ChoiceParameter} """ return self.__class__( self.name, choices, self.label, self.description, self.multiple, self.viewFactory)
python
def clone(self, choices): """ Make a copy of this parameter, supply different choices. @param choices: A sequence of L{Option} instances. @type choices: C{list} @rtype: L{ChoiceParameter} """ return self.__class__( self.name, choices, self.label, self.description, self.multiple, self.viewFactory)
[ "def", "clone", "(", "self", ",", "choices", ")", ":", "return", "self", ".", "__class__", "(", "self", ".", "name", ",", "choices", ",", "self", ".", "label", ",", "self", ".", "description", ",", "self", ".", "multiple", ",", "self", ".", "viewFact...
Make a copy of this parameter, supply different choices. @param choices: A sequence of L{Option} instances. @type choices: C{list} @rtype: L{ChoiceParameter}
[ "Make", "a", "copy", "of", "this", "parameter", "supply", "different", "choices", "." ]
train
https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/liveform.py#L712-L727
twisted/mantissa
xmantissa/liveform.py
_LiveFormMixin.compact
def compact(self): """ Switch to the compact variant of the live form template. By default, this will simply create a loader for the C{self.compactFragmentName} template and compact all of this form's parameters. """ self.docFactory = webtheme.getLoader(self.compactFragmentName) for param in self.parameters: param.compact()
python
def compact(self): """ Switch to the compact variant of the live form template. By default, this will simply create a loader for the C{self.compactFragmentName} template and compact all of this form's parameters. """ self.docFactory = webtheme.getLoader(self.compactFragmentName) for param in self.parameters: param.compact()
[ "def", "compact", "(", "self", ")", ":", "self", ".", "docFactory", "=", "webtheme", ".", "getLoader", "(", "self", ".", "compactFragmentName", ")", "for", "param", "in", "self", ".", "parameters", ":", "param", ".", "compact", "(", ")" ]
Switch to the compact variant of the live form template. By default, this will simply create a loader for the C{self.compactFragmentName} template and compact all of this form's parameters.
[ "Switch", "to", "the", "compact", "variant", "of", "the", "live", "form", "template", "." ]
train
https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/liveform.py#L825-L835
twisted/mantissa
xmantissa/liveform.py
_LiveFormMixin.asSubForm
def asSubForm(self, name): """ Make a form suitable for nesting within another form (a subform) out of this top-level liveform. @param name: the name of the subform within its parent. @type name: C{unicode} @return: a subform. @rtype: L{LiveForm} """ self.subFormName = name self.jsClass = _SUBFORM_JS_CLASS return self
python
def asSubForm(self, name): """ Make a form suitable for nesting within another form (a subform) out of this top-level liveform. @param name: the name of the subform within its parent. @type name: C{unicode} @return: a subform. @rtype: L{LiveForm} """ self.subFormName = name self.jsClass = _SUBFORM_JS_CLASS return self
[ "def", "asSubForm", "(", "self", ",", "name", ")", ":", "self", ".", "subFormName", "=", "name", "self", ".", "jsClass", "=", "_SUBFORM_JS_CLASS", "return", "self" ]
Make a form suitable for nesting within another form (a subform) out of this top-level liveform. @param name: the name of the subform within its parent. @type name: C{unicode} @return: a subform. @rtype: L{LiveForm}
[ "Make", "a", "form", "suitable", "for", "nesting", "within", "another", "form", "(", "a", "subform", ")", "out", "of", "this", "top", "-", "level", "liveform", "." ]
train
https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/liveform.py#L846-L859
twisted/mantissa
xmantissa/liveform.py
_LiveFormMixin.submitbutton
def submitbutton(self, request, tag): """ Render an INPUT element of type SUBMIT which will post this form to the server. """ return tags.input(type='submit', name='__submit__', value=self._getDescription())
python
def submitbutton(self, request, tag): """ Render an INPUT element of type SUBMIT which will post this form to the server. """ return tags.input(type='submit', name='__submit__', value=self._getDescription())
[ "def", "submitbutton", "(", "self", ",", "request", ",", "tag", ")", ":", "return", "tags", ".", "input", "(", "type", "=", "'submit'", ",", "name", "=", "'__submit__'", ",", "value", "=", "self", ".", "_getDescription", "(", ")", ")" ]
Render an INPUT element of type SUBMIT which will post this form to the server.
[ "Render", "an", "INPUT", "element", "of", "type", "SUBMIT", "which", "will", "post", "this", "form", "to", "the", "server", "." ]
train
https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/liveform.py#L869-L876
twisted/mantissa
xmantissa/liveform.py
_LiveFormMixin.form
def form(self, request, tag): """ Render the inputs for a form. @param tag: A tag with: - I{form} and I{description} slots - I{liveform} and I{subform} patterns, to fill the I{form} slot - An I{inputs} slot, to fill with parameter views - L{IParameterView.patternName}I{-input-container} patterns for each parameter type in C{self.parameters} """ patterns = PatternDictionary(self.docFactory) inputs = [] for parameter in self.parameters: view = parameter.viewFactory(parameter, None) if view is not None: view.setDefaultTemplate( tag.onePattern(view.patternName + '-input-container')) setFragmentParent = getattr(view, 'setFragmentParent', None) if setFragmentParent is not None: setFragmentParent(self) inputs.append(view) else: inputs.append(_legacySpecialCases(self, patterns, parameter)) if self.subFormName is None: pattern = tag.onePattern('liveform') else: pattern = tag.onePattern('subform') return dictFillSlots( tag, dict(form=pattern.fillSlots('inputs', inputs), description=self._getDescription()))
python
def form(self, request, tag): """ Render the inputs for a form. @param tag: A tag with: - I{form} and I{description} slots - I{liveform} and I{subform} patterns, to fill the I{form} slot - An I{inputs} slot, to fill with parameter views - L{IParameterView.patternName}I{-input-container} patterns for each parameter type in C{self.parameters} """ patterns = PatternDictionary(self.docFactory) inputs = [] for parameter in self.parameters: view = parameter.viewFactory(parameter, None) if view is not None: view.setDefaultTemplate( tag.onePattern(view.patternName + '-input-container')) setFragmentParent = getattr(view, 'setFragmentParent', None) if setFragmentParent is not None: setFragmentParent(self) inputs.append(view) else: inputs.append(_legacySpecialCases(self, patterns, parameter)) if self.subFormName is None: pattern = tag.onePattern('liveform') else: pattern = tag.onePattern('subform') return dictFillSlots( tag, dict(form=pattern.fillSlots('inputs', inputs), description=self._getDescription()))
[ "def", "form", "(", "self", ",", "request", ",", "tag", ")", ":", "patterns", "=", "PatternDictionary", "(", "self", ".", "docFactory", ")", "inputs", "=", "[", "]", "for", "parameter", "in", "self", ".", "parameters", ":", "view", "=", "parameter", "....
Render the inputs for a form. @param tag: A tag with: - I{form} and I{description} slots - I{liveform} and I{subform} patterns, to fill the I{form} slot - An I{inputs} slot, to fill with parameter views - L{IParameterView.patternName}I{-input-container} patterns for each parameter type in C{self.parameters}
[ "Render", "the", "inputs", "for", "a", "form", "." ]
train
https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/liveform.py#L888-L922
twisted/mantissa
xmantissa/liveform.py
_LiveFormMixin.invoke
def invoke(self, formPostEmulator): """ Invoke my callable with input from the browser. @param formPostEmulator: a dict of lists of strings in a format like a cgi-module form post. """ result = self.fromInputs(formPostEmulator) result.addCallback(lambda params: self.callable(**params)) return result
python
def invoke(self, formPostEmulator): """ Invoke my callable with input from the browser. @param formPostEmulator: a dict of lists of strings in a format like a cgi-module form post. """ result = self.fromInputs(formPostEmulator) result.addCallback(lambda params: self.callable(**params)) return result
[ "def", "invoke", "(", "self", ",", "formPostEmulator", ")", ":", "result", "=", "self", ".", "fromInputs", "(", "formPostEmulator", ")", "result", ".", "addCallback", "(", "lambda", "params", ":", "self", ".", "callable", "(", "*", "*", "params", ")", ")...
Invoke my callable with input from the browser. @param formPostEmulator: a dict of lists of strings in a format like a cgi-module form post.
[ "Invoke", "my", "callable", "with", "input", "from", "the", "browser", "." ]
train
https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/liveform.py#L930-L939
twisted/mantissa
xmantissa/liveform.py
_LiveFormMixin.fromInputs
def fromInputs(self, received): """ Convert some random strings received from a browser into structured data, using a list of parameters. @param received: a dict of lists of strings, i.e. the canonical Python form of web form post. @rtype: L{Deferred} @return: A Deferred which will be called back with a dict mapping parameter names to coerced parameter values. """ results = [] for parameter in self.parameters: name = parameter.name.encode('ascii') d = maybeDeferred(parameter.fromInputs, received) d.addCallback(lambda value, name=name: (name, value)) results.append(d) return gatherResults(results).addCallback(dict)
python
def fromInputs(self, received): """ Convert some random strings received from a browser into structured data, using a list of parameters. @param received: a dict of lists of strings, i.e. the canonical Python form of web form post. @rtype: L{Deferred} @return: A Deferred which will be called back with a dict mapping parameter names to coerced parameter values. """ results = [] for parameter in self.parameters: name = parameter.name.encode('ascii') d = maybeDeferred(parameter.fromInputs, received) d.addCallback(lambda value, name=name: (name, value)) results.append(d) return gatherResults(results).addCallback(dict)
[ "def", "fromInputs", "(", "self", ",", "received", ")", ":", "results", "=", "[", "]", "for", "parameter", "in", "self", ".", "parameters", ":", "name", "=", "parameter", ".", "name", ".", "encode", "(", "'ascii'", ")", "d", "=", "maybeDeferred", "(", ...
Convert some random strings received from a browser into structured data, using a list of parameters. @param received: a dict of lists of strings, i.e. the canonical Python form of web form post. @rtype: L{Deferred} @return: A Deferred which will be called back with a dict mapping parameter names to coerced parameter values.
[ "Convert", "some", "random", "strings", "received", "from", "a", "browser", "into", "structured", "data", "using", "a", "list", "of", "parameters", "." ]
train
https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/liveform.py#L952-L970
twisted/mantissa
xmantissa/liveform.py
_ParameterViewMixin.label
def label(self, request, tag): """ Render the label of the wrapped L{Parameter} or L{ChoiceParameter} instance. """ if self.parameter.label: tag[self.parameter.label] return tag
python
def label(self, request, tag): """ Render the label of the wrapped L{Parameter} or L{ChoiceParameter} instance. """ if self.parameter.label: tag[self.parameter.label] return tag
[ "def", "label", "(", "self", ",", "request", ",", "tag", ")", ":", "if", "self", ".", "parameter", ".", "label", ":", "tag", "[", "self", ".", "parameter", ".", "label", "]", "return", "tag" ]
Render the label of the wrapped L{Parameter} or L{ChoiceParameter} instance.
[ "Render", "the", "label", "of", "the", "wrapped", "L", "{", "Parameter", "}", "or", "L", "{", "ChoiceParameter", "}", "instance", "." ]
train
https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/liveform.py#L1045-L1051
twisted/mantissa
xmantissa/liveform.py
_ParameterViewMixin.description
def description(self, request, tag): """ Render the description of the wrapped L{Parameter} instance. """ if self.parameter.description is not None: tag[self.parameter.description] return tag
python
def description(self, request, tag): """ Render the description of the wrapped L{Parameter} instance. """ if self.parameter.description is not None: tag[self.parameter.description] return tag
[ "def", "description", "(", "self", ",", "request", ",", "tag", ")", ":", "if", "self", ".", "parameter", ".", "description", "is", "not", "None", ":", "tag", "[", "self", ".", "parameter", ".", "description", "]", "return", "tag" ]
Render the description of the wrapped L{Parameter} instance.
[ "Render", "the", "description", "of", "the", "wrapped", "L", "{", "Parameter", "}", "instance", "." ]
train
https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/liveform.py#L1055-L1061
twisted/mantissa
xmantissa/liveform.py
RepeatedLiveFormWrapper.realForm
def realForm(self, req, tag): """ Render L{liveForm}. """ self.liveForm.setFragmentParent(self) return self.liveForm
python
def realForm(self, req, tag): """ Render L{liveForm}. """ self.liveForm.setFragmentParent(self) return self.liveForm
[ "def", "realForm", "(", "self", ",", "req", ",", "tag", ")", ":", "self", ".", "liveForm", ".", "setFragmentParent", "(", "self", ")", "return", "self", ".", "liveForm" ]
Render L{liveForm}.
[ "Render", "L", "{", "liveForm", "}", "." ]
train
https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/liveform.py#L1097-L1102
twisted/mantissa
xmantissa/liveform.py
_TextLikeParameterView.default
def default(self, request, tag): """ Render the initial value of the wrapped L{Parameter} instance. """ if self.parameter.default is not None: tag[self.parameter.default] return tag
python
def default(self, request, tag): """ Render the initial value of the wrapped L{Parameter} instance. """ if self.parameter.default is not None: tag[self.parameter.default] return tag
[ "def", "default", "(", "self", ",", "request", ",", "tag", ")", ":", "if", "self", ".", "parameter", ".", "default", "is", "not", "None", ":", "tag", "[", "self", ".", "parameter", ".", "default", "]", "return", "tag" ]
Render the initial value of the wrapped L{Parameter} instance.
[ "Render", "the", "initial", "value", "of", "the", "wrapped", "L", "{", "Parameter", "}", "instance", "." ]
train
https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/liveform.py#L1123-L1129
twisted/mantissa
xmantissa/liveform.py
OptionView.selected
def selected(self, request, tag): """ Render a selected attribute on the given tag if the wrapped L{Option} instance is selected. """ if self.option.selected: tag(selected='selected') return tag
python
def selected(self, request, tag): """ Render a selected attribute on the given tag if the wrapped L{Option} instance is selected. """ if self.option.selected: tag(selected='selected') return tag
[ "def", "selected", "(", "self", ",", "request", ",", "tag", ")", ":", "if", "self", ".", "option", ".", "selected", ":", "tag", "(", "selected", "=", "'selected'", ")", "return", "tag" ]
Render a selected attribute on the given tag if the wrapped L{Option} instance is selected.
[ "Render", "a", "selected", "attribute", "on", "the", "given", "tag", "if", "the", "wrapped", "L", "{", "Option", "}", "instance", "is", "selected", "." ]
train
https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/liveform.py#L1205-L1212
twisted/mantissa
xmantissa/liveform.py
ChoiceParameterView.multiple
def multiple(self, request, tag): """ Render a I{multiple} attribute on the given tag if the wrapped L{ChoiceParameter} instance allows multiple selection. """ if self.parameter.multiple: tag(multiple='multiple') return tag
python
def multiple(self, request, tag): """ Render a I{multiple} attribute on the given tag if the wrapped L{ChoiceParameter} instance allows multiple selection. """ if self.parameter.multiple: tag(multiple='multiple') return tag
[ "def", "multiple", "(", "self", ",", "request", ",", "tag", ")", ":", "if", "self", ".", "parameter", ".", "multiple", ":", "tag", "(", "multiple", "=", "'multiple'", ")", "return", "tag" ]
Render a I{multiple} attribute on the given tag if the wrapped L{ChoiceParameter} instance allows multiple selection.
[ "Render", "a", "I", "{", "multiple", "}", "attribute", "on", "the", "given", "tag", "if", "the", "wrapped", "L", "{", "ChoiceParameter", "}", "instance", "allows", "multiple", "selection", "." ]
train
https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/liveform.py#L1240-L1247
twisted/mantissa
xmantissa/liveform.py
ChoiceParameterView.options
def options(self, request, tag): """ Render each of the options of the wrapped L{ChoiceParameter} instance. """ option = tag.patternGenerator('option') return tag[[ OptionView(index, o, option()) for (index, o) in enumerate(self.parameter.choices)]]
python
def options(self, request, tag): """ Render each of the options of the wrapped L{ChoiceParameter} instance. """ option = tag.patternGenerator('option') return tag[[ OptionView(index, o, option()) for (index, o) in enumerate(self.parameter.choices)]]
[ "def", "options", "(", "self", ",", "request", ",", "tag", ")", ":", "option", "=", "tag", ".", "patternGenerator", "(", "'option'", ")", "return", "tag", "[", "[", "OptionView", "(", "index", ",", "o", ",", "option", "(", ")", ")", "for", "(", "in...
Render each of the options of the wrapped L{ChoiceParameter} instance.
[ "Render", "each", "of", "the", "options", "of", "the", "wrapped", "L", "{", "ChoiceParameter", "}", "instance", "." ]
train
https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/liveform.py#L1251-L1259
twisted/mantissa
xmantissa/liveform.py
ListChangeParameterView.forms
def forms(self, req, tag): """ Make and return some forms, using L{self.parameter.getInitialLiveForms}. @return: some subforms. @rtype: C{list} of L{LiveForm} """ liveForms = self.parameter.getInitialLiveForms() for liveForm in liveForms: liveForm.setFragmentParent(self) return liveForms
python
def forms(self, req, tag): """ Make and return some forms, using L{self.parameter.getInitialLiveForms}. @return: some subforms. @rtype: C{list} of L{LiveForm} """ liveForms = self.parameter.getInitialLiveForms() for liveForm in liveForms: liveForm.setFragmentParent(self) return liveForms
[ "def", "forms", "(", "self", ",", "req", ",", "tag", ")", ":", "liveForms", "=", "self", ".", "parameter", ".", "getInitialLiveForms", "(", ")", "for", "liveForm", "in", "liveForms", ":", "liveForm", ".", "setFragmentParent", "(", "self", ")", "return", ...
Make and return some forms, using L{self.parameter.getInitialLiveForms}. @return: some subforms. @rtype: C{list} of L{LiveForm}
[ "Make", "and", "return", "some", "forms", "using", "L", "{", "self", ".", "parameter", ".", "getInitialLiveForms", "}", "." ]
train
https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/liveform.py#L1288-L1298
twisted/mantissa
xmantissa/liveform.py
ListChangeParameterView.repeatForm
def repeatForm(self): """ Make and return a form, using L{self.parameter.asLiveForm}. @return: a subform. @rtype: L{LiveForm} """ liveForm = self.parameter.asLiveForm() liveForm.setFragmentParent(self) return liveForm
python
def repeatForm(self): """ Make and return a form, using L{self.parameter.asLiveForm}. @return: a subform. @rtype: L{LiveForm} """ liveForm = self.parameter.asLiveForm() liveForm.setFragmentParent(self) return liveForm
[ "def", "repeatForm", "(", "self", ")", ":", "liveForm", "=", "self", ".", "parameter", ".", "asLiveForm", "(", ")", "liveForm", ".", "setFragmentParent", "(", "self", ")", "return", "liveForm" ]
Make and return a form, using L{self.parameter.asLiveForm}. @return: a subform. @rtype: L{LiveForm}
[ "Make", "and", "return", "a", "form", "using", "L", "{", "self", ".", "parameter", ".", "asLiveForm", "}", "." ]
train
https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/liveform.py#L1302-L1311
twisted/mantissa
xmantissa/liveform.py
ListChangeParameterView.repeater
def repeater(self, req, tag): """ Render some UI for repeating our form. """ repeater = inevow.IQ(self.docFactory).onePattern('repeater') return repeater.fillSlots( 'object-description', self.parameter.modelObjectDescription)
python
def repeater(self, req, tag): """ Render some UI for repeating our form. """ repeater = inevow.IQ(self.docFactory).onePattern('repeater') return repeater.fillSlots( 'object-description', self.parameter.modelObjectDescription)
[ "def", "repeater", "(", "self", ",", "req", ",", "tag", ")", ":", "repeater", "=", "inevow", ".", "IQ", "(", "self", ".", "docFactory", ")", ".", "onePattern", "(", "'repeater'", ")", "return", "repeater", ".", "fillSlots", "(", "'object-description'", "...
Render some UI for repeating our form.
[ "Render", "some", "UI", "for", "repeating", "our", "form", "." ]
train
https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/liveform.py#L1315-L1321
twisted/mantissa
xmantissa/liveform.py
FormParameterView.input
def input(self, request, tag): """ Add the wrapped form, as a subform, as a child of the given tag. """ subform = self.parameter.form.asSubForm(self.parameter.name) subform.setFragmentParent(self) return tag[subform]
python
def input(self, request, tag): """ Add the wrapped form, as a subform, as a child of the given tag. """ subform = self.parameter.form.asSubForm(self.parameter.name) subform.setFragmentParent(self) return tag[subform]
[ "def", "input", "(", "self", ",", "request", ",", "tag", ")", ":", "subform", "=", "self", ".", "parameter", ".", "form", ".", "asSubForm", "(", "self", ".", "parameter", ".", "name", ")", "subform", ".", "setFragmentParent", "(", "self", ")", "return"...
Add the wrapped form, as a subform, as a child of the given tag.
[ "Add", "the", "wrapped", "form", "as", "a", "subform", "as", "a", "child", "of", "the", "given", "tag", "." ]
train
https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/liveform.py#L1343-L1349
KeplerGO/K2fov
K2fov/definefov.py
generateVectors
def generateVectors(): """Convert the known ra/decs of the channel corners into unit vectors. This code creates the conents of the function loadOriginVectors() (below) """ ra_deg = 290.66666667 dec_deg = +44.5 #rollAngle_deg = 33.0 rollAngle_deg = +123. boresight = r.vecFromRaDec(ra_deg, dec_deg) #Read in prime mission coords and convert to vectors inFile = "../etc/fov.txt" inFile = np.loadtxt(inFile) radecs = np.zeros( (len(inFile), 3)) rotate = radecs*0 for i, row in enumerate(inFile): radecs[i, :] = r.vecFromRaDec(inFile[i, 4], inFile[i,5]) rotate[i, :] = r.rotateAroundVector(radecs[i], boresight,\ -rollAngle_deg) #Slew to ra/dec of zero Ra = r.rightAscensionRotationMatrix(-ra_deg) Rd = r.declinationRotationMatrix(-dec_deg) R = np.dot(Rd, Ra) origin = rotate*0 for i, row in enumerate(rotate): origin[i] = np.dot(R, rotate[i]) mp.plot(origin[:,0], origin[:,1]) #Print out the results #import pdb; pdb.set_trace() print("[") for i in range(len(inFile)): ch = channelFromModOut(inFile[i,0], inFile[i,1]) print("[%3i., %3i., %3i., %13.7f, %13.7f, %13.7f], \\" %( \ inFile[i, 0], inFile[i, 1], ch, \ origin[i, 0], origin[i, 1], origin[i,2])) print("]")
python
def generateVectors(): """Convert the known ra/decs of the channel corners into unit vectors. This code creates the conents of the function loadOriginVectors() (below) """ ra_deg = 290.66666667 dec_deg = +44.5 #rollAngle_deg = 33.0 rollAngle_deg = +123. boresight = r.vecFromRaDec(ra_deg, dec_deg) #Read in prime mission coords and convert to vectors inFile = "../etc/fov.txt" inFile = np.loadtxt(inFile) radecs = np.zeros( (len(inFile), 3)) rotate = radecs*0 for i, row in enumerate(inFile): radecs[i, :] = r.vecFromRaDec(inFile[i, 4], inFile[i,5]) rotate[i, :] = r.rotateAroundVector(radecs[i], boresight,\ -rollAngle_deg) #Slew to ra/dec of zero Ra = r.rightAscensionRotationMatrix(-ra_deg) Rd = r.declinationRotationMatrix(-dec_deg) R = np.dot(Rd, Ra) origin = rotate*0 for i, row in enumerate(rotate): origin[i] = np.dot(R, rotate[i]) mp.plot(origin[:,0], origin[:,1]) #Print out the results #import pdb; pdb.set_trace() print("[") for i in range(len(inFile)): ch = channelFromModOut(inFile[i,0], inFile[i,1]) print("[%3i., %3i., %3i., %13.7f, %13.7f, %13.7f], \\" %( \ inFile[i, 0], inFile[i, 1], ch, \ origin[i, 0], origin[i, 1], origin[i,2])) print("]")
[ "def", "generateVectors", "(", ")", ":", "ra_deg", "=", "290.66666667", "dec_deg", "=", "+", "44.5", "#rollAngle_deg = 33.0", "rollAngle_deg", "=", "+", "123.", "boresight", "=", "r", ".", "vecFromRaDec", "(", "ra_deg", ",", "dec_deg", ")", "#Read in prime missi...
Convert the known ra/decs of the channel corners into unit vectors. This code creates the conents of the function loadOriginVectors() (below)
[ "Convert", "the", "known", "ra", "/", "decs", "of", "the", "channel", "corners", "into", "unit", "vectors", ".", "This", "code", "creates", "the", "conents", "of", "the", "function", "loadOriginVectors", "()", "(", "below", ")" ]
train
https://github.com/KeplerGO/K2fov/blob/fb122b35687340e0357cba9e0dd47b3be0760693/K2fov/definefov.py#L10-L53
rmed/pyemtmad
pyemtmad/api/geo.py
GeoApi.get_arrive_stop
def get_arrive_stop(self, **kwargs): """Obtain bus arrival info in target stop. Args: stop_number (int): Stop number to query. lang (str): Language code (*es* or *en*). Returns: Status boolean and parsed response (list[Arrival]), or message string in case of error. """ # Endpoint parameters params = { 'idStop': kwargs.get('stop_number'), 'cultureInfo': util.language_code(kwargs.get('lang')) } # Request result = self.make_request('geo', 'get_arrive_stop', **params) # Funny endpoint, no status code if not util.check_result(result, 'arrives'): return False, 'UNKNOWN ERROR' # Parse values = util.response_list(result, 'arrives') return True, [emtype.Arrival(**a) for a in values]
python
def get_arrive_stop(self, **kwargs): """Obtain bus arrival info in target stop. Args: stop_number (int): Stop number to query. lang (str): Language code (*es* or *en*). Returns: Status boolean and parsed response (list[Arrival]), or message string in case of error. """ # Endpoint parameters params = { 'idStop': kwargs.get('stop_number'), 'cultureInfo': util.language_code(kwargs.get('lang')) } # Request result = self.make_request('geo', 'get_arrive_stop', **params) # Funny endpoint, no status code if not util.check_result(result, 'arrives'): return False, 'UNKNOWN ERROR' # Parse values = util.response_list(result, 'arrives') return True, [emtype.Arrival(**a) for a in values]
[ "def", "get_arrive_stop", "(", "self", ",", "*", "*", "kwargs", ")", ":", "# Endpoint parameters", "params", "=", "{", "'idStop'", ":", "kwargs", ".", "get", "(", "'stop_number'", ")", ",", "'cultureInfo'", ":", "util", ".", "language_code", "(", "kwargs", ...
Obtain bus arrival info in target stop. Args: stop_number (int): Stop number to query. lang (str): Language code (*es* or *en*). Returns: Status boolean and parsed response (list[Arrival]), or message string in case of error.
[ "Obtain", "bus", "arrival", "info", "in", "target", "stop", "." ]
train
https://github.com/rmed/pyemtmad/blob/c21c42d0c7b50035dfed29540d7e64ab67833728/pyemtmad/api/geo.py#L39-L65
rmed/pyemtmad
pyemtmad/api/geo.py
GeoApi.get_groups
def get_groups(self, **kwargs): """Obtain line types and details. Args: lang (str): Language code (*es* or *en*). Returns: Status boolean and parsed response (list[GeoGroupItem]), or message string in case of error. """ # Endpoint parameters params = { 'cultureInfo': util.language_code(kwargs.get('lang')) } # Request result = self.make_request('geo', 'get_groups', **params) if not util.check_result(result): return False, result.get('resultDescription', 'UNKNOWN ERROR') # Parse values = util.response_list(result, 'resultValues') return True, [emtype.GeoGroupItem(**a) for a in values]
python
def get_groups(self, **kwargs): """Obtain line types and details. Args: lang (str): Language code (*es* or *en*). Returns: Status boolean and parsed response (list[GeoGroupItem]), or message string in case of error. """ # Endpoint parameters params = { 'cultureInfo': util.language_code(kwargs.get('lang')) } # Request result = self.make_request('geo', 'get_groups', **params) if not util.check_result(result): return False, result.get('resultDescription', 'UNKNOWN ERROR') # Parse values = util.response_list(result, 'resultValues') return True, [emtype.GeoGroupItem(**a) for a in values]
[ "def", "get_groups", "(", "self", ",", "*", "*", "kwargs", ")", ":", "# Endpoint parameters", "params", "=", "{", "'cultureInfo'", ":", "util", ".", "language_code", "(", "kwargs", ".", "get", "(", "'lang'", ")", ")", "}", "# Request", "result", "=", "se...
Obtain line types and details. Args: lang (str): Language code (*es* or *en*). Returns: Status boolean and parsed response (list[GeoGroupItem]), or message string in case of error.
[ "Obtain", "line", "types", "and", "details", "." ]
train
https://github.com/rmed/pyemtmad/blob/c21c42d0c7b50035dfed29540d7e64ab67833728/pyemtmad/api/geo.py#L67-L90