repository_name
stringclasses
316 values
func_path_in_repository
stringlengths
6
223
func_name
stringlengths
1
134
language
stringclasses
1 value
func_code_string
stringlengths
57
65.5k
func_documentation_string
stringlengths
1
46.3k
split_name
stringclasses
1 value
func_code_url
stringlengths
91
315
called_functions
listlengths
1
156
enclosing_scope
stringlengths
2
1.48M
django-fluent/django-fluent-dashboard
fluent_dashboard/modules.py
CmsAppIconList.init_with_context
python
def init_with_context(self, context): super(CmsAppIconList, self).init_with_context(context) apps = self.children cms_apps = [a for a in apps if is_cms_app(a['name'])] non_cms_apps = [a for a in apps if a not in cms_apps] if cms_apps: # Group the models of all CMS a...
Initializes the icon list.
train
https://github.com/django-fluent/django-fluent-dashboard/blob/aee7ef39e0586cd160036b13b7944b69cd2b4b8c/fluent_dashboard/modules.py#L206-L226
[ "def sort_cms_models(cms_models):\n \"\"\"\n Sort a set of CMS-related models in a custom (predefined) order.\n \"\"\"\n cms_models.sort(key=lambda model: (\n get_cms_model_order(model['name']) if is_cms_app(model['app_name']) else 999,\n model['app_name'],\n model['title']\n ))\...
class CmsAppIconList(AppIconList): """ A variation of the :class:`AppIconList` class with a strong bias towards sorting CMS apps on top. .. image:: /images/cmsappiconlist.png :width: 471px :height: 124px :alt: CmsAppIconList module for django-fluent-dashboard """
django-fluent/django-fluent-dashboard
fluent_dashboard/modules.py
CacheStatusGroup.init_with_context
python
def init_with_context(self, context): super(CacheStatusGroup, self).init_with_context(context) if 'dashboardmods' in settings.INSTALLED_APPS: import dashboardmods memcache_mods = dashboardmods.get_memcache_dash_modules() try: varnish_mods = dashboard...
Initializes the status list.
train
https://github.com/django-fluent/django-fluent-dashboard/blob/aee7ef39e0586cd160036b13b7944b69cd2b4b8c/fluent_dashboard/modules.py#L250-L270
null
class CacheStatusGroup(modules.Group): """ Display status modules for Varnish en Memcache, in a :class:`~admin_tools.modules.Group` module. This module is only displayed when the :ref:`dashboardmods` package is installed, added to the ``INSTALLED_APPS``, and the caches are configured and reachable. ...
goodmami/penman
penman.py
alphanum_order
python
def alphanum_order(triples): return sorted( triples, key=lambda t: [ int(t) if t.isdigit() else t for t in re.split(r'([0-9]+)', t.relation or '') ] )
Sort a list of triples by relation name. Embedded integers are sorted numerically, but otherwise the sorting is alphabetic.
train
https://github.com/goodmami/penman/blob/a2563ca16063a7330e2028eb489a99cc8e425c41/penman.py#L95-L108
null
#!/usr/bin/env python3 """ PENMAN graph library for AMR, DMRS, etc. Penman is a module to assist in working with graphs encoded in PENMAN notation, such as those for Abstract Meaning Representation (AMR) or Dependency Minimal Recursion Semantics (DMRS). It allows for conversion between PENMAN and triples, inspection ...
goodmami/penman
penman.py
decode
python
def decode(s, cls=PENMANCodec, **kwargs): codec = cls(**kwargs) return codec.decode(s)
Deserialize PENMAN-serialized *s* into its Graph object Args: s: a string containing a single PENMAN-serialized graph cls: serialization codec class kwargs: keyword arguments passed to the constructor of *cls* Returns: the Graph object described by *s* Example: >>> ...
train
https://github.com/goodmami/penman/blob/a2563ca16063a7330e2028eb489a99cc8e425c41/penman.py#L793-L809
[ "def decode(self, s, triples=False):\n \"\"\"\n Deserialize PENMAN-notation string *s* into its Graph object.\n\n Args:\n s: a string containing a single PENMAN-serialized graph\n triples: if True, treat *s* as a conjunction of logical triples\n Returns:\n the Graph object described...
#!/usr/bin/env python3 """ PENMAN graph library for AMR, DMRS, etc. Penman is a module to assist in working with graphs encoded in PENMAN notation, such as those for Abstract Meaning Representation (AMR) or Dependency Minimal Recursion Semantics (DMRS). It allows for conversion between PENMAN and triples, inspection ...
goodmami/penman
penman.py
encode
python
def encode(g, top=None, cls=PENMANCodec, **kwargs): codec = cls(**kwargs) return codec.encode(g, top=top)
Serialize the graph *g* from *top* to PENMAN notation. Args: g: the Graph object top: the node identifier for the top of the serialized graph; if unset, the original top of *g* is used cls: serialization codec class kwargs: keyword arguments passed to the constructor of ...
train
https://github.com/goodmami/penman/blob/a2563ca16063a7330e2028eb489a99cc8e425c41/penman.py#L812-L830
[ "def encode(self, g, top=None, triples=False):\n \"\"\"\n Serialize the graph *g* from *top* to PENMAN notation.\n\n Args:\n g: the Graph object\n top: the node identifier for the top of the serialized\n graph; if unset, the original top of *g* is used\n triples: if True, se...
#!/usr/bin/env python3 """ PENMAN graph library for AMR, DMRS, etc. Penman is a module to assist in working with graphs encoded in PENMAN notation, such as those for Abstract Meaning Representation (AMR) or Dependency Minimal Recursion Semantics (DMRS). It allows for conversion between PENMAN and triples, inspection ...
goodmami/penman
penman.py
load
python
def load(source, triples=False, cls=PENMANCodec, **kwargs): decode = cls(**kwargs).iterdecode if hasattr(source, 'read'): return list(decode(source.read())) else: with open(source) as fh: return list(decode(fh.read()))
Deserialize a list of PENMAN-encoded graphs from *source*. Args: source: a filename or file-like object to read from triples: if True, read graphs as triples instead of as PENMAN cls: serialization codec class kwargs: keyword arguments passed to the constructor of *cls* Returns:...
train
https://github.com/goodmami/penman/blob/a2563ca16063a7330e2028eb489a99cc8e425c41/penman.py#L833-L850
[ "def iterdecode(self, s, triples=False):\n \"\"\"\n Deserialize PENMAN-notation string *s* into its Graph objects.\n\n Args:\n s: a string containing zero or more PENMAN-serialized graphs\n triples: if True, treat *s* as a conjunction of logical triples\n Yields:\n valid Graph objec...
#!/usr/bin/env python3 """ PENMAN graph library for AMR, DMRS, etc. Penman is a module to assist in working with graphs encoded in PENMAN notation, such as those for Abstract Meaning Representation (AMR) or Dependency Minimal Recursion Semantics (DMRS). It allows for conversion between PENMAN and triples, inspection ...
goodmami/penman
penman.py
loads
python
def loads(string, triples=False, cls=PENMANCodec, **kwargs): codec = cls(**kwargs) return list(codec.iterdecode(string, triples=triples))
Deserialize a list of PENMAN-encoded graphs from *string*. Args: string: a string containing graph data triples: if True, read graphs as triples instead of as PENMAN cls: serialization codec class kwargs: keyword arguments passed to the constructor of *cls* Returns: a li...
train
https://github.com/goodmami/penman/blob/a2563ca16063a7330e2028eb489a99cc8e425c41/penman.py#L853-L866
[ "def iterdecode(self, s, triples=False):\n \"\"\"\n Deserialize PENMAN-notation string *s* into its Graph objects.\n\n Args:\n s: a string containing zero or more PENMAN-serialized graphs\n triples: if True, treat *s* as a conjunction of logical triples\n Yields:\n valid Graph objec...
#!/usr/bin/env python3 """ PENMAN graph library for AMR, DMRS, etc. Penman is a module to assist in working with graphs encoded in PENMAN notation, such as those for Abstract Meaning Representation (AMR) or Dependency Minimal Recursion Semantics (DMRS). It allows for conversion between PENMAN and triples, inspection ...
goodmami/penman
penman.py
dump
python
def dump(graphs, file, triples=False, cls=PENMANCodec, **kwargs): text = dumps(graphs, triples=triples, cls=cls, **kwargs) if hasattr(file, 'write'): print(text, file=file) else: with open(file, 'w') as fh: print(text, file=fh)
Serialize each graph in *graphs* to PENMAN and write to *file*. Args: graphs: an iterable of Graph objects file: a filename or file-like object to write to triples: if True, write graphs as triples instead of as PENMAN cls: serialization codec class kwargs: keyword arguments...
train
https://github.com/goodmami/penman/blob/a2563ca16063a7330e2028eb489a99cc8e425c41/penman.py#L869-L886
[ "def dumps(graphs, triples=False, cls=PENMANCodec, **kwargs):\n \"\"\"\n Serialize each graph in *graphs* to the PENMAN format.\n\n Args:\n graphs: an iterable of Graph objects\n triples: if True, write graphs as triples instead of as PENMAN\n Returns:\n the string of serialized gra...
#!/usr/bin/env python3 """ PENMAN graph library for AMR, DMRS, etc. Penman is a module to assist in working with graphs encoded in PENMAN notation, such as those for Abstract Meaning Representation (AMR) or Dependency Minimal Recursion Semantics (DMRS). It allows for conversion between PENMAN and triples, inspection ...
goodmami/penman
penman.py
dumps
python
def dumps(graphs, triples=False, cls=PENMANCodec, **kwargs): codec = cls(**kwargs) strings = [codec.encode(g, triples=triples) for g in graphs] return '\n\n'.join(strings)
Serialize each graph in *graphs* to the PENMAN format. Args: graphs: an iterable of Graph objects triples: if True, write graphs as triples instead of as PENMAN Returns: the string of serialized graphs
train
https://github.com/goodmami/penman/blob/a2563ca16063a7330e2028eb489a99cc8e425c41/penman.py#L889-L901
null
#!/usr/bin/env python3 """ PENMAN graph library for AMR, DMRS, etc. Penman is a module to assist in working with graphs encoded in PENMAN notation, such as those for Abstract Meaning Representation (AMR) or Dependency Minimal Recursion Semantics (DMRS). It allows for conversion between PENMAN and triples, inspection ...
goodmami/penman
penman.py
PENMANCodec.decode
python
def decode(self, s, triples=False): try: if triples: span, data = self._decode_triple_conjunction(s) else: span, data = self._decode_penman_node(s) except IndexError: raise DecodeError( 'Unexpected end of string.', strin...
Deserialize PENMAN-notation string *s* into its Graph object. Args: s: a string containing a single PENMAN-serialized graph triples: if True, treat *s* as a conjunction of logical triples Returns: the Graph object described by *s* Example: >>> co...
train
https://github.com/goodmami/penman/blob/a2563ca16063a7330e2028eb489a99cc8e425c41/penman.py#L148-L178
[ "def triples_to_graph(self, triples, top=None):\n \"\"\"\n Create a Graph from *triples* considering codec configuration.\n\n The Graph class does not know about information in the codec,\n so if Graph instantiation depends on special `TYPE_REL` or\n `TOP_VAR` values, use this function instead of ins...
class PENMANCodec(object): """ A parameterized encoder/decoder for graphs in PENMAN notation. """ TYPE_REL = 'instance' TOP_VAR = None TOP_REL = 'top' NODE_ENTER_RE = re.compile(r'\s*(\()\s*') NODE_EXIT_RE = re.compile(r'\s*(\))\s*') RELATION_RE = re.compile(r'(:[^\s(),]*)\s*') ...
goodmami/penman
penman.py
PENMANCodec.iterdecode
python
def iterdecode(self, s, triples=False): pos, strlen = 0, len(s) while pos < strlen: if s[pos] == '#': while pos < strlen and s[pos] != '\n': pos += 1 elif triples or s[pos] == '(': try: if triples: ...
Deserialize PENMAN-notation string *s* into its Graph objects. Args: s: a string containing zero or more PENMAN-serialized graphs triples: if True, treat *s* as a conjunction of logical triples Yields: valid Graph objects described by *s* Example: ...
train
https://github.com/goodmami/penman/blob/a2563ca16063a7330e2028eb489a99cc8e425c41/penman.py#L180-L223
[ "def triples_to_graph(self, triples, top=None):\n \"\"\"\n Create a Graph from *triples* considering codec configuration.\n\n The Graph class does not know about information in the codec,\n so if Graph instantiation depends on special `TYPE_REL` or\n `TOP_VAR` values, use this function instead of ins...
class PENMANCodec(object): """ A parameterized encoder/decoder for graphs in PENMAN notation. """ TYPE_REL = 'instance' TOP_VAR = None TOP_REL = 'top' NODE_ENTER_RE = re.compile(r'\s*(\()\s*') NODE_EXIT_RE = re.compile(r'\s*(\))\s*') RELATION_RE = re.compile(r'(:[^\s(),]*)\s*') ...
goodmami/penman
penman.py
PENMANCodec.encode
python
def encode(self, g, top=None, triples=False): if len(g.triples()) == 0: raise EncodeError('Cannot encode empty graph.') if triples: return self._encode_triple_conjunction(g, top=top) else: return self._encode_penman(g, top=top)
Serialize the graph *g* from *top* to PENMAN notation. Args: g: the Graph object top: the node identifier for the top of the serialized graph; if unset, the original top of *g* is used triples: if True, serialize as a conjunction of logical triples Re...
train
https://github.com/goodmami/penman/blob/a2563ca16063a7330e2028eb489a99cc8e425c41/penman.py#L225-L250
[ "def _encode_penman(self, g, top=None):\n \"\"\"\n Walk graph g and find a spanning dag, then serialize the result.\n\n First, depth-first traversal of preferred orientations (whether\n true or inverted) to create graph p.\n\n If any triples remain, select the first remaining triple whose\n source...
class PENMANCodec(object): """ A parameterized encoder/decoder for graphs in PENMAN notation. """ TYPE_REL = 'instance' TOP_VAR = None TOP_REL = 'top' NODE_ENTER_RE = re.compile(r'\s*(\()\s*') NODE_EXIT_RE = re.compile(r'\s*(\))\s*') RELATION_RE = re.compile(r'(:[^\s(),]*)\s*') ...
goodmami/penman
penman.py
PENMANCodec.handle_triple
python
def handle_triple(self, lhs, relation, rhs): relation = relation.replace(':', '', 1) # remove leading : if self.is_relation_inverted(relation): # deinvert source, target, inverted = rhs, lhs, True relation = self.invert_relation(relation) else: source, targ...
Process triples before they are added to the graph. Note that *lhs* and *rhs* are as they originally appeared, and may be inverted. Inversions are detected by is_relation_inverted() and de-inverted by invert_relation(). By default, this function: * removes initial colons on re...
train
https://github.com/goodmami/penman/blob/a2563ca16063a7330e2028eb489a99cc8e425c41/penman.py#L267-L304
[ "def _default_cast(x):\n if isinstance(x, basestring):\n if x.startswith('\"'):\n x = x # strip quotes?\n elif re.match(\n r'-?(0|[1-9]\\d*)(\\.\\d+[eE][-+]?|\\.|[eE][-+]?)\\d+$', x):\n x = float(x)\n elif re.match(r'-?\\d+$', x):\n x = int(x)...
class PENMANCodec(object): """ A parameterized encoder/decoder for graphs in PENMAN notation. """ TYPE_REL = 'instance' TOP_VAR = None TOP_REL = 'top' NODE_ENTER_RE = re.compile(r'\s*(\()\s*') NODE_EXIT_RE = re.compile(r'\s*(\))\s*') RELATION_RE = re.compile(r'(:[^\s(),]*)\s*') ...
goodmami/penman
penman.py
PENMANCodec.triples_to_graph
python
def triples_to_graph(self, triples, top=None): inferred_top = triples[0][0] if triples else None ts = [] for triple in triples: if triple[0] == self.TOP_VAR and triple[1] == self.TOP_REL: inferred_top = triple[2] else: ts.append(self.handle...
Create a Graph from *triples* considering codec configuration. The Graph class does not know about information in the codec, so if Graph instantiation depends on special `TYPE_REL` or `TOP_VAR` values, use this function instead of instantiating a Graph object directly. This is also wher...
train
https://github.com/goodmami/penman/blob/a2563ca16063a7330e2028eb489a99cc8e425c41/penman.py#L306-L331
[ "def handle_triple(self, lhs, relation, rhs):\n \"\"\"\n Process triples before they are added to the graph.\n\n Note that *lhs* and *rhs* are as they originally appeared, and\n may be inverted. Inversions are detected by\n is_relation_inverted() and de-inverted by invert_relation().\n\n By defaul...
class PENMANCodec(object): """ A parameterized encoder/decoder for graphs in PENMAN notation. """ TYPE_REL = 'instance' TOP_VAR = None TOP_REL = 'top' NODE_ENTER_RE = re.compile(r'\s*(\()\s*') NODE_EXIT_RE = re.compile(r'\s*(\))\s*') RELATION_RE = re.compile(r'(:[^\s(),]*)\s*') ...
goodmami/penman
penman.py
PENMANCodec._encode_penman
python
def _encode_penman(self, g, top=None): if top is None: top = g.top remaining = set(g.triples()) variables = g.variables() store = defaultdict(lambda: ([], [])) # (preferred, dispreferred) for t in g.triples(): if t.inverted: store[t.target...
Walk graph g and find a spanning dag, then serialize the result. First, depth-first traversal of preferred orientations (whether true or inverted) to create graph p. If any triples remain, select the first remaining triple whose source in the dispreferred orientation exists in p, where...
train
https://github.com/goodmami/penman/blob/a2563ca16063a7330e2028eb489a99cc8e425c41/penman.py#L436-L499
[ "def _layout(self, g, src, offset, seen):\n indent = self.indent\n if src not in g or len(g.get(src, [])) == 0 or src in seen:\n return src\n seen.add(src)\n branches = []\n outedges = self.relation_sort(g[src])\n head = '({}'.format(src)\n if indent is True:\n offset += len(head)...
class PENMANCodec(object): """ A parameterized encoder/decoder for graphs in PENMAN notation. """ TYPE_REL = 'instance' TOP_VAR = None TOP_REL = 'top' NODE_ENTER_RE = re.compile(r'\s*(\()\s*') NODE_EXIT_RE = re.compile(r'\s*(\))\s*') RELATION_RE = re.compile(r'(:[^\s(),]*)\s*') ...
goodmami/penman
penman.py
AMRCodec.is_relation_inverted
python
def is_relation_inverted(self, relation): return ( relation in self._deinversions or (relation.endswith('-of') and relation not in self._inversions) )
Return True if *relation* is inverted.
train
https://github.com/goodmami/penman/blob/a2563ca16063a7330e2028eb489a99cc8e425c41/penman.py#L571-L578
null
class AMRCodec(PENMANCodec): """ An AMR codec for graphs in PENMAN notation. """ TYPE_REL = 'instance' TOP_VAR = None TOP_REL = 'top' # vars: [a-z]+\d* ; first relation must be node type NODE_ENTER_RE = re.compile(r'\s*(\()\s*(?=[a-z]+\d*\s*\/)') NODETYPE_RE = PENMANCodec.ATOM_RE ...
goodmami/penman
penman.py
AMRCodec.invert_relation
python
def invert_relation(self, relation): if self.is_relation_inverted(relation): rel = self._deinversions.get(relation, relation[:-3]) else: rel = self._inversions.get(relation, relation + '-of') if rel is None: raise PenmanError( 'Cannot (de)inve...
Invert or deinvert *relation*.
train
https://github.com/goodmami/penman/blob/a2563ca16063a7330e2028eb489a99cc8e425c41/penman.py#L580-L592
[ "def is_relation_inverted(self, relation):\n \"\"\"\n Return True if *relation* is inverted.\n \"\"\"\n return (\n relation in self._deinversions or\n (relation.endswith('-of') and relation not in self._inversions)\n )\n" ]
class AMRCodec(PENMANCodec): """ An AMR codec for graphs in PENMAN notation. """ TYPE_REL = 'instance' TOP_VAR = None TOP_REL = 'top' # vars: [a-z]+\d* ; first relation must be node type NODE_ENTER_RE = re.compile(r'\s*(\()\s*(?=[a-z]+\d*\s*\/)') NODETYPE_RE = PENMANCodec.ATOM_RE ...
goodmami/penman
penman.py
Graph.triples
python
def triples(self, source=None, relation=None, target=None): triplematch = lambda t: ( (source is None or source == t.source) and (relation is None or relation == t.relation) and (target is None or target == t.target) ) return list(filter(triplematch, self._tri...
Return triples filtered by their *source*, *relation*, or *target*.
train
https://github.com/goodmami/penman/blob/a2563ca16063a7330e2028eb489a99cc8e425c41/penman.py#L680-L689
null
class Graph(object): """ A basic class for modeling a rooted, directed acyclic graph. A Graph is defined by a list of triples, which can be divided into two parts: a list of graph edges where both the source and target are node identifiers, and a list of node attributes where only the source is...
goodmami/penman
penman.py
Graph.edges
python
def edges(self, source=None, relation=None, target=None): edgematch = lambda e: ( (source is None or source == e.source) and (relation is None or relation == e.relation) and (target is None or target == e.target) ) variables = self.variables() edges = ...
Return edges filtered by their *source*, *relation*, or *target*. Edges don't include terminal triples (node types or attributes).
train
https://github.com/goodmami/penman/blob/a2563ca16063a7330e2028eb489a99cc8e425c41/penman.py#L691-L704
[ "def variables(self):\n \"\"\"\n Return the list of variables (nonterminal node identifiers).\n \"\"\"\n return set(v for v, _, _ in self._triples)\n" ]
class Graph(object): """ A basic class for modeling a rooted, directed acyclic graph. A Graph is defined by a list of triples, which can be divided into two parts: a list of graph edges where both the source and target are node identifiers, and a list of node attributes where only the source is...
goodmami/penman
penman.py
Graph.attributes
python
def attributes(self, source=None, relation=None, target=None): attrmatch = lambda a: ( (source is None or source == a.source) and (relation is None or relation == a.relation) and (target is None or target == a.target) ) variables = self.variables() att...
Return attributes filtered by their *source*, *relation*, or *target*. Attributes don't include triples where the target is a nonterminal.
train
https://github.com/goodmami/penman/blob/a2563ca16063a7330e2028eb489a99cc8e425c41/penman.py#L706-L719
[ "def variables(self):\n \"\"\"\n Return the list of variables (nonterminal node identifiers).\n \"\"\"\n return set(v for v, _, _ in self._triples)\n", "def triples(self, source=None, relation=None, target=None):\n \"\"\"\n Return triples filtered by their *source*, *relation*, or *target*.\n ...
class Graph(object): """ A basic class for modeling a rooted, directed acyclic graph. A Graph is defined by a list of triples, which can be divided into two parts: a list of graph edges where both the source and target are node identifiers, and a list of node attributes where only the source is...
goodmami/penman
penman.py
Graph.reentrancies
python
def reentrancies(self): entrancies = defaultdict(int) entrancies[self.top] += 1 # implicit entrancy to top for t in self.edges(): entrancies[t.target] += 1 return dict((v, cnt - 1) for v, cnt in entrancies.items() if cnt >= 2)
Return a mapping of variables to their re-entrancy count. A re-entrancy is when more than one edge selects a node as its target. These graphs are rooted, so the top node always has an implicit entrancy. Only nodes with re-entrancies are reported, and the count is only for the entrant ed...
train
https://github.com/goodmami/penman/blob/a2563ca16063a7330e2028eb489a99cc8e425c41/penman.py#L721-L737
[ "def edges(self, source=None, relation=None, target=None):\n \"\"\"\n Return edges filtered by their *source*, *relation*, or *target*.\n\n Edges don't include terminal triples (node types or attributes).\n \"\"\"\n edgematch = lambda e: (\n (source is None or source == e.source) and\n ...
class Graph(object): """ A basic class for modeling a rooted, directed acyclic graph. A Graph is defined by a list of triples, which can be divided into two parts: a list of graph edges where both the source and target are node identifiers, and a list of node attributes where only the source is...
maxcountryman/atomos
atomos/util.py
synchronized
python
def synchronized(fn): ''' A decorator which acquires a lock before attempting to execute its wrapped function. Releases the lock in a finally clause. :param fn: The function to wrap. ''' lock = threading.Lock() @functools.wraps(fn) def decorated(*args, **kwargs): lock.acquire()...
A decorator which acquires a lock before attempting to execute its wrapped function. Releases the lock in a finally clause. :param fn: The function to wrap.
train
https://github.com/maxcountryman/atomos/blob/418746c69134efba3c4f999405afe9113dee4827/atomos/util.py#L21-L38
null
# -*- coding: utf-8 -*- ''' atomos.util Utility functions. ''' from __future__ import absolute_import import functools import threading from multiprocessing import Value, Lock def repr(module, instance, value): repr_fmt = '<{m}.{cls}({val}) object at {addr}>' return repr_fmt.format(m=module, ...
maxcountryman/atomos
atomos/atomic.py
AtomicReference.set
python
def set(self, value): ''' Atomically sets the value to `value`. :param value: The value to set. ''' with self._lock.exclusive: self._value = value return value
Atomically sets the value to `value`. :param value: The value to set.
train
https://github.com/maxcountryman/atomos/blob/418746c69134efba3c4f999405afe9113dee4827/atomos/atomic.py#L38-L46
null
class AtomicReference(object): ''' A reference to an object which allows atomic manipulation semantics. AtomicReferences are particularlly useful when an object cannot otherwise be manipulated atomically. ''' def __init__(self, value=None): self._value = value self._lock = util....
maxcountryman/atomos
atomos/atomic.py
AtomicReference.get_and_set
python
def get_and_set(self, value): ''' Atomically sets the value to `value` and returns the old value. :param value: The value to set. ''' with self._lock.exclusive: oldval = self._value self._value = value return oldval
Atomically sets the value to `value` and returns the old value. :param value: The value to set.
train
https://github.com/maxcountryman/atomos/blob/418746c69134efba3c4f999405afe9113dee4827/atomos/atomic.py#L48-L57
null
class AtomicReference(object): ''' A reference to an object which allows atomic manipulation semantics. AtomicReferences are particularlly useful when an object cannot otherwise be manipulated atomically. ''' def __init__(self, value=None): self._value = value self._lock = util....
maxcountryman/atomos
atomos/atomic.py
AtomicReference.compare_and_set
python
def compare_and_set(self, expect, update): ''' Atomically sets the value to `update` if the current value is equal to `expect`. :param expect: The expected current value. :param update: The value to set if and only if `expect` equals the current value. ''' ...
Atomically sets the value to `update` if the current value is equal to `expect`. :param expect: The expected current value. :param update: The value to set if and only if `expect` equals the current value.
train
https://github.com/maxcountryman/atomos/blob/418746c69134efba3c4f999405afe9113dee4827/atomos/atomic.py#L59-L73
null
class AtomicReference(object): ''' A reference to an object which allows atomic manipulation semantics. AtomicReferences are particularlly useful when an object cannot otherwise be manipulated atomically. ''' def __init__(self, value=None): self._value = value self._lock = util....
maxcountryman/atomos
atomos/atomic.py
AtomicNumber.add_and_get
python
def add_and_get(self, delta): ''' Atomically adds `delta` to the current value. :param delta: The delta to add. ''' with self._lock.exclusive: self._value += delta return self._value
Atomically adds `delta` to the current value. :param delta: The delta to add.
train
https://github.com/maxcountryman/atomos/blob/418746c69134efba3c4f999405afe9113dee4827/atomos/atomic.py#L111-L119
null
class AtomicNumber(AtomicReference): ''' AtomicNumber object super type. Contains common methods for AtomicInteger, AtomicLong, and AtomicFloat. ''' # We do not need a locked get since numbers are not complex data types. def get(self): ''' Returns the value. ''' ...
maxcountryman/atomos
atomos/atomic.py
AtomicNumber.get_and_add
python
def get_and_add(self, delta): ''' Atomically adds `delta` to the current value and returns the old value. :param delta: The delta to add. ''' with self._lock.exclusive: oldval = self._value self._value += delta return oldval
Atomically adds `delta` to the current value and returns the old value. :param delta: The delta to add.
train
https://github.com/maxcountryman/atomos/blob/418746c69134efba3c4f999405afe9113dee4827/atomos/atomic.py#L121-L130
null
class AtomicNumber(AtomicReference): ''' AtomicNumber object super type. Contains common methods for AtomicInteger, AtomicLong, and AtomicFloat. ''' # We do not need a locked get since numbers are not complex data types. def get(self): ''' Returns the value. ''' ...
maxcountryman/atomos
atomos/atomic.py
AtomicNumber.subtract_and_get
python
def subtract_and_get(self, delta): ''' Atomically subtracts `delta` from the current value. :param delta: The delta to subtract. ''' with self._lock.exclusive: self._value -= delta return self._value
Atomically subtracts `delta` from the current value. :param delta: The delta to subtract.
train
https://github.com/maxcountryman/atomos/blob/418746c69134efba3c4f999405afe9113dee4827/atomos/atomic.py#L132-L140
null
class AtomicNumber(AtomicReference): ''' AtomicNumber object super type. Contains common methods for AtomicInteger, AtomicLong, and AtomicFloat. ''' # We do not need a locked get since numbers are not complex data types. def get(self): ''' Returns the value. ''' ...
maxcountryman/atomos
atomos/atomic.py
AtomicNumber.get_and_subtract
python
def get_and_subtract(self, delta): ''' Atomically subtracts `delta` from the current value and returns the old value. :param delta: The delta to subtract. ''' with self._lock.exclusive: oldval = self._value self._value -= delta return ...
Atomically subtracts `delta` from the current value and returns the old value. :param delta: The delta to subtract.
train
https://github.com/maxcountryman/atomos/blob/418746c69134efba3c4f999405afe9113dee4827/atomos/atomic.py#L142-L152
null
class AtomicNumber(AtomicReference): ''' AtomicNumber object super type. Contains common methods for AtomicInteger, AtomicLong, and AtomicFloat. ''' # We do not need a locked get since numbers are not complex data types. def get(self): ''' Returns the value. ''' ...
maxcountryman/atomos
atomos/atom.py
ARef.notify_watches
python
def notify_watches(self, oldval, newval): ''' Passes `oldval` and `newval` to each `fn` in the watches dictionary, passing along its respective key and the reference to this object. :param oldval: The old value which will be passed to the watch. :param newval: The new value whic...
Passes `oldval` and `newval` to each `fn` in the watches dictionary, passing along its respective key and the reference to this object. :param oldval: The old value which will be passed to the watch. :param newval: The new value which will be passed to the watch.
train
https://github.com/maxcountryman/atomos/blob/418746c69134efba3c4f999405afe9113dee4827/atomos/atom.py#L64-L76
null
class ARef(object): ''' Ref object super type. Refs may hold watches which can be notified when a value a ref holds changes. In effect, a watch is a callback which receives the key, object reference, oldval, and newval. For example, a watch function could be constructed like this:: >>...
maxcountryman/atomos
atomos/atom.py
Atom.swap
python
def swap(self, fn, *args, **kwargs): ''' Given a mutator `fn`, calls `fn` with the atom's current state, `args`, and `kwargs`. The return value of this invocation becomes the new value of the atom. Returns the new value. :param fn: A function which will be passed the current sta...
Given a mutator `fn`, calls `fn` with the atom's current state, `args`, and `kwargs`. The return value of this invocation becomes the new value of the atom. Returns the new value. :param fn: A function which will be passed the current state. Should return a new state. This absolutel...
train
https://github.com/maxcountryman/atomos/blob/418746c69134efba3c4f999405afe9113dee4827/atomos/atom.py#L154-L172
[ "def deref(self):\n '''\n Returns the value held.\n '''\n return self._state.get()\n" ]
class Atom(ARef): ''' Atom object type. Atoms store mutable state and provide thread-safe methods for retrieving and altering it. This is useful in multi-threaded contexts or any time an application makes use of shared mutable state. By using an atom, it is possible to ensure that read values a...
maxcountryman/atomos
atomos/atom.py
Atom.reset
python
def reset(self, newval): ''' Resets the atom's value to `newval`, returning `newval`. :param newval: The new value to set. ''' oldval = self._state.get() self._state.set(newval) self.notify_watches(oldval, newval) return newval
Resets the atom's value to `newval`, returning `newval`. :param newval: The new value to set.
train
https://github.com/maxcountryman/atomos/blob/418746c69134efba3c4f999405afe9113dee4827/atomos/atom.py#L174-L183
[ "def notify_watches(self, oldval, newval):\n '''\n Passes `oldval` and `newval` to each `fn` in the watches dictionary,\n passing along its respective key and the reference to this object.\n\n :param oldval: The old value which will be passed to the watch.\n :param newval: The new value which will be...
class Atom(ARef): ''' Atom object type. Atoms store mutable state and provide thread-safe methods for retrieving and altering it. This is useful in multi-threaded contexts or any time an application makes use of shared mutable state. By using an atom, it is possible to ensure that read values a...
maxcountryman/atomos
atomos/atom.py
Atom.compare_and_set
python
def compare_and_set(self, oldval, newval): ''' Given `oldval` and `newval`, sets the atom's value to `newval` if and only if `oldval` is the atom's current value. Returns `True` upon success, otherwise `False`. :param oldval: The old expected value. :param newval: The ne...
Given `oldval` and `newval`, sets the atom's value to `newval` if and only if `oldval` is the atom's current value. Returns `True` upon success, otherwise `False`. :param oldval: The old expected value. :param newval: The new value which will be set if and only if `oldval` e...
train
https://github.com/maxcountryman/atomos/blob/418746c69134efba3c4f999405afe9113dee4827/atomos/atom.py#L185-L199
[ "def notify_watches(self, oldval, newval):\n '''\n Passes `oldval` and `newval` to each `fn` in the watches dictionary,\n passing along its respective key and the reference to this object.\n\n :param oldval: The old value which will be passed to the watch.\n :param newval: The new value which will be...
class Atom(ARef): ''' Atom object type. Atoms store mutable state and provide thread-safe methods for retrieving and altering it. This is useful in multi-threaded contexts or any time an application makes use of shared mutable state. By using an atom, it is possible to ensure that read values a...
maxcountryman/atomos
atomos/multiprocessing/atomic.py
AtomicCtypesReference.set
python
def set(self, value): ''' Atomically sets the value to `value`. :param value: The value to set. ''' with self._reference.get_lock(): self._reference.value = value return value
Atomically sets the value to `value`. :param value: The value to set.
train
https://github.com/maxcountryman/atomos/blob/418746c69134efba3c4f999405afe9113dee4827/atomos/multiprocessing/atomic.py#L95-L103
null
class AtomicCtypesReference(object): ''' A reference to an object which allows atomic manipulation semantics. AtomicCtypesReferences are particularlly useful when an object cannot otherwise be manipulated atomically. This only support ctypes data types. https://docs.python.org/3.4/library/ctyp...
maxcountryman/atomos
atomos/multiprocessing/atomic.py
AtomicCtypesReference.get_and_set
python
def get_and_set(self, value): ''' Atomically sets the value to `value` and returns the old value. :param value: The value to set. ''' with self._reference.get_lock(): oldval = self._reference.value self._reference.value = value return oldval
Atomically sets the value to `value` and returns the old value. :param value: The value to set.
train
https://github.com/maxcountryman/atomos/blob/418746c69134efba3c4f999405afe9113dee4827/atomos/multiprocessing/atomic.py#L105-L114
null
class AtomicCtypesReference(object): ''' A reference to an object which allows atomic manipulation semantics. AtomicCtypesReferences are particularlly useful when an object cannot otherwise be manipulated atomically. This only support ctypes data types. https://docs.python.org/3.4/library/ctyp...
maxcountryman/atomos
atomos/multiprocessing/atomic.py
AtomicCtypesReference.compare_and_set
python
def compare_and_set(self, expect, update): ''' Atomically sets the value to `update` if the current value is equal to `expect`. :param expect: The expected current value. :param update: The value to set if and only if `expect` equals the current value. ''' ...
Atomically sets the value to `update` if the current value is equal to `expect`. :param expect: The expected current value. :param update: The value to set if and only if `expect` equals the current value.
train
https://github.com/maxcountryman/atomos/blob/418746c69134efba3c4f999405afe9113dee4827/atomos/multiprocessing/atomic.py#L116-L130
null
class AtomicCtypesReference(object): ''' A reference to an object which allows atomic manipulation semantics. AtomicCtypesReferences are particularlly useful when an object cannot otherwise be manipulated atomically. This only support ctypes data types. https://docs.python.org/3.4/library/ctyp...
maxcountryman/atomos
atomos/multiprocessing/atomic.py
AtomicNumber.add_and_get
python
def add_and_get(self, delta): ''' Atomically adds `delta` to the current value. :param delta: The delta to add. ''' with self._reference.get_lock(): self._reference.value += delta return self._reference.value
Atomically adds `delta` to the current value. :param delta: The delta to add.
train
https://github.com/maxcountryman/atomos/blob/418746c69134efba3c4f999405afe9113dee4827/atomos/multiprocessing/atomic.py#L169-L177
null
class AtomicNumber(AtomicCtypesReference): ''' AtomicNumber object super type. Contains common methods for AtomicInteger, AtomicLong, and AtomicFloat. ''' # We do not need a locked get since numbers are not complex data types. def get(self): ''' Returns the value. ''' ...
maxcountryman/atomos
atomos/multiprocessing/atomic.py
AtomicNumber.get_and_add
python
def get_and_add(self, delta): ''' Atomically adds `delta` to the current value and returns the old value. :param delta: The delta to add. ''' with self._reference.get_lock(): oldval = self._reference.value self._reference.value += delta return...
Atomically adds `delta` to the current value and returns the old value. :param delta: The delta to add.
train
https://github.com/maxcountryman/atomos/blob/418746c69134efba3c4f999405afe9113dee4827/atomos/multiprocessing/atomic.py#L179-L188
null
class AtomicNumber(AtomicCtypesReference): ''' AtomicNumber object super type. Contains common methods for AtomicInteger, AtomicLong, and AtomicFloat. ''' # We do not need a locked get since numbers are not complex data types. def get(self): ''' Returns the value. ''' ...
maxcountryman/atomos
atomos/multiprocessing/atomic.py
AtomicNumber.subtract_and_get
python
def subtract_and_get(self, delta): ''' Atomically subtracts `delta` from the current value. :param delta: The delta to subtract. ''' with self._reference.get_lock(): self._reference.value -= delta return self._reference.value
Atomically subtracts `delta` from the current value. :param delta: The delta to subtract.
train
https://github.com/maxcountryman/atomos/blob/418746c69134efba3c4f999405afe9113dee4827/atomos/multiprocessing/atomic.py#L190-L198
null
class AtomicNumber(AtomicCtypesReference): ''' AtomicNumber object super type. Contains common methods for AtomicInteger, AtomicLong, and AtomicFloat. ''' # We do not need a locked get since numbers are not complex data types. def get(self): ''' Returns the value. ''' ...
maxcountryman/atomos
atomos/multiprocessing/atomic.py
AtomicNumber.get_and_subtract
python
def get_and_subtract(self, delta): ''' Atomically subtracts `delta` from the current value and returns the old value. :param delta: The delta to subtract. ''' with self._reference.get_lock(): oldval = self._reference.value self._reference.value -=...
Atomically subtracts `delta` from the current value and returns the old value. :param delta: The delta to subtract.
train
https://github.com/maxcountryman/atomos/blob/418746c69134efba3c4f999405afe9113dee4827/atomos/multiprocessing/atomic.py#L200-L210
null
class AtomicNumber(AtomicCtypesReference): ''' AtomicNumber object super type. Contains common methods for AtomicInteger, AtomicLong, and AtomicFloat. ''' # We do not need a locked get since numbers are not complex data types. def get(self): ''' Returns the value. ''' ...
joesecurity/jbxapi
setup.py
get_version
python
def get_version(): here = os.path.abspath(os.path.dirname(__file__)) jbxapi_file = os.path.join(here, "jbxapi.py") with open(jbxapi_file) as f: content = f.read() match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]", content, re.M) if not match: raise RuntimeError("Unable to...
Extract the version number from the code.
train
https://github.com/joesecurity/jbxapi/blob/cea2f5edef9661d53fe3d58435d4e88701331f79/setup.py#L7-L18
null
import re import os from setuptools import setup setup(name='jbxapi', version=get_version(), description='API for Joe Sandbox', url='https://github.com/joesecurity/joesandboxcloudapi', author='Joe Security LLC', license='MIT', py_modules=['jbxapi'], install_requires=[ ...
joesecurity/jbxapi
jbxapi.py
JoeSandbox.analysis_list
python
def analysis_list(self): response = self._post(self.apiurl + '/v2/analysis/list', data={'apikey': self.apikey}) return self._raise_or_extract(response)
Fetch a list of all analyses.
train
https://github.com/joesecurity/jbxapi/blob/cea2f5edef9661d53fe3d58435d4e88701331f79/jbxapi.py#L158-L164
[ "def _post(self, url, data=None, **kwargs):\n \"\"\"\n Wrapper around requests.post which\n\n (a) always inserts a timeout\n (b) converts errors to ConnectionError\n (c) re-tries a few times\n (d) converts file names to ASCII\n \"\"\"\n\n # Remove non-ASCII characters from fi...
class JoeSandbox(object): def __init__(self, apikey=API_KEY, apiurl=API_URL, accept_tac=ACCEPT_TAC, timeout=None, verify_ssl=True, retries=3, proxies=None): """ Create a JoeSandbox object. Parameters: apikey: the api key apiurl: the api url accept_tac: ...
joesecurity/jbxapi
jbxapi.py
JoeSandbox.submit_sample
python
def submit_sample(self, sample, cookbook=None, params={}, _extra_params={}): self._check_user_parameters(params) files = {'sample': sample} if cookbook: files['cookbook'] = cookbook return self._submit(params, files, _extra_params=_extra_params)
Submit a sample and returns the submission id. Parameters: sample: The sample to submit. Needs to be a file-like object or a tuple in the shape (filename, file-like object). cookbook: Uploads a cookbook together with the sample. Needs to be a file-like obje...
train
https://github.com/joesecurity/jbxapi/blob/cea2f5edef9661d53fe3d58435d4e88701331f79/jbxapi.py#L166-L202
[ "def _submit(self, params, files=None, _extra_params={}):\n data = copy.copy(submission_defaults)\n data.update(params)\n data = self._prepare_params_for_submission(data)\n data.update(_extra_params)\n\n response = self._post(self.apiurl + '/v2/submission/new', data=data, files=files)\n\n return s...
class JoeSandbox(object): def __init__(self, apikey=API_KEY, apiurl=API_URL, accept_tac=ACCEPT_TAC, timeout=None, verify_ssl=True, retries=3, proxies=None): """ Create a JoeSandbox object. Parameters: apikey: the api key apiurl: the api url accept_tac: ...
joesecurity/jbxapi
jbxapi.py
JoeSandbox.submit_sample_url
python
def submit_sample_url(self, url, params={}, _extra_params={}): self._check_user_parameters(params) params = copy.copy(params) params['sample-url'] = url return self._submit(params, _extra_params=_extra_params)
Submit a sample at a given URL for analysis.
train
https://github.com/joesecurity/jbxapi/blob/cea2f5edef9661d53fe3d58435d4e88701331f79/jbxapi.py#L204-L211
[ "def _submit(self, params, files=None, _extra_params={}):\n data = copy.copy(submission_defaults)\n data.update(params)\n data = self._prepare_params_for_submission(data)\n data.update(_extra_params)\n\n response = self._post(self.apiurl + '/v2/submission/new', data=data, files=files)\n\n return s...
class JoeSandbox(object): def __init__(self, apikey=API_KEY, apiurl=API_URL, accept_tac=ACCEPT_TAC, timeout=None, verify_ssl=True, retries=3, proxies=None): """ Create a JoeSandbox object. Parameters: apikey: the api key apiurl: the api url accept_tac: ...
joesecurity/jbxapi
jbxapi.py
JoeSandbox.submit_url
python
def submit_url(self, url, params={}, _extra_params={}): self._check_user_parameters(params) params = copy.copy(params) params['url'] = url return self._submit(params, _extra_params=_extra_params)
Submit a website for analysis.
train
https://github.com/joesecurity/jbxapi/blob/cea2f5edef9661d53fe3d58435d4e88701331f79/jbxapi.py#L213-L220
[ "def _submit(self, params, files=None, _extra_params={}):\n data = copy.copy(submission_defaults)\n data.update(params)\n data = self._prepare_params_for_submission(data)\n data.update(_extra_params)\n\n response = self._post(self.apiurl + '/v2/submission/new', data=data, files=files)\n\n return s...
class JoeSandbox(object): def __init__(self, apikey=API_KEY, apiurl=API_URL, accept_tac=ACCEPT_TAC, timeout=None, verify_ssl=True, retries=3, proxies=None): """ Create a JoeSandbox object. Parameters: apikey: the api key apiurl: the api url accept_tac: ...
joesecurity/jbxapi
jbxapi.py
JoeSandbox.submit_cookbook
python
def submit_cookbook(self, cookbook, params={}, _extra_params={}): self._check_user_parameters(params) files = {'cookbook': cookbook} return self._submit(params, files, _extra_params=_extra_params)
Submit a cookbook.
train
https://github.com/joesecurity/jbxapi/blob/cea2f5edef9661d53fe3d58435d4e88701331f79/jbxapi.py#L222-L228
[ "def _submit(self, params, files=None, _extra_params={}):\n data = copy.copy(submission_defaults)\n data.update(params)\n data = self._prepare_params_for_submission(data)\n data.update(_extra_params)\n\n response = self._post(self.apiurl + '/v2/submission/new', data=data, files=files)\n\n return s...
class JoeSandbox(object): def __init__(self, apikey=API_KEY, apiurl=API_URL, accept_tac=ACCEPT_TAC, timeout=None, verify_ssl=True, retries=3, proxies=None): """ Create a JoeSandbox object. Parameters: apikey: the api key apiurl: the api url accept_tac: ...
joesecurity/jbxapi
jbxapi.py
JoeSandbox.submission_delete
python
def submission_delete(self, submission_id): response = self._post(self.apiurl + '/v2/submission/delete', data={'apikey': self.apikey, 'submission_id': submission_id}) return self._raise_or_extract(response)
Delete a submission.
train
https://github.com/joesecurity/jbxapi/blob/cea2f5edef9661d53fe3d58435d4e88701331f79/jbxapi.py#L271-L277
[ "def _post(self, url, data=None, **kwargs):\n \"\"\"\n Wrapper around requests.post which\n\n (a) always inserts a timeout\n (b) converts errors to ConnectionError\n (c) re-tries a few times\n (d) converts file names to ASCII\n \"\"\"\n\n # Remove non-ASCII characters from fi...
class JoeSandbox(object): def __init__(self, apikey=API_KEY, apiurl=API_URL, accept_tac=ACCEPT_TAC, timeout=None, verify_ssl=True, retries=3, proxies=None): """ Create a JoeSandbox object. Parameters: apikey: the api key apiurl: the api url accept_tac: ...
joesecurity/jbxapi
jbxapi.py
JoeSandbox.server_online
python
def server_online(self): response = self._post(self.apiurl + '/v2/server/online', data={'apikey': self.apikey}) return self._raise_or_extract(response)
Returns True if the Joe Sandbox servers are running or False if they are in maintenance mode.
train
https://github.com/joesecurity/jbxapi/blob/cea2f5edef9661d53fe3d58435d4e88701331f79/jbxapi.py#L279-L285
[ "def _post(self, url, data=None, **kwargs):\n \"\"\"\n Wrapper around requests.post which\n\n (a) always inserts a timeout\n (b) converts errors to ConnectionError\n (c) re-tries a few times\n (d) converts file names to ASCII\n \"\"\"\n\n # Remove non-ASCII characters from fi...
class JoeSandbox(object): def __init__(self, apikey=API_KEY, apiurl=API_URL, accept_tac=ACCEPT_TAC, timeout=None, verify_ssl=True, retries=3, proxies=None): """ Create a JoeSandbox object. Parameters: apikey: the api key apiurl: the api url accept_tac: ...
joesecurity/jbxapi
jbxapi.py
JoeSandbox.analysis_info
python
def analysis_info(self, webid): response = self._post(self.apiurl + "/v2/analysis/info", data={'apikey': self.apikey, 'webid': webid}) return self._raise_or_extract(response)
Show the status and most important attributes of an analysis.
train
https://github.com/joesecurity/jbxapi/blob/cea2f5edef9661d53fe3d58435d4e88701331f79/jbxapi.py#L287-L293
[ "def _post(self, url, data=None, **kwargs):\n \"\"\"\n Wrapper around requests.post which\n\n (a) always inserts a timeout\n (b) converts errors to ConnectionError\n (c) re-tries a few times\n (d) converts file names to ASCII\n \"\"\"\n\n # Remove non-ASCII characters from fi...
class JoeSandbox(object): def __init__(self, apikey=API_KEY, apiurl=API_URL, accept_tac=ACCEPT_TAC, timeout=None, verify_ssl=True, retries=3, proxies=None): """ Create a JoeSandbox object. Parameters: apikey: the api key apiurl: the api url accept_tac: ...
joesecurity/jbxapi
jbxapi.py
JoeSandbox.analysis_download
python
def analysis_download(self, webid, type, run=None, file=None): # when no file is specified, we create our own if file is None: _file = io.BytesIO() else: _file = file data = { 'apikey': self.apikey, 'webid': webid, 'type': typ...
Download a resource for an analysis. E.g. the full report, binaries, screenshots. The full list of resources can be found in our API documentation. When `file` is given, the return value is the filename specified by the server, otherwise it's a tuple of (filename, bytes). Parameters: ...
train
https://github.com/joesecurity/jbxapi/blob/cea2f5edef9661d53fe3d58435d4e88701331f79/jbxapi.py#L303-L363
[ "def _post(self, url, data=None, **kwargs):\n \"\"\"\n Wrapper around requests.post which\n\n (a) always inserts a timeout\n (b) converts errors to ConnectionError\n (c) re-tries a few times\n (d) converts file names to ASCII\n \"\"\"\n\n # Remove non-ASCII characters from fi...
class JoeSandbox(object): def __init__(self, apikey=API_KEY, apiurl=API_URL, accept_tac=ACCEPT_TAC, timeout=None, verify_ssl=True, retries=3, proxies=None): """ Create a JoeSandbox object. Parameters: apikey: the api key apiurl: the api url accept_tac: ...
joesecurity/jbxapi
jbxapi.py
JoeSandbox.analysis_search
python
def analysis_search(self, query): response = self._post(self.apiurl + "/v2/analysis/search", data={'apikey': self.apikey, 'q': query}) return self._raise_or_extract(response)
Lists the webids of the analyses that match the given query. Searches in MD5, SHA1, SHA256, filename, cookbook name, comment, url and report id.
train
https://github.com/joesecurity/jbxapi/blob/cea2f5edef9661d53fe3d58435d4e88701331f79/jbxapi.py#L365-L373
[ "def _post(self, url, data=None, **kwargs):\n \"\"\"\n Wrapper around requests.post which\n\n (a) always inserts a timeout\n (b) converts errors to ConnectionError\n (c) re-tries a few times\n (d) converts file names to ASCII\n \"\"\"\n\n # Remove non-ASCII characters from fi...
class JoeSandbox(object): def __init__(self, apikey=API_KEY, apiurl=API_URL, accept_tac=ACCEPT_TAC, timeout=None, verify_ssl=True, retries=3, proxies=None): """ Create a JoeSandbox object. Parameters: apikey: the api key apiurl: the api url accept_tac: ...
joesecurity/jbxapi
jbxapi.py
JoeSandbox.server_systems
python
def server_systems(self): response = self._post(self.apiurl + "/v2/server/systems", data={'apikey': self.apikey}) return self._raise_or_extract(response)
Retrieve a list of available systems.
train
https://github.com/joesecurity/jbxapi/blob/cea2f5edef9661d53fe3d58435d4e88701331f79/jbxapi.py#L375-L381
[ "def _post(self, url, data=None, **kwargs):\n \"\"\"\n Wrapper around requests.post which\n\n (a) always inserts a timeout\n (b) converts errors to ConnectionError\n (c) re-tries a few times\n (d) converts file names to ASCII\n \"\"\"\n\n # Remove non-ASCII characters from fi...
class JoeSandbox(object): def __init__(self, apikey=API_KEY, apiurl=API_URL, accept_tac=ACCEPT_TAC, timeout=None, verify_ssl=True, retries=3, proxies=None): """ Create a JoeSandbox object. Parameters: apikey: the api key apiurl: the api url accept_tac: ...
joesecurity/jbxapi
jbxapi.py
JoeSandbox.account_info
python
def account_info(self): response = self._post(self.apiurl + "/v2/account/info", data={'apikey': self.apikey}) return self._raise_or_extract(response)
Only available on Joe Sandbox Cloud Show information about the account.
train
https://github.com/joesecurity/jbxapi/blob/cea2f5edef9661d53fe3d58435d4e88701331f79/jbxapi.py#L383-L391
[ "def _post(self, url, data=None, **kwargs):\n \"\"\"\n Wrapper around requests.post which\n\n (a) always inserts a timeout\n (b) converts errors to ConnectionError\n (c) re-tries a few times\n (d) converts file names to ASCII\n \"\"\"\n\n # Remove non-ASCII characters from fi...
class JoeSandbox(object): def __init__(self, apikey=API_KEY, apiurl=API_URL, accept_tac=ACCEPT_TAC, timeout=None, verify_ssl=True, retries=3, proxies=None): """ Create a JoeSandbox object. Parameters: apikey: the api key apiurl: the api url accept_tac: ...
joesecurity/jbxapi
jbxapi.py
JoeSandbox.server_info
python
def server_info(self): response = self._post(self.apiurl + "/v2/server/info", data={'apikey': self.apikey}) return self._raise_or_extract(response)
Query information about the server.
train
https://github.com/joesecurity/jbxapi/blob/cea2f5edef9661d53fe3d58435d4e88701331f79/jbxapi.py#L393-L399
[ "def _post(self, url, data=None, **kwargs):\n \"\"\"\n Wrapper around requests.post which\n\n (a) always inserts a timeout\n (b) converts errors to ConnectionError\n (c) re-tries a few times\n (d) converts file names to ASCII\n \"\"\"\n\n # Remove non-ASCII characters from fi...
class JoeSandbox(object): def __init__(self, apikey=API_KEY, apiurl=API_URL, accept_tac=ACCEPT_TAC, timeout=None, verify_ssl=True, retries=3, proxies=None): """ Create a JoeSandbox object. Parameters: apikey: the api key apiurl: the api url accept_tac: ...
joesecurity/jbxapi
jbxapi.py
JoeSandbox.server_lia_countries
python
def server_lia_countries(self): response = self._post(self.apiurl + "/v2/server/lia_countries", data={'apikey': self.apikey}) return self._raise_or_extract(response)
Show the available localized internet anonymization countries.
train
https://github.com/joesecurity/jbxapi/blob/cea2f5edef9661d53fe3d58435d4e88701331f79/jbxapi.py#L401-L407
[ "def _post(self, url, data=None, **kwargs):\n \"\"\"\n Wrapper around requests.post which\n\n (a) always inserts a timeout\n (b) converts errors to ConnectionError\n (c) re-tries a few times\n (d) converts file names to ASCII\n \"\"\"\n\n # Remove non-ASCII characters from fi...
class JoeSandbox(object): def __init__(self, apikey=API_KEY, apiurl=API_URL, accept_tac=ACCEPT_TAC, timeout=None, verify_ssl=True, retries=3, proxies=None): """ Create a JoeSandbox object. Parameters: apikey: the api key apiurl: the api url accept_tac: ...
joesecurity/jbxapi
jbxapi.py
JoeSandbox.server_languages_and_locales
python
def server_languages_and_locales(self): response = self._post(self.apiurl + "/v2/server/languages_and_locales", data={'apikey': self.apikey}) return self._raise_or_extract(response)
Show the available languages and locales
train
https://github.com/joesecurity/jbxapi/blob/cea2f5edef9661d53fe3d58435d4e88701331f79/jbxapi.py#L409-L415
[ "def _post(self, url, data=None, **kwargs):\n \"\"\"\n Wrapper around requests.post which\n\n (a) always inserts a timeout\n (b) converts errors to ConnectionError\n (c) re-tries a few times\n (d) converts file names to ASCII\n \"\"\"\n\n # Remove non-ASCII characters from fi...
class JoeSandbox(object): def __init__(self, apikey=API_KEY, apiurl=API_URL, accept_tac=ACCEPT_TAC, timeout=None, verify_ssl=True, retries=3, proxies=None): """ Create a JoeSandbox object. Parameters: apikey: the api key apiurl: the api url accept_tac: ...
joesecurity/jbxapi
jbxapi.py
JoeSandbox._post
python
def _post(self, url, data=None, **kwargs): # Remove non-ASCII characters from filenames due to a limitation of the combination of # urllib3 (via python-requests) and our server # https://github.com/requests/requests/issues/2117 # Internal Ticket #3090 if "files" in kwargs and kw...
Wrapper around requests.post which (a) always inserts a timeout (b) converts errors to ConnectionError (c) re-tries a few times (d) converts file names to ASCII
train
https://github.com/joesecurity/jbxapi/blob/cea2f5edef9661d53fe3d58435d4e88701331f79/jbxapi.py#L417-L463
null
class JoeSandbox(object): def __init__(self, apikey=API_KEY, apiurl=API_URL, accept_tac=ACCEPT_TAC, timeout=None, verify_ssl=True, retries=3, proxies=None): """ Create a JoeSandbox object. Parameters: apikey: the api key apiurl: the api url accept_tac: ...
joesecurity/jbxapi
jbxapi.py
JoeSandbox._check_user_parameters
python
def _check_user_parameters(self, user_parameters): if not user_parameters: return # sanity check against typos for key in user_parameters: if key not in submission_defaults: raise ValueError("Unknown parameter {0}".format(key))
Verifies that the parameter dict given by the user only contains known keys. This ensures that the user detects typos faster.
train
https://github.com/joesecurity/jbxapi/blob/cea2f5edef9661d53fe3d58435d4e88701331f79/jbxapi.py#L465-L476
null
class JoeSandbox(object): def __init__(self, apikey=API_KEY, apiurl=API_URL, accept_tac=ACCEPT_TAC, timeout=None, verify_ssl=True, retries=3, proxies=None): """ Create a JoeSandbox object. Parameters: apikey: the api key apiurl: the api url accept_tac: ...
joesecurity/jbxapi
jbxapi.py
JoeSandbox._raise_or_extract
python
def _raise_or_extract(self, response): try: data = response.json() except ValueError: raise JoeException("The server responded with an unexpected format ({}). Is the API url correct?". format(response.status_code)) try: if response.ok: return...
Raises an exception if the response indicates an API error. Otherwise returns the object at the 'data' key of the API response.
train
https://github.com/joesecurity/jbxapi/blob/cea2f5edef9661d53fe3d58435d4e88701331f79/jbxapi.py#L478-L497
null
class JoeSandbox(object): def __init__(self, apikey=API_KEY, apiurl=API_URL, accept_tac=ACCEPT_TAC, timeout=None, verify_ssl=True, retries=3, proxies=None): """ Create a JoeSandbox object. Parameters: apikey: the api key apiurl: the api url accept_tac: ...
WoLpH/python-statsd
statsd/connection.py
Connection.send
python
def send(self, data, sample_rate=None): '''Send the data over UDP while taking the sample_rate in account The sample rate should be a number between `0` and `1` which indicates the probability that a message will be sent. The sample_rate is also communicated to `statsd` so it knows what...
Send the data over UDP while taking the sample_rate in account The sample rate should be a number between `0` and `1` which indicates the probability that a message will be sent. The sample_rate is also communicated to `statsd` so it knows what multiplier to use. :keyword data: The dat...
train
https://github.com/WoLpH/python-statsd/blob/a757da04375c48d03d322246405b33382d37f03f/statsd/connection.py#L47-L81
[ "def iter_dict(dict_): # pragma: no cover\n if PY3K:\n return dict_.items()\n else:\n return dict_.iteritems()\n" ]
class Connection(object): '''Statsd Connection :keyword host: The statsd host to connect to, defaults to `localhost` :type host: str :keyword port: The statsd port to connect to, defaults to `8125` :type port: int :keyword sample_rate: The sample rate, defaults to `1` (meaning always) :type...
WoLpH/python-statsd
statsd/timer.py
Timer.start
python
def start(self): '''Start the timer and store the start time, this can only be executed once per instance It returns the timer instance so it can be chained when instantiating the timer instance like this: ``timer = Timer('application_name').start()``''' assert self._sta...
Start the timer and store the start time, this can only be executed once per instance It returns the timer instance so it can be chained when instantiating the timer instance like this: ``timer = Timer('application_name').start()``
train
https://github.com/WoLpH/python-statsd/blob/a757da04375c48d03d322246405b33382d37f03f/statsd/timer.py#L38-L48
null
class Timer(statsd.Client): ''' Statsd Timer Object Additional documentation is available at the parent class :class:`~statsd.client.Client` :keyword name: The name for this timer :type name: str :keyword connection: The connection to use, will be automatically created if not give...
WoLpH/python-statsd
statsd/timer.py
Timer.send
python
def send(self, subname, delta): '''Send the data to statsd via self.connection :keyword subname: The subname to report the data to (appended to the client name) :type subname: str :keyword delta: The time delta (time.time() - time.time()) to report :type delta: float...
Send the data to statsd via self.connection :keyword subname: The subname to report the data to (appended to the client name) :type subname: str :keyword delta: The time delta (time.time() - time.time()) to report :type delta: float
train
https://github.com/WoLpH/python-statsd/blob/a757da04375c48d03d322246405b33382d37f03f/statsd/timer.py#L50-L65
[ "def _get_name(cls, *name_parts):\n name_parts = [compat.to_str(x) for x in name_parts if x]\n return '.'.join(name_parts)\n", "def _send(self, data):\n return self.connection.send(data)\n" ]
class Timer(statsd.Client): ''' Statsd Timer Object Additional documentation is available at the parent class :class:`~statsd.client.Client` :keyword name: The name for this timer :type name: str :keyword connection: The connection to use, will be automatically created if not give...
WoLpH/python-statsd
statsd/timer.py
Timer.intermediate
python
def intermediate(self, subname): '''Send the time that has passed since our last measurement :keyword subname: The subname to report the data to (appended to the client name) :type subname: str ''' t = time.time() response = self.send(subname, t - self._last)...
Send the time that has passed since our last measurement :keyword subname: The subname to report the data to (appended to the client name) :type subname: str
train
https://github.com/WoLpH/python-statsd/blob/a757da04375c48d03d322246405b33382d37f03f/statsd/timer.py#L67-L77
[ "def send(self, subname, delta):\n '''Send the data to statsd via self.connection\n\n :keyword subname: The subname to report the data to (appended to the\n client name)\n :type subname: str\n :keyword delta: The time delta (time.time() - time.time()) to report\n :type delta: float\n '''\n ...
class Timer(statsd.Client): ''' Statsd Timer Object Additional documentation is available at the parent class :class:`~statsd.client.Client` :keyword name: The name for this timer :type name: str :keyword connection: The connection to use, will be automatically created if not give...
WoLpH/python-statsd
statsd/timer.py
Timer.stop
python
def stop(self, subname='total'): '''Stop the timer and send the total since `start()` was run :keyword subname: The subname to report the data to (appended to the client name) :type subname: str ''' assert self._stop is None, ( 'Unable to stop, the timer ...
Stop the timer and send the total since `start()` was run :keyword subname: The subname to report the data to (appended to the client name) :type subname: str
train
https://github.com/WoLpH/python-statsd/blob/a757da04375c48d03d322246405b33382d37f03f/statsd/timer.py#L79-L89
[ "def send(self, subname, delta):\n '''Send the data to statsd via self.connection\n\n :keyword subname: The subname to report the data to (appended to the\n client name)\n :type subname: str\n :keyword delta: The time delta (time.time() - time.time()) to report\n :type delta: float\n '''\n ...
class Timer(statsd.Client): ''' Statsd Timer Object Additional documentation is available at the parent class :class:`~statsd.client.Client` :keyword name: The name for this timer :type name: str :keyword connection: The connection to use, will be automatically created if not give...
WoLpH/python-statsd
statsd/timer.py
Timer.decorate
python
def decorate(self, function_or_name): '''Decorate a function to time the execution The method can be called with or without a name. If no name is given the function defaults to the name of the function. :keyword function_or_name: The name to post to or the function to wrap >>>...
Decorate a function to time the execution The method can be called with or without a name. If no name is given the function defaults to the name of the function. :keyword function_or_name: The name to post to or the function to wrap >>> from statsd import Timer >>> timer = Tim...
train
https://github.com/WoLpH/python-statsd/blob/a757da04375c48d03d322246405b33382d37f03f/statsd/timer.py#L127-L152
[ "def _decorate(self, name, function, class_=None):\n class_ = class_ or Timer\n\n @wraps(function)\n def _decorator(*args, **kwargs):\n timer = self.get_client(name, class_)\n timer.start()\n try:\n return function(*args, **kwargs)\n finally:\n # Stop the t...
class Timer(statsd.Client): ''' Statsd Timer Object Additional documentation is available at the parent class :class:`~statsd.client.Client` :keyword name: The name for this timer :type name: str :keyword connection: The connection to use, will be automatically created if not give...
WoLpH/python-statsd
statsd/timer.py
Timer.time
python
def time(self, subname=None, class_=None): '''Returns a context manager to time execution of a block of code. :keyword subname: The subname to report data to :type subname: str :keyword class_: The :class:`~statsd.client.Client` subclass to use (e.g. :class:`~statsd.timer.Ti...
Returns a context manager to time execution of a block of code. :keyword subname: The subname to report data to :type subname: str :keyword class_: The :class:`~statsd.client.Client` subclass to use (e.g. :class:`~statsd.timer.Timer` or :class:`~statsd.counter.Counter`) ...
train
https://github.com/WoLpH/python-statsd/blob/a757da04375c48d03d322246405b33382d37f03f/statsd/timer.py#L155-L183
[ "def get_client(self, name=None, class_=None):\n '''Get a (sub-)client with a separate namespace\n This way you can create a global/app based client with subclients\n per class/function\n\n :keyword name: The name to use, if the name for this client was `spam`\n and the `name` argument is `eggs` ...
class Timer(statsd.Client): ''' Statsd Timer Object Additional documentation is available at the parent class :class:`~statsd.client.Client` :keyword name: The name for this timer :type name: str :keyword connection: The connection to use, will be automatically created if not give...
WoLpH/python-statsd
statsd/raw.py
Raw.send
python
def send(self, subname, value, timestamp=None): '''Send the data to statsd via self.connection :keyword subname: The subname to report the data to (appended to the client name) :type subname: str :keyword value: The raw value to send ''' if timestamp is None:...
Send the data to statsd via self.connection :keyword subname: The subname to report the data to (appended to the client name) :type subname: str :keyword value: The raw value to send
train
https://github.com/WoLpH/python-statsd/blob/a757da04375c48d03d322246405b33382d37f03f/statsd/raw.py#L24-L38
[ "def _get_name(cls, *name_parts):\n name_parts = [compat.to_str(x) for x in name_parts if x]\n return '.'.join(name_parts)\n", "def _send(self, data):\n return self.connection.send(data)\n" ]
class Raw(statsd.Client): '''Class to implement a statsd raw message. If a service has already summarized its own data for e.g. inspection purposes, use this summarized data to send to a statsd that has the raw patch, and this data will be sent to graphite pretty much unchanged. See https:/...
WoLpH/python-statsd
statsd/gauge.py
Gauge._send
python
def _send(self, subname, value): '''Send the data to statsd via self.connection :keyword subname: The subname to report the data to (appended to the client name) :type subname: str :keyword value: The gauge value to send ''' name = self._get_name(self.name, s...
Send the data to statsd via self.connection :keyword subname: The subname to report the data to (appended to the client name) :type subname: str :keyword value: The gauge value to send
train
https://github.com/WoLpH/python-statsd/blob/a757da04375c48d03d322246405b33382d37f03f/statsd/gauge.py#L10-L20
[ "def _get_name(cls, *name_parts):\n name_parts = [compat.to_str(x) for x in name_parts if x]\n return '.'.join(name_parts)\n", "def _send(self, data):\n return self.connection.send(data)\n" ]
class Gauge(statsd.Client): 'Class to implement a statsd gauge' def send(self, subname, value): '''Send the data to statsd via self.connection :keyword subname: The subname to report the data to (appended to the client name) :type subname: str :keyword value: The ...
WoLpH/python-statsd
statsd/gauge.py
Gauge.send
python
def send(self, subname, value): '''Send the data to statsd via self.connection :keyword subname: The subname to report the data to (appended to the client name) :type subname: str :keyword value: The gauge value to send ''' assert isinstance(value, compat.NUM...
Send the data to statsd via self.connection :keyword subname: The subname to report the data to (appended to the client name) :type subname: str :keyword value: The gauge value to send
train
https://github.com/WoLpH/python-statsd/blob/a757da04375c48d03d322246405b33382d37f03f/statsd/gauge.py#L22-L31
[ "def _send(self, subname, value):\n '''Send the data to statsd via self.connection\n\n :keyword subname: The subname to report the data to (appended to the\n client name)\n :type subname: str\n :keyword value: The gauge value to send\n '''\n name = self._get_name(self.name, subname)\n se...
class Gauge(statsd.Client): 'Class to implement a statsd gauge' def _send(self, subname, value): '''Send the data to statsd via self.connection :keyword subname: The subname to report the data to (appended to the client name) :type subname: str :keyword value: The ...
WoLpH/python-statsd
statsd/gauge.py
Gauge.increment
python
def increment(self, subname=None, delta=1): '''Increment the gauge with `delta` :keyword subname: The subname to report the data to (appended to the client name) :type subname: str :keyword delta: The delta to add to the gauge :type delta: int >>> gauge = Ga...
Increment the gauge with `delta` :keyword subname: The subname to report the data to (appended to the client name) :type subname: str :keyword delta: The delta to add to the gauge :type delta: int >>> gauge = Gauge('application_name') >>> gauge.increment('ga...
train
https://github.com/WoLpH/python-statsd/blob/a757da04375c48d03d322246405b33382d37f03f/statsd/gauge.py#L33-L52
[ "def _send(self, subname, value):\n '''Send the data to statsd via self.connection\n\n :keyword subname: The subname to report the data to (appended to the\n client name)\n :type subname: str\n :keyword value: The gauge value to send\n '''\n name = self._get_name(self.name, subname)\n se...
class Gauge(statsd.Client): 'Class to implement a statsd gauge' def _send(self, subname, value): '''Send the data to statsd via self.connection :keyword subname: The subname to report the data to (appended to the client name) :type subname: str :keyword value: The ...
WoLpH/python-statsd
statsd/gauge.py
Gauge.decrement
python
def decrement(self, subname=None, delta=1): '''Decrement the gauge with `delta` :keyword subname: The subname to report the data to (appended to the client name) :type subname: str :keyword delta: The delta to remove from the gauge :type delta: int >>> gauge...
Decrement the gauge with `delta` :keyword subname: The subname to report the data to (appended to the client name) :type subname: str :keyword delta: The delta to remove from the gauge :type delta: int >>> gauge = Gauge('application_name') >>> gauge.decremen...
train
https://github.com/WoLpH/python-statsd/blob/a757da04375c48d03d322246405b33382d37f03f/statsd/gauge.py#L54-L73
[ "def _send(self, subname, value):\n '''Send the data to statsd via self.connection\n\n :keyword subname: The subname to report the data to (appended to the\n client name)\n :type subname: str\n :keyword value: The gauge value to send\n '''\n name = self._get_name(self.name, subname)\n se...
class Gauge(statsd.Client): 'Class to implement a statsd gauge' def _send(self, subname, value): '''Send the data to statsd via self.connection :keyword subname: The subname to report the data to (appended to the client name) :type subname: str :keyword value: The ...
WoLpH/python-statsd
statsd/gauge.py
Gauge.set
python
def set(self, subname, value): ''' Set the data ignoring the sign, ie set("test", -1) will set "test" exactly to -1 (not decrement it by 1) See https://github.com/etsy/statsd/blob/master/docs/metric_types.md "Adding a sign to the gauge value will change the value, rather ...
Set the data ignoring the sign, ie set("test", -1) will set "test" exactly to -1 (not decrement it by 1) See https://github.com/etsy/statsd/blob/master/docs/metric_types.md "Adding a sign to the gauge value will change the value, rather than setting it. gaugor:-10|g ...
train
https://github.com/WoLpH/python-statsd/blob/a757da04375c48d03d322246405b33382d37f03f/statsd/gauge.py#L99-L126
[ "def _send(self, subname, value):\n '''Send the data to statsd via self.connection\n\n :keyword subname: The subname to report the data to (appended to the\n client name)\n :type subname: str\n :keyword value: The gauge value to send\n '''\n name = self._get_name(self.name, subname)\n se...
class Gauge(statsd.Client): 'Class to implement a statsd gauge' def _send(self, subname, value): '''Send the data to statsd via self.connection :keyword subname: The subname to report the data to (appended to the client name) :type subname: str :keyword value: The ...
WoLpH/python-statsd
statsd/client.py
Client.get_client
python
def get_client(self, name=None, class_=None): '''Get a (sub-)client with a separate namespace This way you can create a global/app based client with subclients per class/function :keyword name: The name to use, if the name for this client was `spam` and the `name` argument i...
Get a (sub-)client with a separate namespace This way you can create a global/app based client with subclients per class/function :keyword name: The name to use, if the name for this client was `spam` and the `name` argument is `eggs` than the resulting name will be `spa...
train
https://github.com/WoLpH/python-statsd/blob/a757da04375c48d03d322246405b33382d37f03f/statsd/client.py#L45-L70
[ "def _get_name(cls, *name_parts):\n name_parts = [compat.to_str(x) for x in name_parts if x]\n return '.'.join(name_parts)\n" ]
class Client(object): '''Statsd Client Object :keyword name: The name for this client :type name: str :keyword connection: The connection to use, will be automatically created if not given :type connection: :class:`~statsd.connection.Connection` >>> client = Client('test') >>> cli...
WoLpH/python-statsd
statsd/client.py
Client.get_average
python
def get_average(self, name=None): '''Shortcut for getting an :class:`~statsd.average.Average` instance :keyword name: See :func:`~statsd.client.Client.get_client` :type name: str ''' return self.get_client(name=name, class_=statsd.Average)
Shortcut for getting an :class:`~statsd.average.Average` instance :keyword name: See :func:`~statsd.client.Client.get_client` :type name: str
train
https://github.com/WoLpH/python-statsd/blob/a757da04375c48d03d322246405b33382d37f03f/statsd/client.py#L72-L78
[ "def get_client(self, name=None, class_=None):\n '''Get a (sub-)client with a separate namespace\n This way you can create a global/app based client with subclients\n per class/function\n\n :keyword name: The name to use, if the name for this client was `spam`\n and the `name` argument is `eggs` ...
class Client(object): '''Statsd Client Object :keyword name: The name for this client :type name: str :keyword connection: The connection to use, will be automatically created if not given :type connection: :class:`~statsd.connection.Connection` >>> client = Client('test') >>> cli...
WoLpH/python-statsd
statsd/client.py
Client.get_counter
python
def get_counter(self, name=None): '''Shortcut for getting a :class:`~statsd.counter.Counter` instance :keyword name: See :func:`~statsd.client.Client.get_client` :type name: str ''' return self.get_client(name=name, class_=statsd.Counter)
Shortcut for getting a :class:`~statsd.counter.Counter` instance :keyword name: See :func:`~statsd.client.Client.get_client` :type name: str
train
https://github.com/WoLpH/python-statsd/blob/a757da04375c48d03d322246405b33382d37f03f/statsd/client.py#L80-L86
[ "def get_client(self, name=None, class_=None):\n '''Get a (sub-)client with a separate namespace\n This way you can create a global/app based client with subclients\n per class/function\n\n :keyword name: The name to use, if the name for this client was `spam`\n and the `name` argument is `eggs` ...
class Client(object): '''Statsd Client Object :keyword name: The name for this client :type name: str :keyword connection: The connection to use, will be automatically created if not given :type connection: :class:`~statsd.connection.Connection` >>> client = Client('test') >>> cli...
WoLpH/python-statsd
statsd/client.py
Client.get_gauge
python
def get_gauge(self, name=None): '''Shortcut for getting a :class:`~statsd.gauge.Gauge` instance :keyword name: See :func:`~statsd.client.Client.get_client` :type name: str ''' return self.get_client(name=name, class_=statsd.Gauge)
Shortcut for getting a :class:`~statsd.gauge.Gauge` instance :keyword name: See :func:`~statsd.client.Client.get_client` :type name: str
train
https://github.com/WoLpH/python-statsd/blob/a757da04375c48d03d322246405b33382d37f03f/statsd/client.py#L88-L94
[ "def get_client(self, name=None, class_=None):\n '''Get a (sub-)client with a separate namespace\n This way you can create a global/app based client with subclients\n per class/function\n\n :keyword name: The name to use, if the name for this client was `spam`\n and the `name` argument is `eggs` ...
class Client(object): '''Statsd Client Object :keyword name: The name for this client :type name: str :keyword connection: The connection to use, will be automatically created if not given :type connection: :class:`~statsd.connection.Connection` >>> client = Client('test') >>> cli...
WoLpH/python-statsd
statsd/client.py
Client.get_raw
python
def get_raw(self, name=None): '''Shortcut for getting a :class:`~statsd.raw.Raw` instance :keyword name: See :func:`~statsd.client.Client.get_client` :type name: str ''' return self.get_client(name=name, class_=statsd.Raw)
Shortcut for getting a :class:`~statsd.raw.Raw` instance :keyword name: See :func:`~statsd.client.Client.get_client` :type name: str
train
https://github.com/WoLpH/python-statsd/blob/a757da04375c48d03d322246405b33382d37f03f/statsd/client.py#L96-L102
[ "def get_client(self, name=None, class_=None):\n '''Get a (sub-)client with a separate namespace\n This way you can create a global/app based client with subclients\n per class/function\n\n :keyword name: The name to use, if the name for this client was `spam`\n and the `name` argument is `eggs` ...
class Client(object): '''Statsd Client Object :keyword name: The name for this client :type name: str :keyword connection: The connection to use, will be automatically created if not given :type connection: :class:`~statsd.connection.Connection` >>> client = Client('test') >>> cli...
WoLpH/python-statsd
statsd/client.py
Client.get_timer
python
def get_timer(self, name=None): '''Shortcut for getting a :class:`~statsd.timer.Timer` instance :keyword name: See :func:`~statsd.client.Client.get_client` :type name: str ''' return self.get_client(name=name, class_=statsd.Timer)
Shortcut for getting a :class:`~statsd.timer.Timer` instance :keyword name: See :func:`~statsd.client.Client.get_client` :type name: str
train
https://github.com/WoLpH/python-statsd/blob/a757da04375c48d03d322246405b33382d37f03f/statsd/client.py#L104-L110
[ "def get_client(self, name=None, class_=None):\n '''Get a (sub-)client with a separate namespace\n This way you can create a global/app based client with subclients\n per class/function\n\n :keyword name: The name to use, if the name for this client was `spam`\n and the `name` argument is `eggs` ...
class Client(object): '''Statsd Client Object :keyword name: The name for this client :type name: str :keyword connection: The connection to use, will be automatically created if not given :type connection: :class:`~statsd.connection.Connection` >>> client = Client('test') >>> cli...
edx/edx-oauth2-provider
edx_oauth2_provider/oidc/handlers.py
BasicIDTokenHandler.now
python
def now(self): if self._now is None: # Compute the current time only once per instance self._now = datetime.utcnow() return self._now
Capture time.
train
https://github.com/edx/edx-oauth2-provider/blob/73e7569a8369e74c345022ccba634365e24befab/edx_oauth2_provider/oidc/handlers.py#L83-L88
null
class BasicIDTokenHandler(object): """ Basic OpenID Connect ID token claims. For reference see: http://openid.net/specs/openid-connect-basic-1_0.html#IDToken """ def __init__(self): self._now = None @property def scope_openid(self, data): """ Returns claims for the ...
edx/edx-oauth2-provider
edx_oauth2_provider/oidc/handlers.py
BasicIDTokenHandler.claim_exp
python
def claim_exp(self, data): expiration = getattr(settings, 'OAUTH_ID_TOKEN_EXPIRATION', 30) expires = self.now + timedelta(seconds=expiration) return timegm(expires.utctimetuple())
Required expiration time.
train
https://github.com/edx/edx-oauth2-provider/blob/73e7569a8369e74c345022ccba634365e24befab/edx_oauth2_provider/oidc/handlers.py#L111-L115
null
class BasicIDTokenHandler(object): """ Basic OpenID Connect ID token claims. For reference see: http://openid.net/specs/openid-connect-basic-1_0.html#IDToken """ def __init__(self): self._now = None @property def now(self): """ Capture time. """ if self._now i...
edx/edx-oauth2-provider
edx_oauth2_provider/management/commands/create_oauth2_client.py
Command._clean_required_args
python
def _clean_required_args(self, url, redirect_uri, client_type): # Validate URLs for url_to_validate in (url, redirect_uri): try: URLValidator()(url_to_validate) except ValidationError: raise CommandError("URLs provided are invalid. Please provide v...
Validate and clean the command's arguments. Arguments: url (str): Client's application URL. redirect_uri (str): Client application's OAuth2 callback URI. client_type (str): Client's type, indicating whether the Client application is capable of maintaining the...
train
https://github.com/edx/edx-oauth2-provider/blob/73e7569a8369e74c345022ccba634365e24befab/edx_oauth2_provider/management/commands/create_oauth2_client.py#L106-L141
null
class Command(BaseCommand): """ create_oauth2_client command class """ help = 'Create a new OAuth2 Client. Outputs a serialized representation of the newly-created Client.' def add_arguments(self, parser): super(Command, self).add_arguments(parser) # Required positional arguments. ...
edx/edx-oauth2-provider
edx_oauth2_provider/management/commands/create_oauth2_client.py
Command._parse_options
python
def _parse_options(self, options): for key in ('username', 'client_name', 'client_id', 'client_secret', 'trusted', 'logout_uri'): value = options.get(key) if value is not None: self.fields[key] = value username = self.fields.pop('username', None) if usern...
Parse the command's options. Arguments: options (dict): Options with which the command was called. Raises: CommandError, if a user matching the provided username does not exist.
train
https://github.com/edx/edx-oauth2-provider/blob/73e7569a8369e74c345022ccba634365e24befab/edx_oauth2_provider/management/commands/create_oauth2_client.py#L143-L177
null
class Command(BaseCommand): """ create_oauth2_client command class """ help = 'Create a new OAuth2 Client. Outputs a serialized representation of the newly-created Client.' def add_arguments(self, parser): super(Command, self).add_arguments(parser) # Required positional arguments. ...
edx/edx-oauth2-provider
edx_oauth2_provider/oidc/core.py
id_token
python
def id_token(access_token, nonce=None, claims_request=None): handlers = HANDLERS['id_token'] # Select only the relevant section of the claims request. claims_request_section = claims_request.get('id_token', {}) if claims_request else {} scope_request = provider.scope.to_names(access_token.scope) ...
Returns data required for an OpenID Connect ID Token according to: - http://openid.net/specs/openid-connect-basic-1_0.html#IDToken Arguments: access_token (:class:`AccessToken`): Associated OAuth2 access token. nonce (str): Optional nonce to protect against replay attacks. claims_reque...
train
https://github.com/edx/edx-oauth2-provider/blob/73e7569a8369e74c345022ccba634365e24befab/edx_oauth2_provider/oidc/core.py#L59-L99
[ "def collect(handlers, access_token, scope_request=None, claims_request=None):\n \"\"\"\n Collect all the claims values from the `handlers`.\n\n Arguments:\n handlers (list): List of claim :class:`Handler` classes.\n access_token (:class:AccessToken): Associated access token.\n scope_request...
""" OpenID Connect core related utility functions. Defines utility functions to process the ID Token and UserInfo endpoints according to the OpenID Connect specification. """ from __future__ import absolute_import, division, print_function, unicode_literals import jwt import provider.scope from django.utils.module_l...
edx/edx-oauth2-provider
edx_oauth2_provider/oidc/core.py
userinfo
python
def userinfo(access_token, scope_request=None, claims_request=None): handlers = HANDLERS['userinfo'] # Select only the relevant section of the claims request. claims_request_section = claims_request.get('userinfo', {}) if claims_request else {} # If nothing is requested, return the claims for the sco...
Returns data required for an OpenID Connect UserInfo response, according to: http://openid.net/specs/openid-connect-basic-1_0.html#UserInfoResponse Supports scope and claims request parameter as described in: - http://openid.net/specs/openid-connect-core-1_0.html#ScopeClaims - http://openid.net/specs...
train
https://github.com/edx/edx-oauth2-provider/blob/73e7569a8369e74c345022ccba634365e24befab/edx_oauth2_provider/oidc/core.py#L102-L152
[ "def collect(handlers, access_token, scope_request=None, claims_request=None):\n \"\"\"\n Collect all the claims values from the `handlers`.\n\n Arguments:\n handlers (list): List of claim :class:`Handler` classes.\n access_token (:class:AccessToken): Associated access token.\n scope_request...
""" OpenID Connect core related utility functions. Defines utility functions to process the ID Token and UserInfo endpoints according to the OpenID Connect specification. """ from __future__ import absolute_import, division, print_function, unicode_literals import jwt import provider.scope from django.utils.module_l...
edx/edx-oauth2-provider
edx_oauth2_provider/oidc/core.py
IDToken.encode
python
def encode(self, secret, algorithm='HS256'): return jwt.encode(self.claims, secret, algorithm)
Encode the set of claims to the JWT (JSON Web Token) format according to the OpenID Connect specification: http://openid.net/specs/openid-connect-basic-1_0.html#IDToken Arguments: claims (dict): A dictionary with the OpenID Connect claims. secret (str): Secret used to e...
train
https://github.com/edx/edx-oauth2-provider/blob/73e7569a8369e74c345022ccba634365e24befab/edx_oauth2_provider/oidc/core.py#L39-L56
null
class IDToken(object): """ Simple container for OpenID Connect related responses. Attributes: access_token (:class:`AccessToken`): Associated Access Token object. scopes (list): List of scope names. claims (dict): Dictionary of claim names and values. """ def __init__(self...
edx/edx-oauth2-provider
edx_oauth2_provider/views.py
AccessTokenView.access_token_response_data
python
def access_token_response_data(self, access_token, response_type=None, nonce=''): # Clear the scope for requests that do not use OpenID Connect. # Scopes for pure OAuth2 request are currently not supported. scope = constants.DEFAULT_SCOPE extra_data = {} # Add OpenID Connect `...
Return `access_token` fields for OAuth2, and add `id_token` fields for OpenID Connect according to the `access_token` scope.
train
https://github.com/edx/edx-oauth2-provider/blob/73e7569a8369e74c345022ccba634365e24befab/edx_oauth2_provider/views.py#L110-L145
[ "def get_id_token(self, access_token, nonce):\n \"\"\" Return an ID token for the given Access Token. \"\"\"\n\n claims_string = self.request.POST.get('claims')\n claims_request = json.loads(claims_string) if claims_string else {}\n\n return oidc.id_token(access_token, nonce, claims_request)\n", "def ...
class AccessTokenView(provider.oauth2.views.AccessTokenView): """ Customized OAuth2 access token view. Allows usage of email as main identifier when requesting a password grant. Support the ID Token endpoint following the OpenID Connect specification: - http://openid.net/specs/openid-connect-core...
edx/edx-oauth2-provider
edx_oauth2_provider/views.py
AccessTokenView.get_id_token
python
def get_id_token(self, access_token, nonce): claims_string = self.request.POST.get('claims') claims_request = json.loads(claims_string) if claims_string else {} return oidc.id_token(access_token, nonce, claims_request)
Return an ID token for the given Access Token.
train
https://github.com/edx/edx-oauth2-provider/blob/73e7569a8369e74c345022ccba634365e24befab/edx_oauth2_provider/views.py#L147-L153
[ "def id_token(access_token, nonce=None, claims_request=None):\n \"\"\"\n Returns data required for an OpenID Connect ID Token according to:\n\n - http://openid.net/specs/openid-connect-basic-1_0.html#IDToken\n\n Arguments:\n access_token (:class:`AccessToken`): Associated OAuth2 access token.\n ...
class AccessTokenView(provider.oauth2.views.AccessTokenView): """ Customized OAuth2 access token view. Allows usage of email as main identifier when requesting a password grant. Support the ID Token endpoint following the OpenID Connect specification: - http://openid.net/specs/openid-connect-core...
edx/edx-oauth2-provider
edx_oauth2_provider/views.py
AccessTokenView.encode_id_token
python
def encode_id_token(self, id_token): # Encode the ID token using the `client_secret`. # # TODO: Using the `client_secret` is not ideal, since it is transmitted # over the wire in some authentication flows. A better alternative is # to use the public key of the issuer, which als...
Return encoded ID token.
train
https://github.com/edx/edx-oauth2-provider/blob/73e7569a8369e74c345022ccba634365e24befab/edx_oauth2_provider/views.py#L155-L171
null
class AccessTokenView(provider.oauth2.views.AccessTokenView): """ Customized OAuth2 access token view. Allows usage of email as main identifier when requesting a password grant. Support the ID Token endpoint following the OpenID Connect specification: - http://openid.net/specs/openid-connect-core...
edx/edx-oauth2-provider
edx_oauth2_provider/views.py
UserInfoView.get
python
def get(self, request, *_args, **_kwargs): access_token = self.access_token scope_string = request.GET.get('scope') scope_request = scope_string.split() if scope_string else None claims_string = request.GET.get('claims') claims_request = json.loads(claims_string) if claims_str...
Respond to a UserInfo request. Two optional query parameters are accepted, scope and claims. See the references above for more details.
train
https://github.com/edx/edx-oauth2-provider/blob/73e7569a8369e74c345022ccba634365e24befab/edx_oauth2_provider/views.py#L244-L273
null
class UserInfoView(ProtectedView): """ Implementation of the Basic OpenID Connect UserInfo endpoint as described in: - http://openid.net/specs/openid-connect-basic-1_0.html#UserInfo By default it returns all the claims available to the `access_token` used, and available to the claim handlers confi...
edx/edx-oauth2-provider
edx_oauth2_provider/views.py
UserInfoView.userinfo_claims
python
def userinfo_claims(self, access_token, scope_request, claims_request): id_token = oidc.userinfo(access_token, scope_request, claims_request) return id_token.claims
Return the claims for the requested parameters.
train
https://github.com/edx/edx-oauth2-provider/blob/73e7569a8369e74c345022ccba634365e24befab/edx_oauth2_provider/views.py#L275-L278
[ "def userinfo(access_token, scope_request=None, claims_request=None):\n \"\"\"\n Returns data required for an OpenID Connect UserInfo response, according to:\n\n http://openid.net/specs/openid-connect-basic-1_0.html#UserInfoResponse\n\n Supports scope and claims request parameter as described in:\n\n ...
class UserInfoView(ProtectedView): """ Implementation of the Basic OpenID Connect UserInfo endpoint as described in: - http://openid.net/specs/openid-connect-basic-1_0.html#UserInfo By default it returns all the claims available to the `access_token` used, and available to the claim handlers confi...
edx/edx-oauth2-provider
edx_oauth2_provider/oidc/collect.py
collect
python
def collect(handlers, access_token, scope_request=None, claims_request=None): user = access_token.user client = access_token.client # Instantiate handlers. Each handler is instanciated only once, allowing the # handler to keep state in-between calls to its scope and claim methods. handlers = [cls(...
Collect all the claims values from the `handlers`. Arguments: handlers (list): List of claim :class:`Handler` classes. access_token (:class:AccessToken): Associated access token. scope_request (list): List of requested scopes. claims_request (dict): Dictionary with only the relevant section...
train
https://github.com/edx/edx-oauth2-provider/blob/73e7569a8369e74c345022ccba634365e24befab/edx_oauth2_provider/oidc/collect.py#L19-L81
[ "def _collect_scopes(handlers, scopes, user, client):\n \"\"\" Get a set of all the authorized scopes according to the handlers. \"\"\"\n results = set()\n\n data = {'user': user, 'client': client}\n\n def visitor(scope_name, func):\n claim_names = func(data)\n # If the claim_names is None...
""" Functions to collect OpenID Connect values from claim handlers. For details on the format of the claim handlers, see :mod:`oauth2_provider.oicd.handlers` None: The functions in this module assume the `openid` scope is implied. """ # pylint: disable=missing-docstring from __future__ import absolute_import, divisio...
edx/edx-oauth2-provider
edx_oauth2_provider/oidc/collect.py
_collect_scopes
python
def _collect_scopes(handlers, scopes, user, client): results = set() data = {'user': user, 'client': client} def visitor(scope_name, func): claim_names = func(data) # If the claim_names is None, it means that the scope is not authorized. if claim_names is not None: resu...
Get a set of all the authorized scopes according to the handlers.
train
https://github.com/edx/edx-oauth2-provider/blob/73e7569a8369e74c345022ccba634365e24befab/edx_oauth2_provider/oidc/collect.py#L84-L98
[ "def _visit_handlers(handlers, visitor, prefix, suffixes):\n \"\"\" Use visitor partern to collect information from handlers \"\"\"\n\n results = []\n for handler in handlers:\n for suffix in suffixes:\n func = getattr(handler, '{}_{}'.format(prefix, suffix).lower(), None)\n if...
""" Functions to collect OpenID Connect values from claim handlers. For details on the format of the claim handlers, see :mod:`oauth2_provider.oicd.handlers` None: The functions in this module assume the `openid` scope is implied. """ # pylint: disable=missing-docstring from __future__ import absolute_import, divisio...
edx/edx-oauth2-provider
edx_oauth2_provider/oidc/collect.py
_collect_names
python
def _collect_names(handlers, scopes, user, client): results = set() data = {'user': user, 'client': client} def visitor(_scope_name, func): claim_names = func(data) # If the claim_names is None, it means that the scope is not authorized. if claim_names is not None: res...
Get the names of the claims supported by the handlers for the requested scope.
train
https://github.com/edx/edx-oauth2-provider/blob/73e7569a8369e74c345022ccba634365e24befab/edx_oauth2_provider/oidc/collect.py#L101-L116
[ "def _visit_handlers(handlers, visitor, prefix, suffixes):\n \"\"\" Use visitor partern to collect information from handlers \"\"\"\n\n results = []\n for handler in handlers:\n for suffix in suffixes:\n func = getattr(handler, '{}_{}'.format(prefix, suffix).lower(), None)\n if...
""" Functions to collect OpenID Connect values from claim handlers. For details on the format of the claim handlers, see :mod:`oauth2_provider.oicd.handlers` None: The functions in this module assume the `openid` scope is implied. """ # pylint: disable=missing-docstring from __future__ import absolute_import, divisio...
edx/edx-oauth2-provider
edx_oauth2_provider/oidc/collect.py
_collect_values
python
def _collect_values(handlers, names, user, client, values): results = {} def visitor(claim_name, func): data = {'user': user, 'client': client} data.update(values.get(claim_name) or {}) claim_value = func(data) # If the claim_value is None, it means that the claim is not author...
Get the values from the handlers of the requested claims.
train
https://github.com/edx/edx-oauth2-provider/blob/73e7569a8369e74c345022ccba634365e24befab/edx_oauth2_provider/oidc/collect.py#L119-L135
[ "def _visit_handlers(handlers, visitor, prefix, suffixes):\n \"\"\" Use visitor partern to collect information from handlers \"\"\"\n\n results = []\n for handler in handlers:\n for suffix in suffixes:\n func = getattr(handler, '{}_{}'.format(prefix, suffix).lower(), None)\n if...
""" Functions to collect OpenID Connect values from claim handlers. For details on the format of the claim handlers, see :mod:`oauth2_provider.oicd.handlers` None: The functions in this module assume the `openid` scope is implied. """ # pylint: disable=missing-docstring from __future__ import absolute_import, divisio...
edx/edx-oauth2-provider
edx_oauth2_provider/oidc/collect.py
_validate_claim_request
python
def _validate_claim_request(claims, ignore_errors=False): results = {} claims = claims if claims else {} for name, value in claims.iteritems(): if value is None: results[name] = None elif isinstance(value, dict): results[name] = _validate_claim_values(name, value, i...
Validates a claim request section (`userinfo` or `id_token`) according to section 5.5 of the OpenID Connect specification: - http://openid.net/specs/openid-connect-core-1_0.html#ClaimsParameter Returns a copy of the claim request with only the valid fields and values. Raises ValueError is the claim r...
train
https://github.com/edx/edx-oauth2-provider/blob/73e7569a8369e74c345022ccba634365e24befab/edx_oauth2_provider/oidc/collect.py#L138-L164
[ "def _validate_claim_values(name, value, ignore_errors):\n \"\"\" Helper for `validate_claim_request` \"\"\"\n results = {'essential': False}\n for key, value in value.iteritems():\n if key in CLAIM_REQUEST_FIELDS:\n results[key] = value\n else:\n if not ignore_errors:\n...
""" Functions to collect OpenID Connect values from claim handlers. For details on the format of the claim handlers, see :mod:`oauth2_provider.oicd.handlers` None: The functions in this module assume the `openid` scope is implied. """ # pylint: disable=missing-docstring from __future__ import absolute_import, divisio...
edx/edx-oauth2-provider
edx_oauth2_provider/oidc/collect.py
_validate_claim_values
python
def _validate_claim_values(name, value, ignore_errors): results = {'essential': False} for key, value in value.iteritems(): if key in CLAIM_REQUEST_FIELDS: results[key] = value else: if not ignore_errors: msg = 'Unknown attribute {} in claim value {}.'.for...
Helper for `validate_claim_request`
train
https://github.com/edx/edx-oauth2-provider/blob/73e7569a8369e74c345022ccba634365e24befab/edx_oauth2_provider/oidc/collect.py#L167-L177
null
""" Functions to collect OpenID Connect values from claim handlers. For details on the format of the claim handlers, see :mod:`oauth2_provider.oicd.handlers` None: The functions in this module assume the `openid` scope is implied. """ # pylint: disable=missing-docstring from __future__ import absolute_import, divisio...
edx/edx-oauth2-provider
edx_oauth2_provider/oidc/collect.py
_visit_handlers
python
def _visit_handlers(handlers, visitor, prefix, suffixes): results = [] for handler in handlers: for suffix in suffixes: func = getattr(handler, '{}_{}'.format(prefix, suffix).lower(), None) if func: results.append(visitor(suffix, func)) return results
Use visitor partern to collect information from handlers
train
https://github.com/edx/edx-oauth2-provider/blob/73e7569a8369e74c345022ccba634365e24befab/edx_oauth2_provider/oidc/collect.py#L180-L190
null
""" Functions to collect OpenID Connect values from claim handlers. For details on the format of the claim handlers, see :mod:`oauth2_provider.oicd.handlers` None: The functions in this module assume the `openid` scope is implied. """ # pylint: disable=missing-docstring from __future__ import absolute_import, divisio...
eight04/pyAPNG
apng/__init__.py
parse_chunks
python
def parse_chunks(b): # skip signature i = 8 # yield chunks while i < len(b): data_len, = struct.unpack("!I", b[i:i+4]) type_ = b[i+4:i+8].decode("latin-1") yield Chunk(type_, b[i:i+data_len+12]) i += data_len + 12
Parse PNG bytes into multiple chunks. :arg bytes b: The raw bytes of the PNG file. :return: A generator yielding :class:`Chunk`. :rtype: Iterator[Chunk]
train
https://github.com/eight04/pyAPNG/blob/b4d2927f7892a1de967b5cf57d434ed65f6a017e/apng/__init__.py#L27-L41
null
#! python3 """This is an APNG module, which can create apng file from pngs Reference: http://littlesvr.ca/apng/ http://wiki.mozilla.org/APNG_Specification https://www.w3.org/TR/PNG/ """ import struct import binascii import io import zlib from collections import namedtuple __version__ = "0.3.3" PNG_SIGN = b"\x89\x5...
eight04/pyAPNG
apng/__init__.py
make_chunk
python
def make_chunk(chunk_type, chunk_data): out = struct.pack("!I", len(chunk_data)) chunk_data = chunk_type.encode("latin-1") + chunk_data out += chunk_data + struct.pack("!I", binascii.crc32(chunk_data) & 0xffffffff) return out
Create a raw chunk by composing chunk type and data. It calculates chunk length and CRC for you. :arg str chunk_type: PNG chunk type. :arg bytes chunk_data: PNG chunk data, **excluding chunk length, type, and CRC**. :rtype: bytes
train
https://github.com/eight04/pyAPNG/blob/b4d2927f7892a1de967b5cf57d434ed65f6a017e/apng/__init__.py#L43-L54
null
#! python3 """This is an APNG module, which can create apng file from pngs Reference: http://littlesvr.ca/apng/ http://wiki.mozilla.org/APNG_Specification https://www.w3.org/TR/PNG/ """ import struct import binascii import io import zlib from collections import namedtuple __version__ = "0.3.3" PNG_SIGN = b"\x89\x5...
eight04/pyAPNG
apng/__init__.py
make_text_chunk
python
def make_text_chunk( type="tEXt", key="Comment", value="", compression_flag=0, compression_method=0, lang="", translated_key=""): # pylint: disable=redefined-builtin if type == "tEXt": data = key.encode("latin-1") + b"\0" + value.encode("latin-1") elif type == "zTXt": data = ( key.encode("latin-1") + stru...
Create a text chunk with a key value pair. See https://www.w3.org/TR/PNG/#11textinfo for text chunk information. Usage: .. code:: python from apng import APNG, make_text_chunk im = APNG.open("file.png") png, control = im.frames[0] png.chunks.append(make_text_chunk("tEXt", "Comment", "some text")) im.s...
train
https://github.com/eight04/pyAPNG/blob/b4d2927f7892a1de967b5cf57d434ed65f6a017e/apng/__init__.py#L56-L111
[ "def make_chunk(chunk_type, chunk_data):\n\t\"\"\"Create a raw chunk by composing chunk type and data. It\n\tcalculates chunk length and CRC for you.\n\n\t:arg str chunk_type: PNG chunk type.\n\t:arg bytes chunk_data: PNG chunk data, **excluding chunk length, type, and CRC**.\n\t:rtype: bytes\n\t\"\"\"\n\tout = str...
#! python3 """This is an APNG module, which can create apng file from pngs Reference: http://littlesvr.ca/apng/ http://wiki.mozilla.org/APNG_Specification https://www.w3.org/TR/PNG/ """ import struct import binascii import io import zlib from collections import namedtuple __version__ = "0.3.3" PNG_SIGN = b"\x89\x5...