repository_name
stringlengths
7
55
func_path_in_repository
stringlengths
4
223
func_name
stringlengths
1
134
whole_func_string
stringlengths
75
104k
language
stringclasses
1 value
func_code_string
stringlengths
75
104k
func_code_tokens
listlengths
19
28.4k
func_documentation_string
stringlengths
1
46.9k
func_documentation_tokens
listlengths
1
1.97k
split_name
stringclasses
1 value
func_code_url
stringlengths
87
315
benoitguigal/python-epson-printer
epson_printer/epsonprinter.py
EpsonPrinter.write_this
def write_this(func): """ Decorator that writes the bytes to the wire """ @wraps(func) def wrapper(self, *args, **kwargs): byte_array = func(self, *args, **kwargs) self.write_bytes(byte_array) return wrapper
python
def write_this(func): """ Decorator that writes the bytes to the wire """ @wraps(func) def wrapper(self, *args, **kwargs): byte_array = func(self, *args, **kwargs) self.write_bytes(byte_array) return wrapper
[ "def", "write_this", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "wrapper", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "byte_array", "=", "func", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", "...
Decorator that writes the bytes to the wire
[ "Decorator", "that", "writes", "the", "bytes", "to", "the", "wire" ]
train
https://github.com/benoitguigal/python-epson-printer/blob/7d89b2f21bc76d2cc4d5ad548e19a356ca92fbc5/epson_printer/epsonprinter.py#L199-L207
benoitguigal/python-epson-printer
epson_printer/epsonprinter.py
EpsonPrinter.print_images
def print_images(self, *printable_images): """ This method allows printing several images in one shot. This is useful if the client code does not want the printer to make pause during printing """ printable_image = reduce(lambda x, y: x.append(y), list(printable_images)) ...
python
def print_images(self, *printable_images): """ This method allows printing several images in one shot. This is useful if the client code does not want the printer to make pause during printing """ printable_image = reduce(lambda x, y: x.append(y), list(printable_images)) ...
[ "def", "print_images", "(", "self", ",", "*", "printable_images", ")", ":", "printable_image", "=", "reduce", "(", "lambda", "x", ",", "y", ":", "x", ".", "append", "(", "y", ")", ",", "list", "(", "printable_images", ")", ")", "self", ".", "print_imag...
This method allows printing several images in one shot. This is useful if the client code does not want the printer to make pause during printing
[ "This", "method", "allows", "printing", "several", "images", "in", "one", "shot", ".", "This", "is", "useful", "if", "the", "client", "code", "does", "not", "want", "the", "printer", "to", "make", "pause", "during", "printing" ]
train
https://github.com/benoitguigal/python-epson-printer/blob/7d89b2f21bc76d2cc4d5ad548e19a356ca92fbc5/epson_printer/epsonprinter.py#L258-L264
podio/podio-py
pypodio2/encode.py
encode_and_quote
def encode_and_quote(data): """If ``data`` is unicode, return urllib.quote_plus(data.encode("utf-8")) otherwise return urllib.quote_plus(data)""" if data is None: return None if isinstance(data, unicode): data = data.encode("utf-8") return urllib.quote_plus(data)
python
def encode_and_quote(data): """If ``data`` is unicode, return urllib.quote_plus(data.encode("utf-8")) otherwise return urllib.quote_plus(data)""" if data is None: return None if isinstance(data, unicode): data = data.encode("utf-8") return urllib.quote_plus(data)
[ "def", "encode_and_quote", "(", "data", ")", ":", "if", "data", "is", "None", ":", "return", "None", "if", "isinstance", "(", "data", ",", "unicode", ")", ":", "data", "=", "data", ".", "encode", "(", "\"utf-8\"", ")", "return", "urllib", ".", "quote_p...
If ``data`` is unicode, return urllib.quote_plus(data.encode("utf-8")) otherwise return urllib.quote_plus(data)
[ "If", "data", "is", "unicode", "return", "urllib", ".", "quote_plus", "(", "data", ".", "encode", "(", "utf", "-", "8", "))", "otherwise", "return", "urllib", ".", "quote_plus", "(", "data", ")" ]
train
https://github.com/podio/podio-py/blob/5ce956034a06c98b0ef18fcd940b36da0908ad6c/pypodio2/encode.py#L41-L49
podio/podio-py
pypodio2/encode.py
_strify
def _strify(s): """If s is a unicode string, encode it to UTF-8 and return the results, otherwise return str(s), or None if s is None""" if s is None: return None if isinstance(s, unicode): return s.encode("utf-8") return str(s)
python
def _strify(s): """If s is a unicode string, encode it to UTF-8 and return the results, otherwise return str(s), or None if s is None""" if s is None: return None if isinstance(s, unicode): return s.encode("utf-8") return str(s)
[ "def", "_strify", "(", "s", ")", ":", "if", "s", "is", "None", ":", "return", "None", "if", "isinstance", "(", "s", ",", "unicode", ")", ":", "return", "s", ".", "encode", "(", "\"utf-8\"", ")", "return", "str", "(", "s", ")" ]
If s is a unicode string, encode it to UTF-8 and return the results, otherwise return str(s), or None if s is None
[ "If", "s", "is", "a", "unicode", "string", "encode", "it", "to", "UTF", "-", "8", "and", "return", "the", "results", "otherwise", "return", "str", "(", "s", ")", "or", "None", "if", "s", "is", "None" ]
train
https://github.com/podio/podio-py/blob/5ce956034a06c98b0ef18fcd940b36da0908ad6c/pypodio2/encode.py#L52-L59
podio/podio-py
pypodio2/encode.py
encode_file_header
def encode_file_header(boundary, paramname, filesize, filename=None, filetype=None): """Returns the leading data for a multipart/form-data field that contains file data. ``boundary`` is the boundary string used throughout a single request to separate variables. ``paramname``...
python
def encode_file_header(boundary, paramname, filesize, filename=None, filetype=None): """Returns the leading data for a multipart/form-data field that contains file data. ``boundary`` is the boundary string used throughout a single request to separate variables. ``paramname``...
[ "def", "encode_file_header", "(", "boundary", ",", "paramname", ",", "filesize", ",", "filename", "=", "None", ",", "filetype", "=", "None", ")", ":", "return", "MultipartParam", "(", "paramname", ",", "filesize", "=", "filesize", ",", "filename", "=", "file...
Returns the leading data for a multipart/form-data field that contains file data. ``boundary`` is the boundary string used throughout a single request to separate variables. ``paramname`` is the name of the variable in this request. ``filesize`` is the size of the file data. ``filename`` if ...
[ "Returns", "the", "leading", "data", "for", "a", "multipart", "/", "form", "-", "data", "field", "that", "contains", "file", "data", "." ]
train
https://github.com/podio/podio-py/blob/5ce956034a06c98b0ef18fcd940b36da0908ad6c/pypodio2/encode.py#L291-L312
podio/podio-py
pypodio2/encode.py
get_body_size
def get_body_size(params, boundary): """Returns the number of bytes that the multipart/form-data encoding of ``params`` will be.""" size = sum(p.get_size(boundary) for p in MultipartParam.from_params(params)) return size + len(boundary) + 6
python
def get_body_size(params, boundary): """Returns the number of bytes that the multipart/form-data encoding of ``params`` will be.""" size = sum(p.get_size(boundary) for p in MultipartParam.from_params(params)) return size + len(boundary) + 6
[ "def", "get_body_size", "(", "params", ",", "boundary", ")", ":", "size", "=", "sum", "(", "p", ".", "get_size", "(", "boundary", ")", "for", "p", "in", "MultipartParam", ".", "from_params", "(", "params", ")", ")", "return", "size", "+", "len", "(", ...
Returns the number of bytes that the multipart/form-data encoding of ``params`` will be.
[ "Returns", "the", "number", "of", "bytes", "that", "the", "multipart", "/", "form", "-", "data", "encoding", "of", "params", "will", "be", "." ]
train
https://github.com/podio/podio-py/blob/5ce956034a06c98b0ef18fcd940b36da0908ad6c/pypodio2/encode.py#L315-L319
podio/podio-py
pypodio2/encode.py
get_headers
def get_headers(params, boundary): """Returns a dictionary with Content-Type and Content-Length headers for the multipart/form-data encoding of ``params``.""" headers = {} boundary = urllib.quote_plus(boundary) headers['Content-Type'] = "multipart/form-data; boundary=%s" % boundary headers['Cont...
python
def get_headers(params, boundary): """Returns a dictionary with Content-Type and Content-Length headers for the multipart/form-data encoding of ``params``.""" headers = {} boundary = urllib.quote_plus(boundary) headers['Content-Type'] = "multipart/form-data; boundary=%s" % boundary headers['Cont...
[ "def", "get_headers", "(", "params", ",", "boundary", ")", ":", "headers", "=", "{", "}", "boundary", "=", "urllib", ".", "quote_plus", "(", "boundary", ")", "headers", "[", "'Content-Type'", "]", "=", "\"multipart/form-data; boundary=%s\"", "%", "boundary", "...
Returns a dictionary with Content-Type and Content-Length headers for the multipart/form-data encoding of ``params``.
[ "Returns", "a", "dictionary", "with", "Content", "-", "Type", "and", "Content", "-", "Length", "headers", "for", "the", "multipart", "/", "form", "-", "data", "encoding", "of", "params", "." ]
train
https://github.com/podio/podio-py/blob/5ce956034a06c98b0ef18fcd940b36da0908ad6c/pypodio2/encode.py#L322-L329
podio/podio-py
pypodio2/encode.py
multipart_encode
def multipart_encode(params, boundary=None, cb=None): """Encode ``params`` as multipart/form-data. ``params`` should be a sequence of (name, value) pairs or MultipartParam objects, or a mapping of names to values. Values are either strings parameter values, or file-like objects to use as the parame...
python
def multipart_encode(params, boundary=None, cb=None): """Encode ``params`` as multipart/form-data. ``params`` should be a sequence of (name, value) pairs or MultipartParam objects, or a mapping of names to values. Values are either strings parameter values, or file-like objects to use as the parame...
[ "def", "multipart_encode", "(", "params", ",", "boundary", "=", "None", ",", "cb", "=", "None", ")", ":", "if", "boundary", "is", "None", ":", "boundary", "=", "gen_boundary", "(", ")", "else", ":", "boundary", "=", "urllib", ".", "quote_plus", "(", "b...
Encode ``params`` as multipart/form-data. ``params`` should be a sequence of (name, value) pairs or MultipartParam objects, or a mapping of names to values. Values are either strings parameter values, or file-like objects to use as the parameter value. The file-like objects must support .read() and ei...
[ "Encode", "params", "as", "multipart", "/", "form", "-", "data", "." ]
train
https://github.com/podio/podio-py/blob/5ce956034a06c98b0ef18fcd940b36da0908ad6c/pypodio2/encode.py#L385-L433
podio/podio-py
pypodio2/encode.py
MultipartParam.from_file
def from_file(cls, paramname, filename): """Returns a new MultipartParam object constructed from the local file at ``filename``. ``filesize`` is determined by os.path.getsize(``filename``) ``filetype`` is determined by mimetypes.guess_type(``filename``)[0] ``filename`` is set ...
python
def from_file(cls, paramname, filename): """Returns a new MultipartParam object constructed from the local file at ``filename``. ``filesize`` is determined by os.path.getsize(``filename``) ``filetype`` is determined by mimetypes.guess_type(``filename``)[0] ``filename`` is set ...
[ "def", "from_file", "(", "cls", ",", "paramname", ",", "filename", ")", ":", "return", "cls", "(", "paramname", ",", "filename", "=", "os", ".", "path", ".", "basename", "(", "filename", ")", ",", "filetype", "=", "mimetypes", ".", "guess_type", "(", "...
Returns a new MultipartParam object constructed from the local file at ``filename``. ``filesize`` is determined by os.path.getsize(``filename``) ``filetype`` is determined by mimetypes.guess_type(``filename``)[0] ``filename`` is set to os.path.basename(``filename``)
[ "Returns", "a", "new", "MultipartParam", "object", "constructed", "from", "the", "local", "file", "at", "filename", "." ]
train
https://github.com/podio/podio-py/blob/5ce956034a06c98b0ef18fcd940b36da0908ad6c/pypodio2/encode.py#L143-L157
podio/podio-py
pypodio2/encode.py
MultipartParam.from_params
def from_params(cls, params): """Returns a list of MultipartParam objects from a sequence of name, value pairs, MultipartParam instances, or from a mapping of names to values The values may be strings or file objects, or MultipartParam objects. MultipartParam object names must m...
python
def from_params(cls, params): """Returns a list of MultipartParam objects from a sequence of name, value pairs, MultipartParam instances, or from a mapping of names to values The values may be strings or file objects, or MultipartParam objects. MultipartParam object names must m...
[ "def", "from_params", "(", "cls", ",", "params", ")", ":", "if", "hasattr", "(", "params", ",", "'items'", ")", ":", "params", "=", "params", ".", "items", "(", ")", "retval", "=", "[", "]", "for", "item", "in", "params", ":", "if", "isinstance", "...
Returns a list of MultipartParam objects from a sequence of name, value pairs, MultipartParam instances, or from a mapping of names to values The values may be strings or file objects, or MultipartParam objects. MultipartParam object names must match the given names in the name,...
[ "Returns", "a", "list", "of", "MultipartParam", "objects", "from", "a", "sequence", "of", "name", "value", "pairs", "MultipartParam", "instances", "or", "from", "a", "mapping", "of", "names", "to", "values" ]
train
https://github.com/podio/podio-py/blob/5ce956034a06c98b0ef18fcd940b36da0908ad6c/pypodio2/encode.py#L160-L193
podio/podio-py
pypodio2/encode.py
MultipartParam.encode_hdr
def encode_hdr(self, boundary): """Returns the header of the encoding of this parameter""" boundary = encode_and_quote(boundary) headers = ["--%s" % boundary] if self.filename: disposition = 'form-data; name="%s"; filename="%s"' % (self.name, ...
python
def encode_hdr(self, boundary): """Returns the header of the encoding of this parameter""" boundary = encode_and_quote(boundary) headers = ["--%s" % boundary] if self.filename: disposition = 'form-data; name="%s"; filename="%s"' % (self.name, ...
[ "def", "encode_hdr", "(", "self", ",", "boundary", ")", ":", "boundary", "=", "encode_and_quote", "(", "boundary", ")", "headers", "=", "[", "\"--%s\"", "%", "boundary", "]", "if", "self", ".", "filename", ":", "disposition", "=", "'form-data; name=\"%s\"; fil...
Returns the header of the encoding of this parameter
[ "Returns", "the", "header", "of", "the", "encoding", "of", "this", "parameter" ]
train
https://github.com/podio/podio-py/blob/5ce956034a06c98b0ef18fcd940b36da0908ad6c/pypodio2/encode.py#L195-L219
podio/podio-py
pypodio2/encode.py
MultipartParam.encode
def encode(self, boundary): """Returns the string encoding of this parameter""" if self.value is None: value = self.fileobj.read() else: value = self.value if re.search("^--%s$" % re.escape(boundary), value, re.M): raise ValueError("boundary found in ...
python
def encode(self, boundary): """Returns the string encoding of this parameter""" if self.value is None: value = self.fileobj.read() else: value = self.value if re.search("^--%s$" % re.escape(boundary), value, re.M): raise ValueError("boundary found in ...
[ "def", "encode", "(", "self", ",", "boundary", ")", ":", "if", "self", ".", "value", "is", "None", ":", "value", "=", "self", ".", "fileobj", ".", "read", "(", ")", "else", ":", "value", "=", "self", ".", "value", "if", "re", ".", "search", "(", ...
Returns the string encoding of this parameter
[ "Returns", "the", "string", "encoding", "of", "this", "parameter" ]
train
https://github.com/podio/podio-py/blob/5ce956034a06c98b0ef18fcd940b36da0908ad6c/pypodio2/encode.py#L221-L231
podio/podio-py
pypodio2/encode.py
MultipartParam.iter_encode
def iter_encode(self, boundary, blocksize=4096): """Yields the encoding of this parameter If self.fileobj is set, then blocks of ``blocksize`` bytes are read and yielded.""" total = self.get_size(boundary) current = 0 if self.value is not None: block = self.en...
python
def iter_encode(self, boundary, blocksize=4096): """Yields the encoding of this parameter If self.fileobj is set, then blocks of ``blocksize`` bytes are read and yielded.""" total = self.get_size(boundary) current = 0 if self.value is not None: block = self.en...
[ "def", "iter_encode", "(", "self", ",", "boundary", ",", "blocksize", "=", "4096", ")", ":", "total", "=", "self", ".", "get_size", "(", "boundary", ")", "current", "=", "0", "if", "self", ".", "value", "is", "not", "None", ":", "block", "=", "self",...
Yields the encoding of this parameter If self.fileobj is set, then blocks of ``blocksize`` bytes are read and yielded.
[ "Yields", "the", "encoding", "of", "this", "parameter", "If", "self", ".", "fileobj", "is", "set", "then", "blocks", "of", "blocksize", "bytes", "are", "read", "and", "yielded", "." ]
train
https://github.com/podio/podio-py/blob/5ce956034a06c98b0ef18fcd940b36da0908ad6c/pypodio2/encode.py#L233-L270
podio/podio-py
pypodio2/encode.py
MultipartParam.get_size
def get_size(self, boundary): """Returns the size in bytes that this param will be when encoded with the given boundary.""" if self.filesize is not None: valuesize = self.filesize else: valuesize = len(self.value) return len(self.encode_hdr(boundary)) + 2...
python
def get_size(self, boundary): """Returns the size in bytes that this param will be when encoded with the given boundary.""" if self.filesize is not None: valuesize = self.filesize else: valuesize = len(self.value) return len(self.encode_hdr(boundary)) + 2...
[ "def", "get_size", "(", "self", ",", "boundary", ")", ":", "if", "self", ".", "filesize", "is", "not", "None", ":", "valuesize", "=", "self", ".", "filesize", "else", ":", "valuesize", "=", "len", "(", "self", ".", "value", ")", "return", "len", "(",...
Returns the size in bytes that this param will be when encoded with the given boundary.
[ "Returns", "the", "size", "in", "bytes", "that", "this", "param", "will", "be", "when", "encoded", "with", "the", "given", "boundary", "." ]
train
https://github.com/podio/podio-py/blob/5ce956034a06c98b0ef18fcd940b36da0908ad6c/pypodio2/encode.py#L272-L280
podio/podio-py
pypodio2/encode.py
MultipartYielder.next
def next(self): """generator function to yield multipart/form-data representation of parameters""" if self.param_iter is not None: try: block = self.param_iter.next() self.current += len(block) if self.cb: self.cb(se...
python
def next(self): """generator function to yield multipart/form-data representation of parameters""" if self.param_iter is not None: try: block = self.param_iter.next() self.current += len(block) if self.cb: self.cb(se...
[ "def", "next", "(", "self", ")", ":", "if", "self", ".", "param_iter", "is", "not", "None", ":", "try", ":", "block", "=", "self", ".", "param_iter", ".", "next", "(", ")", "self", ".", "current", "+=", "len", "(", "block", ")", "if", "self", "."...
generator function to yield multipart/form-data representation of parameters
[ "generator", "function", "to", "yield", "multipart", "/", "form", "-", "data", "representation", "of", "parameters" ]
train
https://github.com/podio/podio-py/blob/5ce956034a06c98b0ef18fcd940b36da0908ad6c/pypodio2/encode.py#L347-L376
podio/podio-py
pypodio2/areas.py
Area.get_options
def get_options(silent=False, hook=True): """ Generate a query string with the appropriate options. :param silent: If set to true, the object will not be bumped up in the stream and notifications will not be generated. :type silent: bool :param hook: True ...
python
def get_options(silent=False, hook=True): """ Generate a query string with the appropriate options. :param silent: If set to true, the object will not be bumped up in the stream and notifications will not be generated. :type silent: bool :param hook: True ...
[ "def", "get_options", "(", "silent", "=", "False", ",", "hook", "=", "True", ")", ":", "options_", "=", "{", "}", "if", "silent", ":", "options_", "[", "'silent'", "]", "=", "silent", "if", "not", "hook", ":", "options_", "[", "'hook'", "]", "=", "...
Generate a query string with the appropriate options. :param silent: If set to true, the object will not be bumped up in the stream and notifications will not be generated. :type silent: bool :param hook: True if hooks should be executed for the change, false otherwise. ...
[ "Generate", "a", "query", "string", "with", "the", "appropriate", "options", "." ]
train
https://github.com/podio/podio-py/blob/5ce956034a06c98b0ef18fcd940b36da0908ad6c/pypodio2/areas.py#L22-L42
podio/podio-py
pypodio2/areas.py
Item.find
def find(self, item_id, basic=False, **kwargs): """ Get item :param item_id: Item ID :param basic: ? :type item_id: int :return: Item info :rtype: dict """ if basic: return self.transport.GET(url='/item/%d/basic' % item_id) ...
python
def find(self, item_id, basic=False, **kwargs): """ Get item :param item_id: Item ID :param basic: ? :type item_id: int :return: Item info :rtype: dict """ if basic: return self.transport.GET(url='/item/%d/basic' % item_id) ...
[ "def", "find", "(", "self", ",", "item_id", ",", "basic", "=", "False", ",", "*", "*", "kwargs", ")", ":", "if", "basic", ":", "return", "self", ".", "transport", ".", "GET", "(", "url", "=", "'/item/%d/basic'", "%", "item_id", ")", "return", "self",...
Get item :param item_id: Item ID :param basic: ? :type item_id: int :return: Item info :rtype: dict
[ "Get", "item", ":", "param", "item_id", ":", "Item", "ID", ":", "param", "basic", ":", "?", ":", "type", "item_id", ":", "int", ":", "return", ":", "Item", "info", ":", "rtype", ":", "dict" ]
train
https://github.com/podio/podio-py/blob/5ce956034a06c98b0ef18fcd940b36da0908ad6c/pypodio2/areas.py#L82-L94
podio/podio-py
pypodio2/areas.py
Item.update
def update(self, item_id, attributes, silent=False, hook=True): """ Updates the item using the supplied attributes. If 'silent' is true, Podio will send no notifications to subscribed users and not post updates to the stream. Important: webhooks will still be called. """...
python
def update(self, item_id, attributes, silent=False, hook=True): """ Updates the item using the supplied attributes. If 'silent' is true, Podio will send no notifications to subscribed users and not post updates to the stream. Important: webhooks will still be called. """...
[ "def", "update", "(", "self", ",", "item_id", ",", "attributes", ",", "silent", "=", "False", ",", "hook", "=", "True", ")", ":", "if", "not", "isinstance", "(", "attributes", ",", "dict", ")", ":", "raise", "TypeError", "(", "'Must be of type dict'", ")...
Updates the item using the supplied attributes. If 'silent' is true, Podio will send no notifications to subscribed users and not post updates to the stream. Important: webhooks will still be called.
[ "Updates", "the", "item", "using", "the", "supplied", "attributes", ".", "If", "silent", "is", "true", "Podio", "will", "send", "no", "notifications", "to", "subscribed", "users", "and", "not", "post", "updates", "to", "the", "stream", ".", "Important", ":",...
train
https://github.com/podio/podio-py/blob/5ce956034a06c98b0ef18fcd940b36da0908ad6c/pypodio2/areas.py#L132-L145
podio/podio-py
pypodio2/areas.py
Task.create
def create(self, attributes, silent=False, hook=True): """ https://developers.podio.com/doc/tasks/create-task-22419 Creates the task using the supplied attributes. If 'silent' is true, Podio will send no notifications to subscribed users and not post updates to the stream. If 'ho...
python
def create(self, attributes, silent=False, hook=True): """ https://developers.podio.com/doc/tasks/create-task-22419 Creates the task using the supplied attributes. If 'silent' is true, Podio will send no notifications to subscribed users and not post updates to the stream. If 'ho...
[ "def", "create", "(", "self", ",", "attributes", ",", "silent", "=", "False", ",", "hook", "=", "True", ")", ":", "# if not isinstance(attributes, dict):", "# raise TypeError('Must be of type dict')", "attributes", "=", "json", ".", "dumps", "(", "attributes", ")...
https://developers.podio.com/doc/tasks/create-task-22419 Creates the task using the supplied attributes. If 'silent' is true, Podio will send no notifications to subscribed users and not post updates to the stream. If 'hook' is false webhooks will not be called.
[ "https", ":", "//", "developers", ".", "podio", ".", "com", "/", "doc", "/", "tasks", "/", "create", "-", "task", "-", "22419", "Creates", "the", "task", "using", "the", "supplied", "attributes", ".", "If", "silent", "is", "true", "Podio", "will", "sen...
train
https://github.com/podio/podio-py/blob/5ce956034a06c98b0ef18fcd940b36da0908ad6c/pypodio2/areas.py#L269-L281
podio/podio-py
pypodio2/areas.py
Task.create_for
def create_for(self, ref_type, ref_id, attributes, silent=False, hook=True): """ https://developers.podio.com/doc/tasks/create-task-with-reference-22420 If 'silent' is true, Podio will send no notifications and not post updates to the stream. If 'hook' is false webhooks will not be calle...
python
def create_for(self, ref_type, ref_id, attributes, silent=False, hook=True): """ https://developers.podio.com/doc/tasks/create-task-with-reference-22420 If 'silent' is true, Podio will send no notifications and not post updates to the stream. If 'hook' is false webhooks will not be calle...
[ "def", "create_for", "(", "self", ",", "ref_type", ",", "ref_id", ",", "attributes", ",", "silent", "=", "False", ",", "hook", "=", "True", ")", ":", "# if not isinstance(attributes, dict):", "# raise TypeError('Must be of type dict')", "attributes", "=", "json", ...
https://developers.podio.com/doc/tasks/create-task-with-reference-22420 If 'silent' is true, Podio will send no notifications and not post updates to the stream. If 'hook' is false webhooks will not be called.
[ "https", ":", "//", "developers", ".", "podio", ".", "com", "/", "doc", "/", "tasks", "/", "create", "-", "task", "-", "with", "-", "reference", "-", "22420", "If", "silent", "is", "true", "Podio", "will", "send", "no", "notifications", "and", "not", ...
train
https://github.com/podio/podio-py/blob/5ce956034a06c98b0ef18fcd940b36da0908ad6c/pypodio2/areas.py#L283-L296
podio/podio-py
pypodio2/areas.py
Space.find_by_url
def find_by_url(self, space_url, id_only=True): """ Returns a space ID given the URL of the space. :param space_url: URL of the Space :param id_only: ? :return: space_id: Space url :rtype: str """ resp = self.transport.GET(url='/space/url?%s' % urlencode(...
python
def find_by_url(self, space_url, id_only=True): """ Returns a space ID given the URL of the space. :param space_url: URL of the Space :param id_only: ? :return: space_id: Space url :rtype: str """ resp = self.transport.GET(url='/space/url?%s' % urlencode(...
[ "def", "find_by_url", "(", "self", ",", "space_url", ",", "id_only", "=", "True", ")", ":", "resp", "=", "self", ".", "transport", ".", "GET", "(", "url", "=", "'/space/url?%s'", "%", "urlencode", "(", "{", "'url'", ":", "space_url", "}", ")", ")", "...
Returns a space ID given the URL of the space. :param space_url: URL of the Space :param id_only: ? :return: space_id: Space url :rtype: str
[ "Returns", "a", "space", "ID", "given", "the", "URL", "of", "the", "space", "." ]
train
https://github.com/podio/podio-py/blob/5ce956034a06c98b0ef18fcd940b36da0908ad6c/pypodio2/areas.py#L323-L335
podio/podio-py
pypodio2/areas.py
Space.create
def create(self, attributes): """ Create a new space :param attributes: Refer to API. Pass in argument as dictionary :type attributes: dict :return: Details of newly created space :rtype: dict """ if not isinstance(attributes, dict): r...
python
def create(self, attributes): """ Create a new space :param attributes: Refer to API. Pass in argument as dictionary :type attributes: dict :return: Details of newly created space :rtype: dict """ if not isinstance(attributes, dict): r...
[ "def", "create", "(", "self", ",", "attributes", ")", ":", "if", "not", "isinstance", "(", "attributes", ",", "dict", ")", ":", "raise", "TypeError", "(", "'Dictionary of values expected'", ")", "attributes", "=", "json", ".", "dumps", "(", "attributes", ")"...
Create a new space :param attributes: Refer to API. Pass in argument as dictionary :type attributes: dict :return: Details of newly created space :rtype: dict
[ "Create", "a", "new", "space", ":", "param", "attributes", ":", "Refer", "to", "API", ".", "Pass", "in", "argument", "as", "dictionary", ":", "type", "attributes", ":", "dict", ":", "return", ":", "Details", "of", "newly", "created", "space", ":", "rtype...
train
https://github.com/podio/podio-py/blob/5ce956034a06c98b0ef18fcd940b36da0908ad6c/pypodio2/areas.py#L348-L360
podio/podio-py
pypodio2/areas.py
Stream.find_by_ref
def find_by_ref(self, ref_type, ref_id): """ Returns an object of type "item", "status" or "task" as a stream object. This is useful when a new status has been posted and should be rendered directly in the stream without reloading the entire stream. For details, see: htt...
python
def find_by_ref(self, ref_type, ref_id): """ Returns an object of type "item", "status" or "task" as a stream object. This is useful when a new status has been posted and should be rendered directly in the stream without reloading the entire stream. For details, see: htt...
[ "def", "find_by_ref", "(", "self", ",", "ref_type", ",", "ref_id", ")", ":", "return", "self", ".", "transport", ".", "GET", "(", "url", "=", "'/stream/%s/%s'", "%", "(", "ref_type", ",", "ref_id", ")", ")" ]
Returns an object of type "item", "status" or "task" as a stream object. This is useful when a new status has been posted and should be rendered directly in the stream without reloading the entire stream. For details, see: https://developers.podio.com/doc/stream/get-stream-object-80054
[ "Returns", "an", "object", "of", "type", "item", "status", "or", "task", "as", "a", "stream", "object", ".", "This", "is", "useful", "when", "a", "new", "status", "has", "been", "posted", "and", "should", "be", "rendered", "directly", "in", "the", "strea...
train
https://github.com/podio/podio-py/blob/5ce956034a06c98b0ef18fcd940b36da0908ad6c/pypodio2/areas.py#L415-L424
podio/podio-py
pypodio2/areas.py
Files.find_raw
def find_raw(self, file_id): """Returns raw file as string. Pass to a file object""" raw_handler = lambda resp, data: data return self.transport.GET(url='/file/%d/raw' % file_id, handler=raw_handler)
python
def find_raw(self, file_id): """Returns raw file as string. Pass to a file object""" raw_handler = lambda resp, data: data return self.transport.GET(url='/file/%d/raw' % file_id, handler=raw_handler)
[ "def", "find_raw", "(", "self", ",", "file_id", ")", ":", "raw_handler", "=", "lambda", "resp", ",", "data", ":", "data", "return", "self", ".", "transport", ".", "GET", "(", "url", "=", "'/file/%d/raw'", "%", "file_id", ",", "handler", "=", "raw_handler...
Returns raw file as string. Pass to a file object
[ "Returns", "raw", "file", "as", "string", ".", "Pass", "to", "a", "file", "object" ]
train
https://github.com/podio/podio-py/blob/5ce956034a06c98b0ef18fcd940b36da0908ad6c/pypodio2/areas.py#L509-L512
podio/podio-py
pypodio2/areas.py
Files.create
def create(self, filename, filedata): """Create a file from raw data""" attributes = {'filename': filename, 'source': filedata} return self.transport.POST(url='/file/v2/', body=attributes, type='multipart/form-data')
python
def create(self, filename, filedata): """Create a file from raw data""" attributes = {'filename': filename, 'source': filedata} return self.transport.POST(url='/file/v2/', body=attributes, type='multipart/form-data')
[ "def", "create", "(", "self", ",", "filename", ",", "filedata", ")", ":", "attributes", "=", "{", "'filename'", ":", "filename", ",", "'source'", ":", "filedata", "}", "return", "self", ".", "transport", ".", "POST", "(", "url", "=", "'/file/v2/'", ",", ...
Create a file from raw data
[ "Create", "a", "file", "from", "raw", "data" ]
train
https://github.com/podio/podio-py/blob/5ce956034a06c98b0ef18fcd940b36da0908ad6c/pypodio2/areas.py#L522-L526
podio/podio-py
pypodio2/areas.py
View.get
def get(self, app_id, view_specifier): """ Retrieve the definition of a given view, provided the app_id and the view_id :param app_id: the app id :param view_specifier: Can be one of the following: 1. The view ID 2. The view's name 3. "las...
python
def get(self, app_id, view_specifier): """ Retrieve the definition of a given view, provided the app_id and the view_id :param app_id: the app id :param view_specifier: Can be one of the following: 1. The view ID 2. The view's name 3. "las...
[ "def", "get", "(", "self", ",", "app_id", ",", "view_specifier", ")", ":", "return", "self", ".", "transport", ".", "GET", "(", "url", "=", "'/view/app/{}/{}'", ".", "format", "(", "app_id", ",", "view_specifier", ")", ")" ]
Retrieve the definition of a given view, provided the app_id and the view_id :param app_id: the app id :param view_specifier: Can be one of the following: 1. The view ID 2. The view's name 3. "last" to look up the last view used
[ "Retrieve", "the", "definition", "of", "a", "given", "view", "provided", "the", "app_id", "and", "the", "view_id" ]
train
https://github.com/podio/podio-py/blob/5ce956034a06c98b0ef18fcd940b36da0908ad6c/pypodio2/areas.py#L557-L568
podio/podio-py
pypodio2/areas.py
View.get_views
def get_views(self, app_id, include_standard_views=False): """ Get all of the views for the specified app :param app_id: the app containing the views :param include_standard_views: defaults to false. Set to true if you wish to include standard views. """ include_standard...
python
def get_views(self, app_id, include_standard_views=False): """ Get all of the views for the specified app :param app_id: the app containing the views :param include_standard_views: defaults to false. Set to true if you wish to include standard views. """ include_standard...
[ "def", "get_views", "(", "self", ",", "app_id", ",", "include_standard_views", "=", "False", ")", ":", "include_standard", "=", "\"true\"", "if", "include_standard_views", "is", "True", "else", "\"false\"", "return", "self", ".", "transport", ".", "GET", "(", ...
Get all of the views for the specified app :param app_id: the app containing the views :param include_standard_views: defaults to false. Set to true if you wish to include standard views.
[ "Get", "all", "of", "the", "views", "for", "the", "specified", "app" ]
train
https://github.com/podio/podio-py/blob/5ce956034a06c98b0ef18fcd940b36da0908ad6c/pypodio2/areas.py#L570-L578
podio/podio-py
pypodio2/areas.py
View.update_last_view
def update_last_view(self, app_id, attributes): """ Updates the last view for the active user :param app_id: the app id :param attributes: the body of the request in dictionary format """ if not isinstance(attributes, dict): raise TypeError('Must be of type d...
python
def update_last_view(self, app_id, attributes): """ Updates the last view for the active user :param app_id: the app id :param attributes: the body of the request in dictionary format """ if not isinstance(attributes, dict): raise TypeError('Must be of type d...
[ "def", "update_last_view", "(", "self", ",", "app_id", ",", "attributes", ")", ":", "if", "not", "isinstance", "(", "attributes", ",", "dict", ")", ":", "raise", "TypeError", "(", "'Must be of type dict'", ")", "attribute_data", "=", "json", ".", "dumps", "(...
Updates the last view for the active user :param app_id: the app id :param attributes: the body of the request in dictionary format
[ "Updates", "the", "last", "view", "for", "the", "active", "user" ]
train
https://github.com/podio/podio-py/blob/5ce956034a06c98b0ef18fcd940b36da0908ad6c/pypodio2/areas.py#L589-L600
podio/podio-py
pypodio2/areas.py
View.update_view
def update_view(self, view_id, attributes): """ Update an existing view using the details supplied via the attributes parameter :param view_id: the view's id :param attributes: a dictionary containing the modifications to be made to the view :return: """ if not i...
python
def update_view(self, view_id, attributes): """ Update an existing view using the details supplied via the attributes parameter :param view_id: the view's id :param attributes: a dictionary containing the modifications to be made to the view :return: """ if not i...
[ "def", "update_view", "(", "self", ",", "view_id", ",", "attributes", ")", ":", "if", "not", "isinstance", "(", "attributes", ",", "dict", ")", ":", "raise", "TypeError", "(", "'Must be of type dict'", ")", "attribute_data", "=", "json", ".", "dumps", "(", ...
Update an existing view using the details supplied via the attributes parameter :param view_id: the view's id :param attributes: a dictionary containing the modifications to be made to the view :return:
[ "Update", "an", "existing", "view", "using", "the", "details", "supplied", "via", "the", "attributes", "parameter" ]
train
https://github.com/podio/podio-py/blob/5ce956034a06c98b0ef18fcd940b36da0908ad6c/pypodio2/areas.py#L602-L614
PythonicNinja/pydrill
pydrill/client/__init__.py
PyDrill.is_active
def is_active(self, timeout=2): """ :param timeout: int :return: boolean """ try: result = Result(*self.perform_request('HEAD', '/', params={'request_timeout': timeout})) except ConnectionError: return False except TransportError: ...
python
def is_active(self, timeout=2): """ :param timeout: int :return: boolean """ try: result = Result(*self.perform_request('HEAD', '/', params={'request_timeout': timeout})) except ConnectionError: return False except TransportError: ...
[ "def", "is_active", "(", "self", ",", "timeout", "=", "2", ")", ":", "try", ":", "result", "=", "Result", "(", "*", "self", ".", "perform_request", "(", "'HEAD'", ",", "'/'", ",", "params", "=", "{", "'request_timeout'", ":", "timeout", "}", ")", ")"...
:param timeout: int :return: boolean
[ ":", "param", "timeout", ":", "int", ":", "return", ":", "boolean" ]
train
https://github.com/PythonicNinja/pydrill/blob/0713e78c84d44cd438018e4ba1588a8e242f78c4/pydrill/client/__init__.py#L26-L41
PythonicNinja/pydrill
pydrill/client/__init__.py
PyDrill.query
def query(self, sql, timeout=10): """ Submit a query and return results. :param sql: string :param timeout: int :return: pydrill.client.ResultQuery """ if not sql: raise QueryError('No query passed to drill.') result = ResultQuery(*self.perfo...
python
def query(self, sql, timeout=10): """ Submit a query and return results. :param sql: string :param timeout: int :return: pydrill.client.ResultQuery """ if not sql: raise QueryError('No query passed to drill.') result = ResultQuery(*self.perfo...
[ "def", "query", "(", "self", ",", "sql", ",", "timeout", "=", "10", ")", ":", "if", "not", "sql", ":", "raise", "QueryError", "(", "'No query passed to drill.'", ")", "result", "=", "ResultQuery", "(", "*", "self", ".", "perform_request", "(", "*", "*", ...
Submit a query and return results. :param sql: string :param timeout: int :return: pydrill.client.ResultQuery
[ "Submit", "a", "query", "and", "return", "results", "." ]
train
https://github.com/PythonicNinja/pydrill/blob/0713e78c84d44cd438018e4ba1588a8e242f78c4/pydrill/client/__init__.py#L43-L66
PythonicNinja/pydrill
pydrill/client/__init__.py
PyDrill.plan
def plan(self, sql, timeout=10): """ :param sql: string :param timeout: int :return: pydrill.client.ResultQuery """ sql = 'explain plan for ' + sql return self.query(sql, timeout)
python
def plan(self, sql, timeout=10): """ :param sql: string :param timeout: int :return: pydrill.client.ResultQuery """ sql = 'explain plan for ' + sql return self.query(sql, timeout)
[ "def", "plan", "(", "self", ",", "sql", ",", "timeout", "=", "10", ")", ":", "sql", "=", "'explain plan for '", "+", "sql", "return", "self", ".", "query", "(", "sql", ",", "timeout", ")" ]
:param sql: string :param timeout: int :return: pydrill.client.ResultQuery
[ ":", "param", "sql", ":", "string", ":", "param", "timeout", ":", "int", ":", "return", ":", "pydrill", ".", "client", ".", "ResultQuery" ]
train
https://github.com/PythonicNinja/pydrill/blob/0713e78c84d44cd438018e4ba1588a8e242f78c4/pydrill/client/__init__.py#L68-L75
PythonicNinja/pydrill
pydrill/client/__init__.py
PyDrill.storage_detail
def storage_detail(self, name, timeout=10): """ Get the definition of the named storage plugin. :param name: The assigned name in the storage plugin definition. :param timeout: int :return: pydrill.client.Result """ result = Result(*self.perform_request(**{ ...
python
def storage_detail(self, name, timeout=10): """ Get the definition of the named storage plugin. :param name: The assigned name in the storage plugin definition. :param timeout: int :return: pydrill.client.Result """ result = Result(*self.perform_request(**{ ...
[ "def", "storage_detail", "(", "self", ",", "name", ",", "timeout", "=", "10", ")", ":", "result", "=", "Result", "(", "*", "self", ".", "perform_request", "(", "*", "*", "{", "'method'", ":", "'GET'", ",", "'url'", ":", "'/storage/{0}.json'", ".", "for...
Get the definition of the named storage plugin. :param name: The assigned name in the storage plugin definition. :param timeout: int :return: pydrill.client.Result
[ "Get", "the", "definition", "of", "the", "named", "storage", "plugin", "." ]
train
https://github.com/PythonicNinja/pydrill/blob/0713e78c84d44cd438018e4ba1588a8e242f78c4/pydrill/client/__init__.py#L157-L172
PythonicNinja/pydrill
pydrill/client/__init__.py
PyDrill.storage_enable
def storage_enable(self, name, value=True, timeout=10): """ Enable or disable the named storage plugin. :param name: The assigned name in the storage plugin definition. :param value: Either True (to enable) or False (to disable). :param timeout: int :return: pydrill.clie...
python
def storage_enable(self, name, value=True, timeout=10): """ Enable or disable the named storage plugin. :param name: The assigned name in the storage plugin definition. :param value: Either True (to enable) or False (to disable). :param timeout: int :return: pydrill.clie...
[ "def", "storage_enable", "(", "self", ",", "name", ",", "value", "=", "True", ",", "timeout", "=", "10", ")", ":", "value", "=", "'true'", "if", "value", "else", "'false'", "result", "=", "Result", "(", "*", "self", ".", "perform_request", "(", "*", ...
Enable or disable the named storage plugin. :param name: The assigned name in the storage plugin definition. :param value: Either True (to enable) or False (to disable). :param timeout: int :return: pydrill.client.Result
[ "Enable", "or", "disable", "the", "named", "storage", "plugin", "." ]
train
https://github.com/PythonicNinja/pydrill/blob/0713e78c84d44cd438018e4ba1588a8e242f78c4/pydrill/client/__init__.py#L174-L191
PythonicNinja/pydrill
pydrill/client/__init__.py
PyDrill.storage_update
def storage_update(self, name, config, timeout=10): """ Create or update a storage plugin configuration. :param name: The name of the storage plugin configuration to create or update. :param config: Overwrites the existing configuration if there is any, and therefore, must include all ...
python
def storage_update(self, name, config, timeout=10): """ Create or update a storage plugin configuration. :param name: The name of the storage plugin configuration to create or update. :param config: Overwrites the existing configuration if there is any, and therefore, must include all ...
[ "def", "storage_update", "(", "self", ",", "name", ",", "config", ",", "timeout", "=", "10", ")", ":", "result", "=", "Result", "(", "*", "self", ".", "perform_request", "(", "*", "*", "{", "'method'", ":", "'POST'", ",", "'url'", ":", "'/storage/{0}.j...
Create or update a storage plugin configuration. :param name: The name of the storage plugin configuration to create or update. :param config: Overwrites the existing configuration if there is any, and therefore, must include all required attributes and definitions. :param timeout: int ...
[ "Create", "or", "update", "a", "storage", "plugin", "configuration", "." ]
train
https://github.com/PythonicNinja/pydrill/blob/0713e78c84d44cd438018e4ba1588a8e242f78c4/pydrill/client/__init__.py#L193-L211
PythonicNinja/pydrill
pydrill/client/__init__.py
PyDrill.storage_delete
def storage_delete(self, name, timeout=10): """ Delete a storage plugin configuration. :param name: The name of the storage plugin configuration to delete. :param timeout: int :return: pydrill.client.Result """ result = Result(*self.perform_request(**{ ...
python
def storage_delete(self, name, timeout=10): """ Delete a storage plugin configuration. :param name: The name of the storage plugin configuration to delete. :param timeout: int :return: pydrill.client.Result """ result = Result(*self.perform_request(**{ ...
[ "def", "storage_delete", "(", "self", ",", "name", ",", "timeout", "=", "10", ")", ":", "result", "=", "Result", "(", "*", "self", ".", "perform_request", "(", "*", "*", "{", "'method'", ":", "'DELETE'", ",", "'url'", ":", "'/storage/{0}.json'", ".", "...
Delete a storage plugin configuration. :param name: The name of the storage plugin configuration to delete. :param timeout: int :return: pydrill.client.Result
[ "Delete", "a", "storage", "plugin", "configuration", "." ]
train
https://github.com/PythonicNinja/pydrill/blob/0713e78c84d44cd438018e4ba1588a8e242f78c4/pydrill/client/__init__.py#L213-L228
PythonicNinja/pydrill
pydrill/client/__init__.py
PyDrill.profile
def profile(self, query_id, timeout=10): """ Get the profile of the query that has the given queryid. :param query_id: The UUID of the query in standard UUID format that Drill assigns to each query. :param timeout: int :return: pydrill.client.Result """ result = ...
python
def profile(self, query_id, timeout=10): """ Get the profile of the query that has the given queryid. :param query_id: The UUID of the query in standard UUID format that Drill assigns to each query. :param timeout: int :return: pydrill.client.Result """ result = ...
[ "def", "profile", "(", "self", ",", "query_id", ",", "timeout", "=", "10", ")", ":", "result", "=", "Result", "(", "*", "self", ".", "perform_request", "(", "*", "*", "{", "'method'", ":", "'GET'", ",", "'url'", ":", "'/profiles/{0}.json'", ".", "forma...
Get the profile of the query that has the given queryid. :param query_id: The UUID of the query in standard UUID format that Drill assigns to each query. :param timeout: int :return: pydrill.client.Result
[ "Get", "the", "profile", "of", "the", "query", "that", "has", "the", "given", "queryid", "." ]
train
https://github.com/PythonicNinja/pydrill/blob/0713e78c84d44cd438018e4ba1588a8e242f78c4/pydrill/client/__init__.py#L246-L261
PythonicNinja/pydrill
pydrill/client/__init__.py
PyDrill.profile_cancel
def profile_cancel(self, query_id, timeout=10): """ Cancel the query that has the given queryid. :param query_id: The UUID of the query in standard UUID format that Drill assigns to each query. :param timeout: int :return: pydrill.client.Result """ result = Resul...
python
def profile_cancel(self, query_id, timeout=10): """ Cancel the query that has the given queryid. :param query_id: The UUID of the query in standard UUID format that Drill assigns to each query. :param timeout: int :return: pydrill.client.Result """ result = Resul...
[ "def", "profile_cancel", "(", "self", ",", "query_id", ",", "timeout", "=", "10", ")", ":", "result", "=", "Result", "(", "*", "self", ".", "perform_request", "(", "*", "*", "{", "'method'", ":", "'GET'", ",", "'url'", ":", "'/profiles/cancel/{0}'", ".",...
Cancel the query that has the given queryid. :param query_id: The UUID of the query in standard UUID format that Drill assigns to each query. :param timeout: int :return: pydrill.client.Result
[ "Cancel", "the", "query", "that", "has", "the", "given", "queryid", "." ]
train
https://github.com/PythonicNinja/pydrill/blob/0713e78c84d44cd438018e4ba1588a8e242f78c4/pydrill/client/__init__.py#L263-L278
PythonicNinja/pydrill
pydrill/connection/base.py
Connection.log_request_success
def log_request_success(self, method, full_url, path, body, status_code, response, duration): """ Log a successful API call. """ if body and not isinstance(body, dict): body = body.decode('utf-8') logger.info( '%s %s [status:%s request:%.3fs]', method, full_url, ...
python
def log_request_success(self, method, full_url, path, body, status_code, response, duration): """ Log a successful API call. """ if body and not isinstance(body, dict): body = body.decode('utf-8') logger.info( '%s %s [status:%s request:%.3fs]', method, full_url, ...
[ "def", "log_request_success", "(", "self", ",", "method", ",", "full_url", ",", "path", ",", "body", ",", "status_code", ",", "response", ",", "duration", ")", ":", "if", "body", "and", "not", "isinstance", "(", "body", ",", "dict", ")", ":", "body", "...
Log a successful API call.
[ "Log", "a", "successful", "API", "call", "." ]
train
https://github.com/PythonicNinja/pydrill/blob/0713e78c84d44cd438018e4ba1588a8e242f78c4/pydrill/connection/base.py#L62-L83
PythonicNinja/pydrill
pydrill/connection/base.py
Connection.log_request_fail
def log_request_fail(self, method, full_url, body, duration, status_code=None, exception=None): """ Log an unsuccessful API call. """ logger.warning( '%s %s [status:%s request:%.3fs]', method, full_url, status_code or 'N/A', duration, exc_info=exception is not Non...
python
def log_request_fail(self, method, full_url, body, duration, status_code=None, exception=None): """ Log an unsuccessful API call. """ logger.warning( '%s %s [status:%s request:%.3fs]', method, full_url, status_code or 'N/A', duration, exc_info=exception is not Non...
[ "def", "log_request_fail", "(", "self", ",", "method", ",", "full_url", ",", "body", ",", "duration", ",", "status_code", "=", "None", ",", "exception", "=", "None", ")", ":", "logger", ".", "warning", "(", "'%s %s [status:%s request:%.3fs]'", ",", "method", ...
Log an unsuccessful API call.
[ "Log", "an", "unsuccessful", "API", "call", "." ]
train
https://github.com/PythonicNinja/pydrill/blob/0713e78c84d44cd438018e4ba1588a8e242f78c4/pydrill/connection/base.py#L85-L97
PythonicNinja/pydrill
pydrill/connection/base.py
Connection._raise_error
def _raise_error(self, status_code, raw_data): """ Locate appropriate exception and raise it. """ error_message = raw_data additional_info = None try: additional_info = json.loads(raw_data) error_message = additional_info.get('error', error_message...
python
def _raise_error(self, status_code, raw_data): """ Locate appropriate exception and raise it. """ error_message = raw_data additional_info = None try: additional_info = json.loads(raw_data) error_message = additional_info.get('error', error_message...
[ "def", "_raise_error", "(", "self", ",", "status_code", ",", "raw_data", ")", ":", "error_message", "=", "raw_data", "additional_info", "=", "None", "try", ":", "additional_info", "=", "json", ".", "loads", "(", "raw_data", ")", "error_message", "=", "addition...
Locate appropriate exception and raise it.
[ "Locate", "appropriate", "exception", "and", "raise", "it", "." ]
train
https://github.com/PythonicNinja/pydrill/blob/0713e78c84d44cd438018e4ba1588a8e242f78c4/pydrill/connection/base.py#L99-L113
PythonicNinja/pydrill
pydrill/transport.py
Transport.perform_request
def perform_request(self, method, url, params=None, body=None): """ Perform the actual request. Retrieve a connection. Pass all the information to it's perform_request method and return the data. :arg method: HTTP method to use :arg url: absolute url (without host) to ta...
python
def perform_request(self, method, url, params=None, body=None): """ Perform the actual request. Retrieve a connection. Pass all the information to it's perform_request method and return the data. :arg method: HTTP method to use :arg url: absolute url (without host) to ta...
[ "def", "perform_request", "(", "self", ",", "method", ",", "url", ",", "params", "=", "None", ",", "body", "=", "None", ")", ":", "if", "body", "is", "not", "None", ":", "body", "=", "self", ".", "serializer", ".", "dumps", "(", "body", ")", "# som...
Perform the actual request. Retrieve a connection. Pass all the information to it's perform_request method and return the data. :arg method: HTTP method to use :arg url: absolute url (without host) to target :arg params: dictionary of query parameters, will be handed over to the...
[ "Perform", "the", "actual", "request", ".", "Retrieve", "a", "connection", ".", "Pass", "all", "the", "information", "to", "it", "s", "perform_request", "method", "and", "return", "the", "data", "." ]
train
https://github.com/PythonicNinja/pydrill/blob/0713e78c84d44cd438018e4ba1588a8e242f78c4/pydrill/transport.py#L30-L99
sarugaku/pip-shims
tasks/__init__.py
release
def release(ctx, type_, repo, prebump=PREBUMP, config_file=None, commit=True, yes=False): """Make a new release. """ if prebump not in REL_TYPES: raise ValueError(f"{type_} not in {REL_TYPES}") prebump = REL_TYPES.index(prebump) version = _read_version() version = _bump_release(version,...
python
def release(ctx, type_, repo, prebump=PREBUMP, config_file=None, commit=True, yes=False): """Make a new release. """ if prebump not in REL_TYPES: raise ValueError(f"{type_} not in {REL_TYPES}") prebump = REL_TYPES.index(prebump) version = _read_version() version = _bump_release(version,...
[ "def", "release", "(", "ctx", ",", "type_", ",", "repo", ",", "prebump", "=", "PREBUMP", ",", "config_file", "=", "None", ",", "commit", "=", "True", ",", "yes", "=", "False", ")", ":", "if", "prebump", "not", "in", "REL_TYPES", ":", "raise", "ValueE...
Make a new release.
[ "Make", "a", "new", "release", "." ]
train
https://github.com/sarugaku/pip-shims/blob/aebdc29f8b922871aa3ee78c51885a6caeb3662f/tasks/__init__.py#L136-L181
inveniosoftware/invenio-accounts
invenio_accounts/views/settings.py
init_menu
def init_menu(): """Initialize menu before first request.""" # Register breadcrumb root item = current_menu.submenu('breadcrumbs.settings') item.register('', _('Account')) item = current_menu.submenu('breadcrumbs.{0}'.format( current_app.config['SECURITY_BLUEPRINT_NAME'])) if current_ap...
python
def init_menu(): """Initialize menu before first request.""" # Register breadcrumb root item = current_menu.submenu('breadcrumbs.settings') item.register('', _('Account')) item = current_menu.submenu('breadcrumbs.{0}'.format( current_app.config['SECURITY_BLUEPRINT_NAME'])) if current_ap...
[ "def", "init_menu", "(", ")", ":", "# Register breadcrumb root", "item", "=", "current_menu", ".", "submenu", "(", "'breadcrumbs.settings'", ")", "item", ".", "register", "(", "''", ",", "_", "(", "'Account'", ")", ")", "item", "=", "current_menu", ".", "sub...
Initialize menu before first request.
[ "Initialize", "menu", "before", "first", "request", "." ]
train
https://github.com/inveniosoftware/invenio-accounts/blob/b0d2f0739b00dbefea22ca15d7d374a1b4a63aec/invenio_accounts/views/settings.py#L49-L78
inveniosoftware/invenio-accounts
invenio_accounts/views/settings.py
check_security_settings
def check_security_settings(): """Warn if session cookie is not secure in production.""" in_production = not (current_app.debug or current_app.testing) secure = current_app.config.get('SESSION_COOKIE_SECURE') if in_production and not secure: current_app.logger.warning( "SESSION_COOKI...
python
def check_security_settings(): """Warn if session cookie is not secure in production.""" in_production = not (current_app.debug or current_app.testing) secure = current_app.config.get('SESSION_COOKIE_SECURE') if in_production and not secure: current_app.logger.warning( "SESSION_COOKI...
[ "def", "check_security_settings", "(", ")", ":", "in_production", "=", "not", "(", "current_app", ".", "debug", "or", "current_app", ".", "testing", ")", "secure", "=", "current_app", ".", "config", ".", "get", "(", "'SESSION_COOKIE_SECURE'", ")", "if", "in_pr...
Warn if session cookie is not secure in production.
[ "Warn", "if", "session", "cookie", "is", "not", "secure", "in", "production", "." ]
train
https://github.com/inveniosoftware/invenio-accounts/blob/b0d2f0739b00dbefea22ca15d7d374a1b4a63aec/invenio_accounts/views/settings.py#L82-L90
inveniosoftware/invenio-accounts
invenio_accounts/context_processors/jwt.py
jwt_proccessor
def jwt_proccessor(): """Context processor for jwt.""" def jwt(): """Context processor function to generate jwt.""" token = current_accounts.jwt_creation_factory() return Markup( render_template( current_app.config['ACCOUNTS_JWT_DOM_TOKEN_TEMPLATE'], ...
python
def jwt_proccessor(): """Context processor for jwt.""" def jwt(): """Context processor function to generate jwt.""" token = current_accounts.jwt_creation_factory() return Markup( render_template( current_app.config['ACCOUNTS_JWT_DOM_TOKEN_TEMPLATE'], ...
[ "def", "jwt_proccessor", "(", ")", ":", "def", "jwt", "(", ")", ":", "\"\"\"Context processor function to generate jwt.\"\"\"", "token", "=", "current_accounts", ".", "jwt_creation_factory", "(", ")", "return", "Markup", "(", "render_template", "(", "current_app", "."...
Context processor for jwt.
[ "Context", "processor", "for", "jwt", "." ]
train
https://github.com/inveniosoftware/invenio-accounts/blob/b0d2f0739b00dbefea22ca15d7d374a1b4a63aec/invenio_accounts/context_processors/jwt.py#L17-L36
inveniosoftware/invenio-accounts
invenio_accounts/hash.py
_to_binary
def _to_binary(val): """Convert to binary.""" if isinstance(val, text_type): return val.encode('utf-8') assert isinstance(val, binary_type) return val
python
def _to_binary(val): """Convert to binary.""" if isinstance(val, text_type): return val.encode('utf-8') assert isinstance(val, binary_type) return val
[ "def", "_to_binary", "(", "val", ")", ":", "if", "isinstance", "(", "val", ",", "text_type", ")", ":", "return", "val", ".", "encode", "(", "'utf-8'", ")", "assert", "isinstance", "(", "val", ",", "binary_type", ")", "return", "val" ]
Convert to binary.
[ "Convert", "to", "binary", "." ]
train
https://github.com/inveniosoftware/invenio-accounts/blob/b0d2f0739b00dbefea22ca15d7d374a1b4a63aec/invenio_accounts/hash.py#L23-L28
inveniosoftware/invenio-accounts
invenio_accounts/hash.py
_to_string
def _to_string(val): """Convert to text.""" if isinstance(val, binary_type): return val.decode('utf-8') assert isinstance(val, text_type) return val
python
def _to_string(val): """Convert to text.""" if isinstance(val, binary_type): return val.decode('utf-8') assert isinstance(val, text_type) return val
[ "def", "_to_string", "(", "val", ")", ":", "if", "isinstance", "(", "val", ",", "binary_type", ")", ":", "return", "val", ".", "decode", "(", "'utf-8'", ")", "assert", "isinstance", "(", "val", ",", "text_type", ")", "return", "val" ]
Convert to text.
[ "Convert", "to", "text", "." ]
train
https://github.com/inveniosoftware/invenio-accounts/blob/b0d2f0739b00dbefea22ca15d7d374a1b4a63aec/invenio_accounts/hash.py#L31-L36
inveniosoftware/invenio-accounts
invenio_accounts/hash.py
_mysql_aes_key
def _mysql_aes_key(key): """Format key.""" final_key = bytearray(16) for i, c in enumerate(key): final_key[i % 16] ^= key[i] if PY3 else ord(key[i]) return bytes(final_key)
python
def _mysql_aes_key(key): """Format key.""" final_key = bytearray(16) for i, c in enumerate(key): final_key[i % 16] ^= key[i] if PY3 else ord(key[i]) return bytes(final_key)
[ "def", "_mysql_aes_key", "(", "key", ")", ":", "final_key", "=", "bytearray", "(", "16", ")", "for", "i", ",", "c", "in", "enumerate", "(", "key", ")", ":", "final_key", "[", "i", "%", "16", "]", "^=", "key", "[", "i", "]", "if", "PY3", "else", ...
Format key.
[ "Format", "key", "." ]
train
https://github.com/inveniosoftware/invenio-accounts/blob/b0d2f0739b00dbefea22ca15d7d374a1b4a63aec/invenio_accounts/hash.py#L39-L44
inveniosoftware/invenio-accounts
invenio_accounts/hash.py
_mysql_aes_pad
def _mysql_aes_pad(val): """Padding.""" val = _to_string(val) pad_value = 16 - (len(val) % 16) return _to_binary('{0}{1}'.format(val, chr(pad_value) * pad_value))
python
def _mysql_aes_pad(val): """Padding.""" val = _to_string(val) pad_value = 16 - (len(val) % 16) return _to_binary('{0}{1}'.format(val, chr(pad_value) * pad_value))
[ "def", "_mysql_aes_pad", "(", "val", ")", ":", "val", "=", "_to_string", "(", "val", ")", "pad_value", "=", "16", "-", "(", "len", "(", "val", ")", "%", "16", ")", "return", "_to_binary", "(", "'{0}{1}'", ".", "format", "(", "val", ",", "chr", "(",...
Padding.
[ "Padding", "." ]
train
https://github.com/inveniosoftware/invenio-accounts/blob/b0d2f0739b00dbefea22ca15d7d374a1b4a63aec/invenio_accounts/hash.py#L47-L51
inveniosoftware/invenio-accounts
invenio_accounts/hash.py
_mysql_aes_unpad
def _mysql_aes_unpad(val): """Reverse padding.""" val = _to_string(val) pad_value = ord(val[-1]) return val[:-pad_value]
python
def _mysql_aes_unpad(val): """Reverse padding.""" val = _to_string(val) pad_value = ord(val[-1]) return val[:-pad_value]
[ "def", "_mysql_aes_unpad", "(", "val", ")", ":", "val", "=", "_to_string", "(", "val", ")", "pad_value", "=", "ord", "(", "val", "[", "-", "1", "]", ")", "return", "val", "[", ":", "-", "pad_value", "]" ]
Reverse padding.
[ "Reverse", "padding", "." ]
train
https://github.com/inveniosoftware/invenio-accounts/blob/b0d2f0739b00dbefea22ca15d7d374a1b4a63aec/invenio_accounts/hash.py#L54-L58
inveniosoftware/invenio-accounts
invenio_accounts/hash.py
mysql_aes_encrypt
def mysql_aes_encrypt(val, key): """Mysql AES encrypt value with secret key. :param val: Plain text value. :param key: The AES key. :returns: The encrypted AES value. """ assert isinstance(val, binary_type) or isinstance(val, text_type) assert isinstance(key, binary_type) or isinstance(key,...
python
def mysql_aes_encrypt(val, key): """Mysql AES encrypt value with secret key. :param val: Plain text value. :param key: The AES key. :returns: The encrypted AES value. """ assert isinstance(val, binary_type) or isinstance(val, text_type) assert isinstance(key, binary_type) or isinstance(key,...
[ "def", "mysql_aes_encrypt", "(", "val", ",", "key", ")", ":", "assert", "isinstance", "(", "val", ",", "binary_type", ")", "or", "isinstance", "(", "val", ",", "text_type", ")", "assert", "isinstance", "(", "key", ",", "binary_type", ")", "or", "isinstance...
Mysql AES encrypt value with secret key. :param val: Plain text value. :param key: The AES key. :returns: The encrypted AES value.
[ "Mysql", "AES", "encrypt", "value", "with", "secret", "key", "." ]
train
https://github.com/inveniosoftware/invenio-accounts/blob/b0d2f0739b00dbefea22ca15d7d374a1b4a63aec/invenio_accounts/hash.py#L66-L79
inveniosoftware/invenio-accounts
invenio_accounts/hash.py
mysql_aes_decrypt
def mysql_aes_decrypt(encrypted_val, key): """Mysql AES decrypt value with secret key. :param encrypted_val: Encrypted value. :param key: The AES key. :returns: The AES value decrypted. """ assert isinstance(encrypted_val, binary_type) \ or isinstance(encrypted_val, text_type) asser...
python
def mysql_aes_decrypt(encrypted_val, key): """Mysql AES decrypt value with secret key. :param encrypted_val: Encrypted value. :param key: The AES key. :returns: The AES value decrypted. """ assert isinstance(encrypted_val, binary_type) \ or isinstance(encrypted_val, text_type) asser...
[ "def", "mysql_aes_decrypt", "(", "encrypted_val", ",", "key", ")", ":", "assert", "isinstance", "(", "encrypted_val", ",", "binary_type", ")", "or", "isinstance", "(", "encrypted_val", ",", "text_type", ")", "assert", "isinstance", "(", "key", ",", "binary_type"...
Mysql AES decrypt value with secret key. :param encrypted_val: Encrypted value. :param key: The AES key. :returns: The AES value decrypted.
[ "Mysql", "AES", "decrypt", "value", "with", "secret", "key", "." ]
train
https://github.com/inveniosoftware/invenio-accounts/blob/b0d2f0739b00dbefea22ca15d7d374a1b4a63aec/invenio_accounts/hash.py#L82-L94
inveniosoftware/invenio-accounts
invenio_accounts/hash.py
InvenioAesEncryptedEmail.from_string
def from_string(cls, hash, **context): """Parse instance from configuration string in Modular Crypt Format.""" salt, checksum = parse_mc2(hash, cls.ident, handler=cls) return cls(salt=salt, checksum=checksum)
python
def from_string(cls, hash, **context): """Parse instance from configuration string in Modular Crypt Format.""" salt, checksum = parse_mc2(hash, cls.ident, handler=cls) return cls(salt=salt, checksum=checksum)
[ "def", "from_string", "(", "cls", ",", "hash", ",", "*", "*", "context", ")", ":", "salt", ",", "checksum", "=", "parse_mc2", "(", "hash", ",", "cls", ".", "ident", ",", "handler", "=", "cls", ")", "return", "cls", "(", "salt", "=", "salt", ",", ...
Parse instance from configuration string in Modular Crypt Format.
[ "Parse", "instance", "from", "configuration", "string", "in", "Modular", "Crypt", "Format", "." ]
train
https://github.com/inveniosoftware/invenio-accounts/blob/b0d2f0739b00dbefea22ca15d7d374a1b4a63aec/invenio_accounts/hash.py#L116-L120
inveniosoftware/invenio-accounts
invenio_accounts/hash.py
InvenioAesEncryptedEmail._calc_checksum
def _calc_checksum(self, secret): """Calculate string. :param secret: The secret key. :returns: The checksum. """ return str_to_uascii( hashlib.sha256(mysql_aes_encrypt(self.salt, secret)).hexdigest() )
python
def _calc_checksum(self, secret): """Calculate string. :param secret: The secret key. :returns: The checksum. """ return str_to_uascii( hashlib.sha256(mysql_aes_encrypt(self.salt, secret)).hexdigest() )
[ "def", "_calc_checksum", "(", "self", ",", "secret", ")", ":", "return", "str_to_uascii", "(", "hashlib", ".", "sha256", "(", "mysql_aes_encrypt", "(", "self", ".", "salt", ",", "secret", ")", ")", ".", "hexdigest", "(", ")", ")" ]
Calculate string. :param secret: The secret key. :returns: The checksum.
[ "Calculate", "string", "." ]
train
https://github.com/inveniosoftware/invenio-accounts/blob/b0d2f0739b00dbefea22ca15d7d374a1b4a63aec/invenio_accounts/hash.py#L126-L134
inveniosoftware/invenio-accounts
invenio_accounts/sessions.py
_ip2country
def _ip2country(ip): """Get user country.""" if ip: match = geolite2.reader().get(ip) return match.get('country', {}).get('iso_code') if match else None
python
def _ip2country(ip): """Get user country.""" if ip: match = geolite2.reader().get(ip) return match.get('country', {}).get('iso_code') if match else None
[ "def", "_ip2country", "(", "ip", ")", ":", "if", "ip", ":", "match", "=", "geolite2", ".", "reader", "(", ")", ".", "get", "(", "ip", ")", "return", "match", ".", "get", "(", "'country'", ",", "{", "}", ")", ".", "get", "(", "'iso_code'", ")", ...
Get user country.
[ "Get", "user", "country", "." ]
train
https://github.com/inveniosoftware/invenio-accounts/blob/b0d2f0739b00dbefea22ca15d7d374a1b4a63aec/invenio_accounts/sessions.py#L31-L35
inveniosoftware/invenio-accounts
invenio_accounts/sessions.py
_extract_info_from_useragent
def _extract_info_from_useragent(user_agent): """Extract extra informations from user.""" parsed_string = user_agent_parser.Parse(user_agent) return { 'os': parsed_string.get('os', {}).get('family'), 'browser': parsed_string.get('user_agent', {}).get('family'), 'browser_version': par...
python
def _extract_info_from_useragent(user_agent): """Extract extra informations from user.""" parsed_string = user_agent_parser.Parse(user_agent) return { 'os': parsed_string.get('os', {}).get('family'), 'browser': parsed_string.get('user_agent', {}).get('family'), 'browser_version': par...
[ "def", "_extract_info_from_useragent", "(", "user_agent", ")", ":", "parsed_string", "=", "user_agent_parser", ".", "Parse", "(", "user_agent", ")", "return", "{", "'os'", ":", "parsed_string", ".", "get", "(", "'os'", ",", "{", "}", ")", ".", "get", "(", ...
Extract extra informations from user.
[ "Extract", "extra", "informations", "from", "user", "." ]
train
https://github.com/inveniosoftware/invenio-accounts/blob/b0d2f0739b00dbefea22ca15d7d374a1b4a63aec/invenio_accounts/sessions.py#L38-L46
inveniosoftware/invenio-accounts
invenio_accounts/sessions.py
add_session
def add_session(session=None): r"""Add a session to the SessionActivity table. :param session: Flask Session object to add. If None, ``session`` is used. The object is expected to have a dictionary entry named ``"user_id"`` and a field ``sid_s`` """ user_id, sid_s = session['user_id'], ...
python
def add_session(session=None): r"""Add a session to the SessionActivity table. :param session: Flask Session object to add. If None, ``session`` is used. The object is expected to have a dictionary entry named ``"user_id"`` and a field ``sid_s`` """ user_id, sid_s = session['user_id'], ...
[ "def", "add_session", "(", "session", "=", "None", ")", ":", "user_id", ",", "sid_s", "=", "session", "[", "'user_id'", "]", ",", "session", ".", "sid_s", "with", "db", ".", "session", ".", "begin_nested", "(", ")", ":", "session_activity", "=", "Session...
r"""Add a session to the SessionActivity table. :param session: Flask Session object to add. If None, ``session`` is used. The object is expected to have a dictionary entry named ``"user_id"`` and a field ``sid_s``
[ "r", "Add", "a", "session", "to", "the", "SessionActivity", "table", "." ]
train
https://github.com/inveniosoftware/invenio-accounts/blob/b0d2f0739b00dbefea22ca15d7d374a1b4a63aec/invenio_accounts/sessions.py#L49-L67
inveniosoftware/invenio-accounts
invenio_accounts/sessions.py
login_listener
def login_listener(app, user): """Connect to the user_logged_in signal for table population. :param app: The Flask application. :param user: The :class:`invenio_accounts.models.User` instance. """ @after_this_request def add_user_session(response): """Regenerate current session and add ...
python
def login_listener(app, user): """Connect to the user_logged_in signal for table population. :param app: The Flask application. :param user: The :class:`invenio_accounts.models.User` instance. """ @after_this_request def add_user_session(response): """Regenerate current session and add ...
[ "def", "login_listener", "(", "app", ",", "user", ")", ":", "@", "after_this_request", "def", "add_user_session", "(", "response", ")", ":", "\"\"\"Regenerate current session and add to the SessionActivity table.\n\n .. note:: `flask.session.regenerate()` actually calls Flask-...
Connect to the user_logged_in signal for table population. :param app: The Flask application. :param user: The :class:`invenio_accounts.models.User` instance.
[ "Connect", "to", "the", "user_logged_in", "signal", "for", "table", "population", "." ]
train
https://github.com/inveniosoftware/invenio-accounts/blob/b0d2f0739b00dbefea22ca15d7d374a1b4a63aec/invenio_accounts/sessions.py#L70-L89
inveniosoftware/invenio-accounts
invenio_accounts/sessions.py
logout_listener
def logout_listener(app, user): """Connect to the user_logged_out signal. :param app: The Flask application. :param user: The :class:`invenio_accounts.models.User` instance. """ @after_this_request def _commit(response=None): if hasattr(session, 'sid_s'): delete_session(sess...
python
def logout_listener(app, user): """Connect to the user_logged_out signal. :param app: The Flask application. :param user: The :class:`invenio_accounts.models.User` instance. """ @after_this_request def _commit(response=None): if hasattr(session, 'sid_s'): delete_session(sess...
[ "def", "logout_listener", "(", "app", ",", "user", ")", ":", "@", "after_this_request", "def", "_commit", "(", "response", "=", "None", ")", ":", "if", "hasattr", "(", "session", ",", "'sid_s'", ")", ":", "delete_session", "(", "session", ".", "sid_s", "...
Connect to the user_logged_out signal. :param app: The Flask application. :param user: The :class:`invenio_accounts.models.User` instance.
[ "Connect", "to", "the", "user_logged_out", "signal", "." ]
train
https://github.com/inveniosoftware/invenio-accounts/blob/b0d2f0739b00dbefea22ca15d7d374a1b4a63aec/invenio_accounts/sessions.py#L92-L105
inveniosoftware/invenio-accounts
invenio_accounts/sessions.py
delete_session
def delete_session(sid_s): """Delete entries in the data- and kvsessionstore with the given sid_s. On a successful deletion, the flask-kvsession store returns 1 while the sqlalchemy datastore returns None. :param sid_s: The session ID. :returns: ``1`` if deletion was successful. """ # Remo...
python
def delete_session(sid_s): """Delete entries in the data- and kvsessionstore with the given sid_s. On a successful deletion, the flask-kvsession store returns 1 while the sqlalchemy datastore returns None. :param sid_s: The session ID. :returns: ``1`` if deletion was successful. """ # Remo...
[ "def", "delete_session", "(", "sid_s", ")", ":", "# Remove entries from sessionstore", "_sessionstore", ".", "delete", "(", "sid_s", ")", "# Find and remove the corresponding SessionActivity entry", "with", "db", ".", "session", ".", "begin_nested", "(", ")", ":", "Sess...
Delete entries in the data- and kvsessionstore with the given sid_s. On a successful deletion, the flask-kvsession store returns 1 while the sqlalchemy datastore returns None. :param sid_s: The session ID. :returns: ``1`` if deletion was successful.
[ "Delete", "entries", "in", "the", "data", "-", "and", "kvsessionstore", "with", "the", "given", "sid_s", "." ]
train
https://github.com/inveniosoftware/invenio-accounts/blob/b0d2f0739b00dbefea22ca15d7d374a1b4a63aec/invenio_accounts/sessions.py#L108-L122
inveniosoftware/invenio-accounts
invenio_accounts/sessions.py
delete_user_sessions
def delete_user_sessions(user): """Delete all active user sessions. :param user: User instance. :returns: If ``True`` then the session is successfully deleted. """ with db.session.begin_nested(): for s in user.active_sessions: _sessionstore.delete(s.sid_s) SessionActivi...
python
def delete_user_sessions(user): """Delete all active user sessions. :param user: User instance. :returns: If ``True`` then the session is successfully deleted. """ with db.session.begin_nested(): for s in user.active_sessions: _sessionstore.delete(s.sid_s) SessionActivi...
[ "def", "delete_user_sessions", "(", "user", ")", ":", "with", "db", ".", "session", ".", "begin_nested", "(", ")", ":", "for", "s", "in", "user", ".", "active_sessions", ":", "_sessionstore", ".", "delete", "(", "s", ".", "sid_s", ")", "SessionActivity", ...
Delete all active user sessions. :param user: User instance. :returns: If ``True`` then the session is successfully deleted.
[ "Delete", "all", "active", "user", "sessions", "." ]
train
https://github.com/inveniosoftware/invenio-accounts/blob/b0d2f0739b00dbefea22ca15d7d374a1b4a63aec/invenio_accounts/sessions.py#L125-L137
inveniosoftware/invenio-accounts
invenio_accounts/forms.py
confirm_register_form_factory
def confirm_register_form_factory(Form, app): """Return confirmation for extended registration form.""" if app.config.get('RECAPTCHA_PUBLIC_KEY') and \ app.config.get('RECAPTCHA_PRIVATE_KEY'): class ConfirmRegisterForm(Form): recaptcha = FormField(RegistrationFormRecaptcha, separ...
python
def confirm_register_form_factory(Form, app): """Return confirmation for extended registration form.""" if app.config.get('RECAPTCHA_PUBLIC_KEY') and \ app.config.get('RECAPTCHA_PRIVATE_KEY'): class ConfirmRegisterForm(Form): recaptcha = FormField(RegistrationFormRecaptcha, separ...
[ "def", "confirm_register_form_factory", "(", "Form", ",", "app", ")", ":", "if", "app", ".", "config", ".", "get", "(", "'RECAPTCHA_PUBLIC_KEY'", ")", "and", "app", ".", "config", ".", "get", "(", "'RECAPTCHA_PRIVATE_KEY'", ")", ":", "class", "ConfirmRegisterF...
Return confirmation for extended registration form.
[ "Return", "confirmation", "for", "extended", "registration", "form", "." ]
train
https://github.com/inveniosoftware/invenio-accounts/blob/b0d2f0739b00dbefea22ca15d7d374a1b4a63aec/invenio_accounts/forms.py#L31-L40
inveniosoftware/invenio-accounts
invenio_accounts/forms.py
register_form_factory
def register_form_factory(Form, app): """Return extended registration form.""" if app.config.get('RECAPTCHA_PUBLIC_KEY') and \ app.config.get('RECAPTCHA_PRIVATE_KEY'): class RegisterForm(Form): recaptcha = FormField(RegistrationFormRecaptcha, separator='.') return Regist...
python
def register_form_factory(Form, app): """Return extended registration form.""" if app.config.get('RECAPTCHA_PUBLIC_KEY') and \ app.config.get('RECAPTCHA_PRIVATE_KEY'): class RegisterForm(Form): recaptcha = FormField(RegistrationFormRecaptcha, separator='.') return Regist...
[ "def", "register_form_factory", "(", "Form", ",", "app", ")", ":", "if", "app", ".", "config", ".", "get", "(", "'RECAPTCHA_PUBLIC_KEY'", ")", "and", "app", ".", "config", ".", "get", "(", "'RECAPTCHA_PRIVATE_KEY'", ")", ":", "class", "RegisterForm", "(", ...
Return extended registration form.
[ "Return", "extended", "registration", "form", "." ]
train
https://github.com/inveniosoftware/invenio-accounts/blob/b0d2f0739b00dbefea22ca15d7d374a1b4a63aec/invenio_accounts/forms.py#L43-L52
inveniosoftware/invenio-accounts
invenio_accounts/forms.py
login_form_factory
def login_form_factory(Form, app): """Return extended login form.""" class LoginForm(Form): def __init__(self, *args, **kwargs): """Init the login form. .. note:: The ``remember me`` option will be completely disabled. """ super(LoginFor...
python
def login_form_factory(Form, app): """Return extended login form.""" class LoginForm(Form): def __init__(self, *args, **kwargs): """Init the login form. .. note:: The ``remember me`` option will be completely disabled. """ super(LoginFor...
[ "def", "login_form_factory", "(", "Form", ",", "app", ")", ":", "class", "LoginForm", "(", "Form", ")", ":", "def", "__init__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "\"\"\"Init the login form.\n\n .. note::\n\n ...
Return extended login form.
[ "Return", "extended", "login", "form", "." ]
train
https://github.com/inveniosoftware/invenio-accounts/blob/b0d2f0739b00dbefea22ca15d7d374a1b4a63aec/invenio_accounts/forms.py#L55-L69
inveniosoftware/invenio-accounts
invenio_accounts/admin.py
UserView.on_model_change
def on_model_change(self, form, User, is_created): """Hash password when saving.""" if form.password.data is not None: pwd_ctx = current_app.extensions['security'].pwd_context if pwd_ctx.identify(form.password.data) is None: User.password = hash_password(form.pass...
python
def on_model_change(self, form, User, is_created): """Hash password when saving.""" if form.password.data is not None: pwd_ctx = current_app.extensions['security'].pwd_context if pwd_ctx.identify(form.password.data) is None: User.password = hash_password(form.pass...
[ "def", "on_model_change", "(", "self", ",", "form", ",", "User", ",", "is_created", ")", ":", "if", "form", ".", "password", ".", "data", "is", "not", "None", ":", "pwd_ctx", "=", "current_app", ".", "extensions", "[", "'security'", "]", ".", "pwd_contex...
Hash password when saving.
[ "Hash", "password", "when", "saving", "." ]
train
https://github.com/inveniosoftware/invenio-accounts/blob/b0d2f0739b00dbefea22ca15d7d374a1b4a63aec/invenio_accounts/admin.py#L78-L83
inveniosoftware/invenio-accounts
invenio_accounts/admin.py
UserView.after_model_change
def after_model_change(self, form, User, is_created): """Send password instructions if desired.""" if is_created and form.notification.data is True: send_reset_password_instructions(User)
python
def after_model_change(self, form, User, is_created): """Send password instructions if desired.""" if is_created and form.notification.data is True: send_reset_password_instructions(User)
[ "def", "after_model_change", "(", "self", ",", "form", ",", "User", ",", "is_created", ")", ":", "if", "is_created", "and", "form", ".", "notification", ".", "data", "is", "True", ":", "send_reset_password_instructions", "(", "User", ")" ]
Send password instructions if desired.
[ "Send", "password", "instructions", "if", "desired", "." ]
train
https://github.com/inveniosoftware/invenio-accounts/blob/b0d2f0739b00dbefea22ca15d7d374a1b4a63aec/invenio_accounts/admin.py#L85-L88
inveniosoftware/invenio-accounts
invenio_accounts/admin.py
UserView.action_inactivate
def action_inactivate(self, ids): """Inactivate users.""" try: count = 0 for user_id in ids: user = _datastore.get_user(user_id) if user is None: raise ValueError(_("Cannot find user.")) if _datastore.deactivate_...
python
def action_inactivate(self, ids): """Inactivate users.""" try: count = 0 for user_id in ids: user = _datastore.get_user(user_id) if user is None: raise ValueError(_("Cannot find user.")) if _datastore.deactivate_...
[ "def", "action_inactivate", "(", "self", ",", "ids", ")", ":", "try", ":", "count", "=", "0", "for", "user_id", "in", "ids", ":", "user", "=", "_datastore", ".", "get_user", "(", "user_id", ")", "if", "user", "is", "None", ":", "raise", "ValueError", ...
Inactivate users.
[ "Inactivate", "users", "." ]
train
https://github.com/inveniosoftware/invenio-accounts/blob/b0d2f0739b00dbefea22ca15d7d374a1b4a63aec/invenio_accounts/admin.py#L93-L111
inveniosoftware/invenio-accounts
invenio_accounts/admin.py
SessionActivityView.delete_model
def delete_model(self, model): """Delete a specific session.""" if SessionActivity.is_current(sid_s=model.sid_s): flash('You could not remove your current session', 'error') return delete_session(sid_s=model.sid_s) db.session.commit()
python
def delete_model(self, model): """Delete a specific session.""" if SessionActivity.is_current(sid_s=model.sid_s): flash('You could not remove your current session', 'error') return delete_session(sid_s=model.sid_s) db.session.commit()
[ "def", "delete_model", "(", "self", ",", "model", ")", ":", "if", "SessionActivity", ".", "is_current", "(", "sid_s", "=", "model", ".", "sid_s", ")", ":", "flash", "(", "'You could not remove your current session'", ",", "'error'", ")", "return", "delete_sessio...
Delete a specific session.
[ "Delete", "a", "specific", "session", "." ]
train
https://github.com/inveniosoftware/invenio-accounts/blob/b0d2f0739b00dbefea22ca15d7d374a1b4a63aec/invenio_accounts/admin.py#L193-L199
inveniosoftware/invenio-accounts
invenio_accounts/admin.py
SessionActivityView.action_delete
def action_delete(self, ids): """Delete selected sessions.""" is_current = any(SessionActivity.is_current(sid_s=id_) for id_ in ids) if is_current: flash('You could not remove your current session', 'error') return for id_ in ids: delete_session(sid_s=...
python
def action_delete(self, ids): """Delete selected sessions.""" is_current = any(SessionActivity.is_current(sid_s=id_) for id_ in ids) if is_current: flash('You could not remove your current session', 'error') return for id_ in ids: delete_session(sid_s=...
[ "def", "action_delete", "(", "self", ",", "ids", ")", ":", "is_current", "=", "any", "(", "SessionActivity", ".", "is_current", "(", "sid_s", "=", "id_", ")", "for", "id_", "in", "ids", ")", "if", "is_current", ":", "flash", "(", "'You could not remove you...
Delete selected sessions.
[ "Delete", "selected", "sessions", "." ]
train
https://github.com/inveniosoftware/invenio-accounts/blob/b0d2f0739b00dbefea22ca15d7d374a1b4a63aec/invenio_accounts/admin.py#L203-L211
inveniosoftware/invenio-accounts
invenio_accounts/cli.py
users_create
def users_create(email, password, active): """Create a user.""" kwargs = dict(email=email, password=password, active='y' if active else '') form = ConfirmRegisterForm(MultiDict(kwargs), csrf_enabled=False) if form.validate(): kwargs['password'] = hash_password(kwargs['password']) kwarg...
python
def users_create(email, password, active): """Create a user.""" kwargs = dict(email=email, password=password, active='y' if active else '') form = ConfirmRegisterForm(MultiDict(kwargs), csrf_enabled=False) if form.validate(): kwargs['password'] = hash_password(kwargs['password']) kwarg...
[ "def", "users_create", "(", "email", ",", "password", ",", "active", ")", ":", "kwargs", "=", "dict", "(", "email", "=", "email", ",", "password", "=", "password", ",", "active", "=", "'y'", "if", "active", "else", "''", ")", "form", "=", "ConfirmRegis...
Create a user.
[ "Create", "a", "user", "." ]
train
https://github.com/inveniosoftware/invenio-accounts/blob/b0d2f0739b00dbefea22ca15d7d374a1b4a63aec/invenio_accounts/cli.py#L51-L65
inveniosoftware/invenio-accounts
invenio_accounts/tasks.py
send_security_email
def send_security_email(data): """Celery task to send security email. :param data: Contains the email data. """ msg = Message() msg.__dict__.update(data) current_app.extensions['mail'].send(msg)
python
def send_security_email(data): """Celery task to send security email. :param data: Contains the email data. """ msg = Message() msg.__dict__.update(data) current_app.extensions['mail'].send(msg)
[ "def", "send_security_email", "(", "data", ")", ":", "msg", "=", "Message", "(", ")", "msg", ".", "__dict__", ".", "update", "(", "data", ")", "current_app", ".", "extensions", "[", "'mail'", "]", ".", "send", "(", "msg", ")" ]
Celery task to send security email. :param data: Contains the email data.
[ "Celery", "task", "to", "send", "security", "email", "." ]
train
https://github.com/inveniosoftware/invenio-accounts/blob/b0d2f0739b00dbefea22ca15d7d374a1b4a63aec/invenio_accounts/tasks.py#L24-L31
inveniosoftware/invenio-accounts
invenio_accounts/tasks.py
clean_session_table
def clean_session_table(): """Automatically clean session table. To enable a periodically clean of the session table, you should configure the task as a celery periodic task. .. code-block:: python from datetime import timedelta CELERYBEAT_SCHEDULE = { 'session_cleaner': {...
python
def clean_session_table(): """Automatically clean session table. To enable a periodically clean of the session table, you should configure the task as a celery periodic task. .. code-block:: python from datetime import timedelta CELERYBEAT_SCHEDULE = { 'session_cleaner': {...
[ "def", "clean_session_table", "(", ")", ":", "sessions", "=", "SessionActivity", ".", "query_by_expired", "(", ")", ".", "all", "(", ")", "for", "session", "in", "sessions", ":", "delete_session", "(", "sid_s", "=", "session", ".", "sid_s", ")", "db", ".",...
Automatically clean session table. To enable a periodically clean of the session table, you should configure the task as a celery periodic task. .. code-block:: python from datetime import timedelta CELERYBEAT_SCHEDULE = { 'session_cleaner': { 'task': 'invenio_...
[ "Automatically", "clean", "session", "table", "." ]
train
https://github.com/inveniosoftware/invenio-accounts/blob/b0d2f0739b00dbefea22ca15d7d374a1b4a63aec/invenio_accounts/tasks.py#L35-L57
inveniosoftware/invenio-accounts
invenio_accounts/alembic/9848d0149abd_create_accounts_tables.py
upgrade
def upgrade(): """Upgrade database.""" op.create_table( 'accounts_role', sa.Column('id', sa.Integer(), nullable=False), sa.Column('name', sa.String(length=80), nullable=True), sa.Column('description', sa.String(length=255), nullable=True), sa.PrimaryKeyConstraint('id'), ...
python
def upgrade(): """Upgrade database.""" op.create_table( 'accounts_role', sa.Column('id', sa.Integer(), nullable=False), sa.Column('name', sa.String(length=80), nullable=True), sa.Column('description', sa.String(length=255), nullable=True), sa.PrimaryKeyConstraint('id'), ...
[ "def", "upgrade", "(", ")", ":", "op", ".", "create_table", "(", "'accounts_role'", ",", "sa", ".", "Column", "(", "'id'", ",", "sa", ".", "Integer", "(", ")", ",", "nullable", "=", "False", ")", ",", "sa", ".", "Column", "(", "'name'", ",", "sa", ...
Upgrade database.
[ "Upgrade", "database", "." ]
train
https://github.com/inveniosoftware/invenio-accounts/blob/b0d2f0739b00dbefea22ca15d7d374a1b4a63aec/invenio_accounts/alembic/9848d0149abd_create_accounts_tables.py#L23-L86
inveniosoftware/invenio-accounts
invenio_accounts/alembic/9848d0149abd_create_accounts_tables.py
downgrade
def downgrade(): """Downgrade database.""" ctx = op.get_context() insp = Inspector.from_engine(ctx.connection.engine) for fk in insp.get_foreign_keys('transaction'): if fk['referred_table'] == 'accounts_user': op.drop_constraint( op.f(fk['name']), 'transaction', type...
python
def downgrade(): """Downgrade database.""" ctx = op.get_context() insp = Inspector.from_engine(ctx.connection.engine) for fk in insp.get_foreign_keys('transaction'): if fk['referred_table'] == 'accounts_user': op.drop_constraint( op.f(fk['name']), 'transaction', type...
[ "def", "downgrade", "(", ")", ":", "ctx", "=", "op", ".", "get_context", "(", ")", "insp", "=", "Inspector", ".", "from_engine", "(", "ctx", ".", "connection", ".", "engine", ")", "for", "fk", "in", "insp", ".", "get_foreign_keys", "(", "'transaction'", ...
Downgrade database.
[ "Downgrade", "database", "." ]
train
https://github.com/inveniosoftware/invenio-accounts/blob/b0d2f0739b00dbefea22ca15d7d374a1b4a63aec/invenio_accounts/alembic/9848d0149abd_create_accounts_tables.py#L89-L106
inveniosoftware/invenio-accounts
invenio_accounts/utils.py
jwt_create_token
def jwt_create_token(user_id=None, additional_data=None): """Encode the JWT token. :param int user_id: Addition of user_id. :param dict additional_data: Additional information for the token. :returns: The encoded token. :rtype: str .. note:: Definition of the JWT claims: * exp...
python
def jwt_create_token(user_id=None, additional_data=None): """Encode the JWT token. :param int user_id: Addition of user_id. :param dict additional_data: Additional information for the token. :returns: The encoded token. :rtype: str .. note:: Definition of the JWT claims: * exp...
[ "def", "jwt_create_token", "(", "user_id", "=", "None", ",", "additional_data", "=", "None", ")", ":", "# Create an ID", "uid", "=", "str", "(", "uuid", ".", "uuid4", "(", ")", ")", "# The time in UTC now", "now", "=", "datetime", ".", "utcnow", "(", ")", ...
Encode the JWT token. :param int user_id: Addition of user_id. :param dict additional_data: Additional information for the token. :returns: The encoded token. :rtype: str .. note:: Definition of the JWT claims: * exp: ((Expiration Time) expiration time of the JWT. * sub: (...
[ "Encode", "the", "JWT", "token", "." ]
train
https://github.com/inveniosoftware/invenio-accounts/blob/b0d2f0739b00dbefea22ca15d7d374a1b4a63aec/invenio_accounts/utils.py#L22-L57
inveniosoftware/invenio-accounts
invenio_accounts/utils.py
jwt_decode_token
def jwt_decode_token(token): """Decode the JWT token. :param str token: Additional information for the token. :returns: The token data. :rtype: dict """ try: return decode( token, current_app.config['ACCOUNTS_JWT_SECRET_KEY'], algorithms=[ ...
python
def jwt_decode_token(token): """Decode the JWT token. :param str token: Additional information for the token. :returns: The token data. :rtype: dict """ try: return decode( token, current_app.config['ACCOUNTS_JWT_SECRET_KEY'], algorithms=[ ...
[ "def", "jwt_decode_token", "(", "token", ")", ":", "try", ":", "return", "decode", "(", "token", ",", "current_app", ".", "config", "[", "'ACCOUNTS_JWT_SECRET_KEY'", "]", ",", "algorithms", "=", "[", "current_app", ".", "config", "[", "'ACCOUNTS_JWT_ALOGORITHM'"...
Decode the JWT token. :param str token: Additional information for the token. :returns: The token data. :rtype: dict
[ "Decode", "the", "JWT", "token", "." ]
train
https://github.com/inveniosoftware/invenio-accounts/blob/b0d2f0739b00dbefea22ca15d7d374a1b4a63aec/invenio_accounts/utils.py#L60-L78
inveniosoftware/invenio-accounts
invenio_accounts/utils.py
set_session_info
def set_session_info(app, response, **extra): """Add X-Session-ID and X-User-ID to http response.""" session_id = getattr(session, 'sid_s', None) if session_id: response.headers['X-Session-ID'] = session_id if current_user.is_authenticated: response.headers['X-User-ID'] = current_user.ge...
python
def set_session_info(app, response, **extra): """Add X-Session-ID and X-User-ID to http response.""" session_id = getattr(session, 'sid_s', None) if session_id: response.headers['X-Session-ID'] = session_id if current_user.is_authenticated: response.headers['X-User-ID'] = current_user.ge...
[ "def", "set_session_info", "(", "app", ",", "response", ",", "*", "*", "extra", ")", ":", "session_id", "=", "getattr", "(", "session", ",", "'sid_s'", ",", "None", ")", "if", "session_id", ":", "response", ".", "headers", "[", "'X-Session-ID'", "]", "="...
Add X-Session-ID and X-User-ID to http response.
[ "Add", "X", "-", "Session", "-", "ID", "and", "X", "-", "User", "-", "ID", "to", "http", "response", "." ]
train
https://github.com/inveniosoftware/invenio-accounts/blob/b0d2f0739b00dbefea22ca15d7d374a1b4a63aec/invenio_accounts/utils.py#L81-L87
inveniosoftware/invenio-accounts
invenio_accounts/views/security.py
security
def security(): """View for security page.""" sessions = SessionActivity.query_by_user( user_id=current_user.get_id() ).all() master_session = None for index, session in enumerate(sessions): if SessionActivity.is_current(session.sid_s): master_session = session ...
python
def security(): """View for security page.""" sessions = SessionActivity.query_by_user( user_id=current_user.get_id() ).all() master_session = None for index, session in enumerate(sessions): if SessionActivity.is_current(session.sid_s): master_session = session ...
[ "def", "security", "(", ")", ":", "sessions", "=", "SessionActivity", ".", "query_by_user", "(", "user_id", "=", "current_user", ".", "get_id", "(", ")", ")", ".", "all", "(", ")", "master_session", "=", "None", "for", "index", ",", "session", "in", "enu...
View for security page.
[ "View", "for", "security", "page", "." ]
train
https://github.com/inveniosoftware/invenio-accounts/blob/b0d2f0739b00dbefea22ca15d7d374a1b4a63aec/invenio_accounts/views/security.py#L35-L50
inveniosoftware/invenio-accounts
invenio_accounts/views/security.py
revoke_session
def revoke_session(): """Revoke a session.""" form = RevokeForm(request.form) if not form.validate_on_submit(): abort(403) sid_s = form.data['sid_s'] if SessionActivity.query.filter_by( user_id=current_user.get_id(), sid_s=sid_s).count() == 1: delete_session(sid_s=sid_s)...
python
def revoke_session(): """Revoke a session.""" form = RevokeForm(request.form) if not form.validate_on_submit(): abort(403) sid_s = form.data['sid_s'] if SessionActivity.query.filter_by( user_id=current_user.get_id(), sid_s=sid_s).count() == 1: delete_session(sid_s=sid_s)...
[ "def", "revoke_session", "(", ")", ":", "form", "=", "RevokeForm", "(", "request", ".", "form", ")", "if", "not", "form", ".", "validate_on_submit", "(", ")", ":", "abort", "(", "403", ")", "sid_s", "=", "form", ".", "data", "[", "'sid_s'", "]", "if"...
Revoke a session.
[ "Revoke", "a", "session", "." ]
train
https://github.com/inveniosoftware/invenio-accounts/blob/b0d2f0739b00dbefea22ca15d7d374a1b4a63aec/invenio_accounts/views/security.py#L54-L71
inveniosoftware/invenio-accounts
invenio_accounts/alembic/e12419831262_add_new_columns_on_sessionactivity.py
upgrade
def upgrade(): """Upgrade database.""" with op.batch_alter_table('accounts_user_session_activity') as batch_op: batch_op.add_column(sa.Column('browser', sa.String(80), nullable=True)) batch_op.add_column( sa.Column('browser_version', sa.String(30), nullable=True)) batch_op.ad...
python
def upgrade(): """Upgrade database.""" with op.batch_alter_table('accounts_user_session_activity') as batch_op: batch_op.add_column(sa.Column('browser', sa.String(80), nullable=True)) batch_op.add_column( sa.Column('browser_version', sa.String(30), nullable=True)) batch_op.ad...
[ "def", "upgrade", "(", ")", ":", "with", "op", ".", "batch_alter_table", "(", "'accounts_user_session_activity'", ")", "as", "batch_op", ":", "batch_op", ".", "add_column", "(", "sa", ".", "Column", "(", "'browser'", ",", "sa", ".", "String", "(", "80", ")...
Upgrade database.
[ "Upgrade", "database", "." ]
train
https://github.com/inveniosoftware/invenio-accounts/blob/b0d2f0739b00dbefea22ca15d7d374a1b4a63aec/invenio_accounts/alembic/e12419831262_add_new_columns_on_sessionactivity.py#L21-L34
inveniosoftware/invenio-accounts
invenio_accounts/models.py
SessionActivity.query_by_expired
def query_by_expired(cls): """Query to select all expired sessions.""" lifetime = current_app.permanent_session_lifetime expired_moment = datetime.utcnow() - lifetime return cls.query.filter(cls.created < expired_moment)
python
def query_by_expired(cls): """Query to select all expired sessions.""" lifetime = current_app.permanent_session_lifetime expired_moment = datetime.utcnow() - lifetime return cls.query.filter(cls.created < expired_moment)
[ "def", "query_by_expired", "(", "cls", ")", ":", "lifetime", "=", "current_app", ".", "permanent_session_lifetime", "expired_moment", "=", "datetime", ".", "utcnow", "(", ")", "-", "lifetime", "return", "cls", ".", "query", ".", "filter", "(", "cls", ".", "c...
Query to select all expired sessions.
[ "Query", "to", "select", "all", "expired", "sessions", "." ]
train
https://github.com/inveniosoftware/invenio-accounts/blob/b0d2f0739b00dbefea22ca15d7d374a1b4a63aec/invenio_accounts/models.py#L141-L145
inveniosoftware/invenio-accounts
invenio_accounts/ext.py
InvenioAccounts.monkey_patch_flask_security
def monkey_patch_flask_security(): """Monkey-patch Flask-Security.""" if utils.get_hmac != get_hmac: utils.get_hmac = get_hmac if utils.hash_password != hash_password: utils.hash_password = hash_password changeable.hash_password = hash_password rec...
python
def monkey_patch_flask_security(): """Monkey-patch Flask-Security.""" if utils.get_hmac != get_hmac: utils.get_hmac = get_hmac if utils.hash_password != hash_password: utils.hash_password = hash_password changeable.hash_password = hash_password rec...
[ "def", "monkey_patch_flask_security", "(", ")", ":", "if", "utils", ".", "get_hmac", "!=", "get_hmac", ":", "utils", ".", "get_hmac", "=", "get_hmac", "if", "utils", ".", "hash_password", "!=", "hash_password", ":", "utils", ".", "hash_password", "=", "hash_pa...
Monkey-patch Flask-Security.
[ "Monkey", "-", "patch", "Flask", "-", "Security", "." ]
train
https://github.com/inveniosoftware/invenio-accounts/blob/b0d2f0739b00dbefea22ca15d7d374a1b4a63aec/invenio_accounts/ext.py#L72-L94
inveniosoftware/invenio-accounts
invenio_accounts/ext.py
InvenioAccounts.init_app
def init_app(self, app, sessionstore=None, register_blueprint=True): """Flask application initialization. The following actions are executed: #. Initialize the configuration. #. Monkey-patch Flask-Security. #. Create the user datastore. #. Create the sessionstore. ...
python
def init_app(self, app, sessionstore=None, register_blueprint=True): """Flask application initialization. The following actions are executed: #. Initialize the configuration. #. Monkey-patch Flask-Security. #. Create the user datastore. #. Create the sessionstore. ...
[ "def", "init_app", "(", "self", ",", "app", ",", "sessionstore", "=", "None", ",", "register_blueprint", "=", "True", ")", ":", "self", ".", "init_config", "(", "app", ")", "# Monkey-patch Flask-Security", "InvenioAccounts", ".", "monkey_patch_flask_security", "("...
Flask application initialization. The following actions are executed: #. Initialize the configuration. #. Monkey-patch Flask-Security. #. Create the user datastore. #. Create the sessionstore. #. Initialize the extension, the forms to register users and c...
[ "Flask", "application", "initialization", "." ]
train
https://github.com/inveniosoftware/invenio-accounts/blob/b0d2f0739b00dbefea22ca15d7d374a1b4a63aec/invenio_accounts/ext.py#L133-L208
inveniosoftware/invenio-accounts
invenio_accounts/ext.py
InvenioAccounts.init_config
def init_config(self, app): """Initialize configuration. :param app: The Flask application. """ try: pkg_resources.get_distribution('celery') app.config.setdefault( "ACCOUNTS_USE_CELERY", not (app.debug or app.testing)) except pkg_resource...
python
def init_config(self, app): """Initialize configuration. :param app: The Flask application. """ try: pkg_resources.get_distribution('celery') app.config.setdefault( "ACCOUNTS_USE_CELERY", not (app.debug or app.testing)) except pkg_resource...
[ "def", "init_config", "(", "self", ",", "app", ")", ":", "try", ":", "pkg_resources", ".", "get_distribution", "(", "'celery'", ")", "app", ".", "config", ".", "setdefault", "(", "\"ACCOUNTS_USE_CELERY\"", ",", "not", "(", "app", ".", "debug", "or", "app",...
Initialize configuration. :param app: The Flask application.
[ "Initialize", "configuration", "." ]
train
https://github.com/inveniosoftware/invenio-accounts/blob/b0d2f0739b00dbefea22ca15d7d374a1b4a63aec/invenio_accounts/ext.py#L210-L264
inveniosoftware/invenio-accounts
invenio_accounts/ext.py
InvenioAccounts._enable_session_activity
def _enable_session_activity(self, app): """Enable session activity.""" user_logged_in.connect(login_listener, app) user_logged_out.connect(logout_listener, app) from .views.settings import blueprint from .views.security import security, revoke_session blueprint.route('/s...
python
def _enable_session_activity(self, app): """Enable session activity.""" user_logged_in.connect(login_listener, app) user_logged_out.connect(logout_listener, app) from .views.settings import blueprint from .views.security import security, revoke_session blueprint.route('/s...
[ "def", "_enable_session_activity", "(", "self", ",", "app", ")", ":", "user_logged_in", ".", "connect", "(", "login_listener", ",", "app", ")", "user_logged_out", ".", "connect", "(", "logout_listener", ",", "app", ")", "from", ".", "views", ".", "settings", ...
Enable session activity.
[ "Enable", "session", "activity", "." ]
train
https://github.com/inveniosoftware/invenio-accounts/blob/b0d2f0739b00dbefea22ca15d7d374a1b4a63aec/invenio_accounts/ext.py#L266-L273
inveniosoftware/invenio-accounts
invenio_accounts/ext.py
InvenioAccountsREST.init_app
def init_app(self, app, sessionstore=None, register_blueprint=False): """Flask application initialization. :param app: The Flask application. :param sessionstore: store for sessions. Passed to ``flask-kvsession``. If ``None`` then Redis is configured. (Default: ``None``)...
python
def init_app(self, app, sessionstore=None, register_blueprint=False): """Flask application initialization. :param app: The Flask application. :param sessionstore: store for sessions. Passed to ``flask-kvsession``. If ``None`` then Redis is configured. (Default: ``None``)...
[ "def", "init_app", "(", "self", ",", "app", ",", "sessionstore", "=", "None", ",", "register_blueprint", "=", "False", ")", ":", "return", "super", "(", "InvenioAccountsREST", ",", "self", ")", ".", "init_app", "(", "app", ",", "sessionstore", "=", "sessio...
Flask application initialization. :param app: The Flask application. :param sessionstore: store for sessions. Passed to ``flask-kvsession``. If ``None`` then Redis is configured. (Default: ``None``) :param register_blueprint: If ``True``, the application registers the ...
[ "Flask", "application", "initialization", "." ]
train
https://github.com/inveniosoftware/invenio-accounts/blob/b0d2f0739b00dbefea22ca15d7d374a1b4a63aec/invenio_accounts/ext.py#L279-L292
inveniosoftware/invenio-accounts
invenio_accounts/ext.py
InvenioAccountsUI.init_app
def init_app(self, app, sessionstore=None, register_blueprint=True): """Flask application initialization. :param app: The Flask application. :param sessionstore: store for sessions. Passed to ``flask-kvsession``. If ``None`` then Redis is configured. (Default: ``None``) ...
python
def init_app(self, app, sessionstore=None, register_blueprint=True): """Flask application initialization. :param app: The Flask application. :param sessionstore: store for sessions. Passed to ``flask-kvsession``. If ``None`` then Redis is configured. (Default: ``None``) ...
[ "def", "init_app", "(", "self", ",", "app", ",", "sessionstore", "=", "None", ",", "register_blueprint", "=", "True", ")", ":", "self", ".", "make_session_permanent", "(", "app", ")", "return", "super", "(", "InvenioAccountsUI", ",", "self", ")", ".", "ini...
Flask application initialization. :param app: The Flask application. :param sessionstore: store for sessions. Passed to ``flask-kvsession``. If ``None`` then Redis is configured. (Default: ``None``) :param register_blueprint: If ``True``, the application registers the ...
[ "Flask", "application", "initialization", "." ]
train
https://github.com/inveniosoftware/invenio-accounts/blob/b0d2f0739b00dbefea22ca15d7d374a1b4a63aec/invenio_accounts/ext.py#L298-L312
inveniosoftware/invenio-accounts
invenio_accounts/datastore.py
SessionAwareSQLAlchemyUserDatastore.deactivate_user
def deactivate_user(self, user): """Deactivate a user. :param user: A :class:`invenio_accounts.models.User` instance. :returns: The datastore instance. """ res = super(SessionAwareSQLAlchemyUserDatastore, self).deactivate_user( user) if res: dele...
python
def deactivate_user(self, user): """Deactivate a user. :param user: A :class:`invenio_accounts.models.User` instance. :returns: The datastore instance. """ res = super(SessionAwareSQLAlchemyUserDatastore, self).deactivate_user( user) if res: dele...
[ "def", "deactivate_user", "(", "self", ",", "user", ")", ":", "res", "=", "super", "(", "SessionAwareSQLAlchemyUserDatastore", ",", "self", ")", ".", "deactivate_user", "(", "user", ")", "if", "res", ":", "delete_user_sessions", "(", "user", ")", "return", "...
Deactivate a user. :param user: A :class:`invenio_accounts.models.User` instance. :returns: The datastore instance.
[ "Deactivate", "a", "user", "." ]
train
https://github.com/inveniosoftware/invenio-accounts/blob/b0d2f0739b00dbefea22ca15d7d374a1b4a63aec/invenio_accounts/datastore.py#L21-L31
iamteem/redisco
redisco/models/base.py
_initialize_attributes
def _initialize_attributes(model_class, name, bases, attrs): """Initialize the attributes of the model.""" model_class._attributes = {} for k, v in attrs.iteritems(): if isinstance(v, Attribute): model_class._attributes[k] = v v.name = v.name or k
python
def _initialize_attributes(model_class, name, bases, attrs): """Initialize the attributes of the model.""" model_class._attributes = {} for k, v in attrs.iteritems(): if isinstance(v, Attribute): model_class._attributes[k] = v v.name = v.name or k
[ "def", "_initialize_attributes", "(", "model_class", ",", "name", ",", "bases", ",", "attrs", ")", ":", "model_class", ".", "_attributes", "=", "{", "}", "for", "k", ",", "v", "in", "attrs", ".", "iteritems", "(", ")", ":", "if", "isinstance", "(", "v"...
Initialize the attributes of the model.
[ "Initialize", "the", "attributes", "of", "the", "model", "." ]
train
https://github.com/iamteem/redisco/blob/a7ba19ff3c38061d6d8bc0c10fa754baadcfeb91/redisco/models/base.py#L19-L25
iamteem/redisco
redisco/models/base.py
_initialize_referenced
def _initialize_referenced(model_class, attribute): """Adds a property to the target of a reference field that returns the list of associated objects. """ # this should be a descriptor def _related_objects(self): return (model_class.objects .filter(**{attribute.attname: self....
python
def _initialize_referenced(model_class, attribute): """Adds a property to the target of a reference field that returns the list of associated objects. """ # this should be a descriptor def _related_objects(self): return (model_class.objects .filter(**{attribute.attname: self....
[ "def", "_initialize_referenced", "(", "model_class", ",", "attribute", ")", ":", "# this should be a descriptor", "def", "_related_objects", "(", "self", ")", ":", "return", "(", "model_class", ".", "objects", ".", "filter", "(", "*", "*", "{", "attribute", ".",...
Adds a property to the target of a reference field that returns the list of associated objects.
[ "Adds", "a", "property", "to", "the", "target", "of", "a", "reference", "field", "that", "returns", "the", "list", "of", "associated", "objects", "." ]
train
https://github.com/iamteem/redisco/blob/a7ba19ff3c38061d6d8bc0c10fa754baadcfeb91/redisco/models/base.py#L27-L43
iamteem/redisco
redisco/models/base.py
_initialize_lists
def _initialize_lists(model_class, name, bases, attrs): """Stores the list fields descriptors of a model.""" model_class._lists = {} for k, v in attrs.iteritems(): if isinstance(v, ListField): model_class._lists[k] = v v.name = v.name or k
python
def _initialize_lists(model_class, name, bases, attrs): """Stores the list fields descriptors of a model.""" model_class._lists = {} for k, v in attrs.iteritems(): if isinstance(v, ListField): model_class._lists[k] = v v.name = v.name or k
[ "def", "_initialize_lists", "(", "model_class", ",", "name", ",", "bases", ",", "attrs", ")", ":", "model_class", ".", "_lists", "=", "{", "}", "for", "k", ",", "v", "in", "attrs", ".", "iteritems", "(", ")", ":", "if", "isinstance", "(", "v", ",", ...
Stores the list fields descriptors of a model.
[ "Stores", "the", "list", "fields", "descriptors", "of", "a", "model", "." ]
train
https://github.com/iamteem/redisco/blob/a7ba19ff3c38061d6d8bc0c10fa754baadcfeb91/redisco/models/base.py#L45-L51
iamteem/redisco
redisco/models/base.py
_initialize_references
def _initialize_references(model_class, name, bases, attrs): """Stores the list of reference field descriptors of a model.""" model_class._references = {} h = {} deferred = [] for k, v in attrs.iteritems(): if isinstance(v, ReferenceField): model_class._references[k] = v ...
python
def _initialize_references(model_class, name, bases, attrs): """Stores the list of reference field descriptors of a model.""" model_class._references = {} h = {} deferred = [] for k, v in attrs.iteritems(): if isinstance(v, ReferenceField): model_class._references[k] = v ...
[ "def", "_initialize_references", "(", "model_class", ",", "name", ",", "bases", ",", "attrs", ")", ":", "model_class", ".", "_references", "=", "{", "}", "h", "=", "{", "}", "deferred", "=", "[", "]", "for", "k", ",", "v", "in", "attrs", ".", "iterit...
Stores the list of reference field descriptors of a model.
[ "Stores", "the", "list", "of", "reference", "field", "descriptors", "of", "a", "model", "." ]
train
https://github.com/iamteem/redisco/blob/a7ba19ff3c38061d6d8bc0c10fa754baadcfeb91/redisco/models/base.py#L53-L69
iamteem/redisco
redisco/models/base.py
_initialize_indices
def _initialize_indices(model_class, name, bases, attrs): """Stores the list of indexed attributes.""" model_class._indices = [] for k, v in attrs.iteritems(): if isinstance(v, (Attribute, ListField)) and v.indexed: model_class._indices.append(k) if model_class._meta['indices']: ...
python
def _initialize_indices(model_class, name, bases, attrs): """Stores the list of indexed attributes.""" model_class._indices = [] for k, v in attrs.iteritems(): if isinstance(v, (Attribute, ListField)) and v.indexed: model_class._indices.append(k) if model_class._meta['indices']: ...
[ "def", "_initialize_indices", "(", "model_class", ",", "name", ",", "bases", ",", "attrs", ")", ":", "model_class", ".", "_indices", "=", "[", "]", "for", "k", ",", "v", "in", "attrs", ".", "iteritems", "(", ")", ":", "if", "isinstance", "(", "v", ",...
Stores the list of indexed attributes.
[ "Stores", "the", "list", "of", "indexed", "attributes", "." ]
train
https://github.com/iamteem/redisco/blob/a7ba19ff3c38061d6d8bc0c10fa754baadcfeb91/redisco/models/base.py#L71-L78
iamteem/redisco
redisco/models/base.py
_initialize_counters
def _initialize_counters(model_class, name, bases, attrs): """Stores the list of counter fields.""" model_class._counters = [] for k, v in attrs.iteritems(): if isinstance(v, Counter): model_class._counters.append(k)
python
def _initialize_counters(model_class, name, bases, attrs): """Stores the list of counter fields.""" model_class._counters = [] for k, v in attrs.iteritems(): if isinstance(v, Counter): model_class._counters.append(k)
[ "def", "_initialize_counters", "(", "model_class", ",", "name", ",", "bases", ",", "attrs", ")", ":", "model_class", ".", "_counters", "=", "[", "]", "for", "k", ",", "v", "in", "attrs", ".", "iteritems", "(", ")", ":", "if", "isinstance", "(", "v", ...
Stores the list of counter fields.
[ "Stores", "the", "list", "of", "counter", "fields", "." ]
train
https://github.com/iamteem/redisco/blob/a7ba19ff3c38061d6d8bc0c10fa754baadcfeb91/redisco/models/base.py#L80-L85
iamteem/redisco
redisco/models/base.py
get_model_from_key
def get_model_from_key(key): """Gets the model from a given key.""" _known_models = {} model_name = key.split(':', 2)[0] # populate for klass in Model.__subclasses__(): _known_models[klass.__name__] = klass return _known_models.get(model_name, None)
python
def get_model_from_key(key): """Gets the model from a given key.""" _known_models = {} model_name = key.split(':', 2)[0] # populate for klass in Model.__subclasses__(): _known_models[klass.__name__] = klass return _known_models.get(model_name, None)
[ "def", "get_model_from_key", "(", "key", ")", ":", "_known_models", "=", "{", "}", "model_name", "=", "key", ".", "split", "(", "':'", ",", "2", ")", "[", "0", "]", "# populate", "for", "klass", "in", "Model", ".", "__subclasses__", "(", ")", ":", "_...
Gets the model from a given key.
[ "Gets", "the", "model", "from", "a", "given", "key", "." ]
train
https://github.com/iamteem/redisco/blob/a7ba19ff3c38061d6d8bc0c10fa754baadcfeb91/redisco/models/base.py#L521-L528
iamteem/redisco
redisco/models/base.py
from_key
def from_key(key): """Returns the model instance based on the key. Raises BadKeyError if the key is not recognized by redisco or no defined model can be found. Returns None if the key could not be found. """ model = get_model_from_key(key) if model is None: raise BadKeyError try...
python
def from_key(key): """Returns the model instance based on the key. Raises BadKeyError if the key is not recognized by redisco or no defined model can be found. Returns None if the key could not be found. """ model = get_model_from_key(key) if model is None: raise BadKeyError try...
[ "def", "from_key", "(", "key", ")", ":", "model", "=", "get_model_from_key", "(", "key", ")", "if", "model", "is", "None", ":", "raise", "BadKeyError", "try", ":", "_", ",", "id", "=", "key", ".", "split", "(", "':'", ",", "2", ")", "id", "=", "i...
Returns the model instance based on the key. Raises BadKeyError if the key is not recognized by redisco or no defined model can be found. Returns None if the key could not be found.
[ "Returns", "the", "model", "instance", "based", "on", "the", "key", "." ]
train
https://github.com/iamteem/redisco/blob/a7ba19ff3c38061d6d8bc0c10fa754baadcfeb91/redisco/models/base.py#L531-L546
iamteem/redisco
redisco/models/base.py
Model.is_valid
def is_valid(self): """Returns True if all the fields are valid. It first validates the fields (required, unique, etc.) and then calls the validate method. """ self._errors = [] for field in self.fields: try: field.validate(self) e...
python
def is_valid(self): """Returns True if all the fields are valid. It first validates the fields (required, unique, etc.) and then calls the validate method. """ self._errors = [] for field in self.fields: try: field.validate(self) e...
[ "def", "is_valid", "(", "self", ")", ":", "self", ".", "_errors", "=", "[", "]", "for", "field", "in", "self", ".", "fields", ":", "try", ":", "field", ".", "validate", "(", "self", ")", "except", "FieldValidationError", ",", "e", ":", "self", ".", ...
Returns True if all the fields are valid. It first validates the fields (required, unique, etc.) and then calls the validate method.
[ "Returns", "True", "if", "all", "the", "fields", "are", "valid", "." ]
train
https://github.com/iamteem/redisco/blob/a7ba19ff3c38061d6d8bc0c10fa754baadcfeb91/redisco/models/base.py#L154-L167
iamteem/redisco
redisco/models/base.py
Model.update_attributes
def update_attributes(self, **kwargs): """Updates the attributes of the model.""" attrs = self.attributes.values() + self.lists.values() \ + self.references.values() for att in attrs: if att.name in kwargs: att.__set__(self, kwargs[att.name])
python
def update_attributes(self, **kwargs): """Updates the attributes of the model.""" attrs = self.attributes.values() + self.lists.values() \ + self.references.values() for att in attrs: if att.name in kwargs: att.__set__(self, kwargs[att.name])
[ "def", "update_attributes", "(", "self", ",", "*", "*", "kwargs", ")", ":", "attrs", "=", "self", ".", "attributes", ".", "values", "(", ")", "+", "self", ".", "lists", ".", "values", "(", ")", "+", "self", ".", "references", ".", "values", "(", ")...
Updates the attributes of the model.
[ "Updates", "the", "attributes", "of", "the", "model", "." ]
train
https://github.com/iamteem/redisco/blob/a7ba19ff3c38061d6d8bc0c10fa754baadcfeb91/redisco/models/base.py#L186-L192
iamteem/redisco
redisco/models/base.py
Model.save
def save(self): """Saves the instance to the datastore.""" if not self.is_valid(): return self._errors _new = self.is_new() if _new: self._initialize_id() with Mutex(self): self._write(_new) return True
python
def save(self): """Saves the instance to the datastore.""" if not self.is_valid(): return self._errors _new = self.is_new() if _new: self._initialize_id() with Mutex(self): self._write(_new) return True
[ "def", "save", "(", "self", ")", ":", "if", "not", "self", ".", "is_valid", "(", ")", ":", "return", "self", ".", "_errors", "_new", "=", "self", ".", "is_new", "(", ")", "if", "_new", ":", "self", ".", "_initialize_id", "(", ")", "with", "Mutex", ...
Saves the instance to the datastore.
[ "Saves", "the", "instance", "to", "the", "datastore", "." ]
train
https://github.com/iamteem/redisco/blob/a7ba19ff3c38061d6d8bc0c10fa754baadcfeb91/redisco/models/base.py#L194-L203