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
davidrpugh/pyCollocation
pycollocation/solvers/solvers.py
SolverLike._compute_residuals
python
def _compute_residuals(self, coefs_array, basis_kwargs, boundary_points, nodes, problem): coefs_list = self._array_to_list(coefs_array, problem.number_odes) derivs, funcs = self._construct_approximation(basis_kwargs, coefs_list) resids = self._assess_approximation(boundary_points, derivs, funcs,...
Return collocation residuals. Parameters ---------- coefs_array : numpy.ndarray basis_kwargs : dict problem : TwoPointBVPLike Returns ------- resids : numpy.ndarray
train
https://github.com/davidrpugh/pyCollocation/blob/9376f3488a992dc416cfd2a4dbb396d094927569/pycollocation/solvers/solvers.py#L124-L143
null
class SolverLike(object): """ Class describing the protocol the all SolverLike objects should satisfy. Notes ----- Subclasses should implement `solve` method as described below. """ @property def basis_functions(self): r""" Functions used to approximate the solution to...
davidrpugh/pyCollocation
pycollocation/solvers/solvers.py
SolverLike._construct_approximation
python
def _construct_approximation(self, basis_kwargs, coefs_list): derivs = self._construct_derivatives(coefs_list, **basis_kwargs) funcs = self._construct_functions(coefs_list, **basis_kwargs) return derivs, funcs
Construct a collection of derivatives and functions that approximate the solution to the boundary value problem. Parameters ---------- basis_kwargs : dict(str: ) coefs_list : list(numpy.ndarray) Returns ------- basis_derivs : list(function) basis...
train
https://github.com/davidrpugh/pyCollocation/blob/9376f3488a992dc416cfd2a4dbb396d094927569/pycollocation/solvers/solvers.py#L145-L163
null
class SolverLike(object): """ Class describing the protocol the all SolverLike objects should satisfy. Notes ----- Subclasses should implement `solve` method as described below. """ @property def basis_functions(self): r""" Functions used to approximate the solution to...
davidrpugh/pyCollocation
pycollocation/solvers/solvers.py
SolverLike._construct_derivatives
python
def _construct_derivatives(self, coefs, **kwargs): return [self.basis_functions.derivatives_factory(coef, **kwargs) for coef in coefs]
Return a list of derivatives given a list of coefficients.
train
https://github.com/davidrpugh/pyCollocation/blob/9376f3488a992dc416cfd2a4dbb396d094927569/pycollocation/solvers/solvers.py#L165-L167
null
class SolverLike(object): """ Class describing the protocol the all SolverLike objects should satisfy. Notes ----- Subclasses should implement `solve` method as described below. """ @property def basis_functions(self): r""" Functions used to approximate the solution to...
davidrpugh/pyCollocation
pycollocation/solvers/solvers.py
SolverLike._construct_functions
python
def _construct_functions(self, coefs, **kwargs): return [self.basis_functions.functions_factory(coef, **kwargs) for coef in coefs]
Return a list of functions given a list of coefficients.
train
https://github.com/davidrpugh/pyCollocation/blob/9376f3488a992dc416cfd2a4dbb396d094927569/pycollocation/solvers/solvers.py#L169-L171
null
class SolverLike(object): """ Class describing the protocol the all SolverLike objects should satisfy. Notes ----- Subclasses should implement `solve` method as described below. """ @property def basis_functions(self): r""" Functions used to approximate the solution to...
davidrpugh/pyCollocation
pycollocation/solvers/solvers.py
SolverLike._solution_factory
python
def _solution_factory(self, basis_kwargs, coefs_array, nodes, problem, result): soln_coefs = self._array_to_list(coefs_array, problem.number_odes) soln_derivs = self._construct_derivatives(soln_coefs, **basis_kwargs) soln_funcs = self._construct_functions(soln_coefs, **basis_kwargs) soln...
Construct a representation of the solution to the boundary value problem. Parameters ---------- basis_kwargs : dict(str : ) coefs_array : numpy.ndarray problem : TwoPointBVPLike result : OptimizeResult Returns ------- solution : SolutionLike
train
https://github.com/davidrpugh/pyCollocation/blob/9376f3488a992dc416cfd2a4dbb396d094927569/pycollocation/solvers/solvers.py#L173-L197
[ "def _array_to_list(coefs_array, indices_or_sections, axis=0):\n \"\"\"Split an array into a list of arrays.\"\"\"\n return np.split(coefs_array, indices_or_sections, axis)\n", "def _interior_residuals_factory(cls, derivs, funcs, problem):\n return functools.partial(cls._interior_residuals, derivs, funcs...
class SolverLike(object): """ Class describing the protocol the all SolverLike objects should satisfy. Notes ----- Subclasses should implement `solve` method as described below. """ @property def basis_functions(self): r""" Functions used to approximate the solution to...
davidrpugh/pyCollocation
pycollocation/solvers/solvers.py
Solver.solve
python
def solve(self, basis_kwargs, boundary_points, coefs_array, nodes, problem, **solver_options): result = optimize.root(self._compute_residuals, x0=coefs_array, args=(basis_kwargs, boundary_points, nodes, problem), ...
Solve a boundary value problem using the collocation method. Parameters ---------- basis_kwargs : dict Dictionary of keyword arguments used to build basis functions. coefs_array : numpy.ndarray Array of coefficients for basis functions defining the initial ...
train
https://github.com/davidrpugh/pyCollocation/blob/9376f3488a992dc416cfd2a4dbb396d094927569/pycollocation/solvers/solvers.py#L234-L267
[ "def _solution_factory(self, basis_kwargs, coefs_array, nodes, problem, result):\n \"\"\"\n Construct a representation of the solution to the boundary value problem.\n\n Parameters\n ----------\n basis_kwargs : dict(str : )\n coefs_array : numpy.ndarray\n problem : TwoPointBVPLike\n result :...
class Solver(SolverLike): def __init__(self, basis_functions): self._basis_functions = basis_functions
davidrpugh/pyCollocation
pycollocation/solvers/solutions.py
Solution.normalize_residuals
python
def normalize_residuals(self, points): residuals = self.evaluate_residual(points) solutions = self.evaluate_solution(points) return [resid / soln for resid, soln in zip(residuals, solutions)]
Normalize residuals by the level of the variable.
train
https://github.com/davidrpugh/pyCollocation/blob/9376f3488a992dc416cfd2a4dbb396d094927569/pycollocation/solvers/solutions.py#L66-L70
[ "def evaluate_residual(self, points):\n return self.residual_function(points)\n", "def evaluate_solution(self, points):\n return [f(points) for f in self.functions]\n" ]
class Solution(SolutionLike): """Class representing the solution to a Boundary Value Problem (BVP).""" def __init__(self, basis_kwargs, functions, nodes, problem, residual_function, result): """ Initialize an instance of the Solution class. Parameters ---------- basis_k...
davidrpugh/pyCollocation
pycollocation/basis_functions/polynomials.py
PolynomialBasis._basis_polynomial_factory
python
def _basis_polynomial_factory(cls, kind): valid_kind = cls._validate(kind) basis_polynomial = getattr(np.polynomial, valid_kind) return basis_polynomial
Return a polynomial given some coefficients.
train
https://github.com/davidrpugh/pyCollocation/blob/9376f3488a992dc416cfd2a4dbb396d094927569/pycollocation/basis_functions/polynomials.py#L23-L27
null
class PolynomialBasis(basis_functions.BasisFunctionLike): _valid_kinds = ['Polynomial', 'Chebyshev', 'Legendre', 'Laguerre', 'Hermite'] @staticmethod def _basis_monomial_coefs(degree): """Return coefficients for a monomial of a given degree.""" return np.append(np.zeros(degree), 1) @c...
davidrpugh/pyCollocation
pycollocation/basis_functions/polynomials.py
PolynomialBasis._validate
python
def _validate(cls, kind): if kind not in cls._valid_kinds: mesg = "'kind' must be one of {}, {}, {}, or {}." raise ValueError(mesg.format(*cls._valid_kinds)) else: return kind
Validate the kind argument.
train
https://github.com/davidrpugh/pyCollocation/blob/9376f3488a992dc416cfd2a4dbb396d094927569/pycollocation/basis_functions/polynomials.py#L30-L36
null
class PolynomialBasis(basis_functions.BasisFunctionLike): _valid_kinds = ['Polynomial', 'Chebyshev', 'Legendre', 'Laguerre', 'Hermite'] @staticmethod def _basis_monomial_coefs(degree): """Return coefficients for a monomial of a given degree.""" return np.append(np.zeros(degree), 1) @c...
davidrpugh/pyCollocation
pycollocation/basis_functions/polynomials.py
PolynomialBasis.derivatives_factory
python
def derivatives_factory(cls, coef, domain, kind, **kwargs): basis_polynomial = cls._basis_polynomial_factory(kind) return basis_polynomial(coef, domain).deriv()
Given some coefficients, return a the derivative of a certain kind of orthogonal polynomial defined over a specific domain.
train
https://github.com/davidrpugh/pyCollocation/blob/9376f3488a992dc416cfd2a4dbb396d094927569/pycollocation/basis_functions/polynomials.py#L39-L46
null
class PolynomialBasis(basis_functions.BasisFunctionLike): _valid_kinds = ['Polynomial', 'Chebyshev', 'Legendre', 'Laguerre', 'Hermite'] @staticmethod def _basis_monomial_coefs(degree): """Return coefficients for a monomial of a given degree.""" return np.append(np.zeros(degree), 1) @c...
davidrpugh/pyCollocation
pycollocation/basis_functions/polynomials.py
PolynomialBasis.functions_factory
python
def functions_factory(cls, coef, domain, kind, **kwargs): basis_polynomial = cls._basis_polynomial_factory(kind) return basis_polynomial(coef, domain)
Given some coefficients, return a certain kind of orthogonal polynomial defined over a specific domain.
train
https://github.com/davidrpugh/pyCollocation/blob/9376f3488a992dc416cfd2a4dbb396d094927569/pycollocation/basis_functions/polynomials.py#L54-L61
null
class PolynomialBasis(basis_functions.BasisFunctionLike): _valid_kinds = ['Polynomial', 'Chebyshev', 'Legendre', 'Laguerre', 'Hermite'] @staticmethod def _basis_monomial_coefs(degree): """Return coefficients for a monomial of a given degree.""" return np.append(np.zeros(degree), 1) @c...
davidrpugh/pyCollocation
pycollocation/basis_functions/polynomials.py
PolynomialBasis.roots
python
def roots(cls, degree, domain, kind): basis_coefs = cls._basis_monomial_coefs(degree) basis_poly = cls.functions_factory(basis_coefs, domain, kind) return basis_poly.roots()
Return optimal collocation nodes for some orthogonal polynomial.
train
https://github.com/davidrpugh/pyCollocation/blob/9376f3488a992dc416cfd2a4dbb396d094927569/pycollocation/basis_functions/polynomials.py#L64-L68
null
class PolynomialBasis(basis_functions.BasisFunctionLike): _valid_kinds = ['Polynomial', 'Chebyshev', 'Legendre', 'Laguerre', 'Hermite'] @staticmethod def _basis_monomial_coefs(degree): """Return coefficients for a monomial of a given degree.""" return np.append(np.zeros(degree), 1) @c...
brunobord/meuhdb
meuhdb/core.py
autocommit
python
def autocommit(f): "A decorator to commit to the storage if autocommit is set to True." @wraps(f) def wrapper(self, *args, **kwargs): result = f(self, *args, **kwargs) if self._meta.commit_ready(): self.commit() return result return wrapper
A decorator to commit to the storage if autocommit is set to True.
train
https://github.com/brunobord/meuhdb/blob/2ef2ea0b1065768d88f52bacf1b94b3d3ce3d9eb/meuhdb/core.py#L18-L26
null
#-*- coding: utf-8 -*- """ MeuhDB, a database that says "meuh". """ from __future__ import unicode_literals from copy import deepcopy from functools import wraps import os from uuid import uuid4 import warnings import six from .backends import DEFAULT_BACKEND, BACKENDS from .exceptions import BadValueError def int...
brunobord/meuhdb
meuhdb/core.py
intersect
python
def intersect(d1, d2): return dict((k, d1[k]) for k in d1 if k in d2 and d1[k] == d2[k])
Intersect dictionaries d1 and d2 by key *and* value.
train
https://github.com/brunobord/meuhdb/blob/2ef2ea0b1065768d88f52bacf1b94b3d3ce3d9eb/meuhdb/core.py#L29-L31
null
#-*- coding: utf-8 -*- """ MeuhDB, a database that says "meuh". """ from __future__ import unicode_literals from copy import deepcopy from functools import wraps import os from uuid import uuid4 import warnings import six from .backends import DEFAULT_BACKEND, BACKENDS from .exceptions import BadValueError def auto...
brunobord/meuhdb
meuhdb/core.py
MeuhDb.set
python
def set(self, key, value): "Set value to the key store." # if key already in data, update indexes if not isinstance(value, dict): raise BadValueError( 'The value {} is incorrect.' ' Values should be strings'.format(value)) _value = deepcopy(val...
Set value to the key store.
train
https://github.com/brunobord/meuhdb/blob/2ef2ea0b1065768d88f52bacf1b94b3d3ce3d9eb/meuhdb/core.py#L157-L168
[ "def delete_from_index(self, key):\n \"Delete references from the index of the key old value(s).\"\n old_value = self.data[key]\n keys = set(old_value.keys()).intersection(self.indexes.keys())\n for index_name in keys:\n if old_value[index_name] in self.indexes[index_name]:\n del self....
class MeuhDb(object): """ MeuhDb is a key / JSON value store. """ def __init__(self, path=None, autocommit=False, autocommit_after=None, lazy_indexes=False, backend=DEFAULT_BACKEND): """ Options: * ``path``: Path to the DB filen...
brunobord/meuhdb
meuhdb/core.py
MeuhDb.insert
python
def insert(self, value): "Insert value in the keystore. Return the UUID key." key = str(uuid4()) self.set(key, value) return key
Insert value in the keystore. Return the UUID key.
train
https://github.com/brunobord/meuhdb/blob/2ef2ea0b1065768d88f52bacf1b94b3d3ce3d9eb/meuhdb/core.py#L171-L175
null
class MeuhDb(object): """ MeuhDb is a key / JSON value store. """ def __init__(self, path=None, autocommit=False, autocommit_after=None, lazy_indexes=False, backend=DEFAULT_BACKEND): """ Options: * ``path``: Path to the DB filen...
brunobord/meuhdb
meuhdb/core.py
MeuhDb.delete
python
def delete(self, key): "Delete a `key` from the keystore." if key in self.data: self.delete_from_index(key) del self.data[key]
Delete a `key` from the keystore.
train
https://github.com/brunobord/meuhdb/blob/2ef2ea0b1065768d88f52bacf1b94b3d3ce3d9eb/meuhdb/core.py#L178-L182
[ "def delete_from_index(self, key):\n \"Delete references from the index of the key old value(s).\"\n old_value = self.data[key]\n keys = set(old_value.keys()).intersection(self.indexes.keys())\n for index_name in keys:\n if old_value[index_name] in self.indexes[index_name]:\n del self....
class MeuhDb(object): """ MeuhDb is a key / JSON value store. """ def __init__(self, path=None, autocommit=False, autocommit_after=None, lazy_indexes=False, backend=DEFAULT_BACKEND): """ Options: * ``path``: Path to the DB filen...
brunobord/meuhdb
meuhdb/core.py
MeuhDb.update
python
def update(self, key, value): if not isinstance(value, dict): raise BadValueError( 'The value {} is incorrect.' ' Values should be strings'.format(value)) if key in self.data: v = self.get(key) v.update(value) else: ...
Update a `key` in the keystore. If the key is non-existent, it's being created
train
https://github.com/brunobord/meuhdb/blob/2ef2ea0b1065768d88f52bacf1b94b3d3ce3d9eb/meuhdb/core.py#L185-L198
[ "def get(self, key):\n \"\"\"\n Return value of 'key' if it's in the database.\n Raise KeyError if not.\n \"\"\"\n return self.data[key]\n" ]
class MeuhDb(object): """ MeuhDb is a key / JSON value store. """ def __init__(self, path=None, autocommit=False, autocommit_after=None, lazy_indexes=False, backend=DEFAULT_BACKEND): """ Options: * ``path``: Path to the DB filen...
brunobord/meuhdb
meuhdb/core.py
MeuhDb.del_key
python
def del_key(self, key, key_to_delete): "Delete the `key_to_delete` for the record found with `key`." v = self.get(key) if key_to_delete in v: del v[key_to_delete] self.set(key, v)
Delete the `key_to_delete` for the record found with `key`.
train
https://github.com/brunobord/meuhdb/blob/2ef2ea0b1065768d88f52bacf1b94b3d3ce3d9eb/meuhdb/core.py#L208-L213
[ "def get(self, key):\n \"\"\"\n Return value of 'key' if it's in the database.\n Raise KeyError if not.\n \"\"\"\n return self.data[key]\n" ]
class MeuhDb(object): """ MeuhDb is a key / JSON value store. """ def __init__(self, path=None, autocommit=False, autocommit_after=None, lazy_indexes=False, backend=DEFAULT_BACKEND): """ Options: * ``path``: Path to the DB filen...
brunobord/meuhdb
meuhdb/core.py
MeuhDb.commit
python
def commit(self): "Commit data to the storage." if self._meta.path: with open(self._meta.path, 'wb') as fd: raw = deepcopy(self.raw) # LAZY INDEX PROCESSING # Save indexes only if not lazy lazy_indexes = self.lazy_indexes # Kee...
Commit data to the storage.
train
https://github.com/brunobord/meuhdb/blob/2ef2ea0b1065768d88f52bacf1b94b3d3ce3d9eb/meuhdb/core.py#L215-L236
[ "def serialize(self, obj):\n return self._meta.serializer(obj)\n" ]
class MeuhDb(object): """ MeuhDb is a key / JSON value store. """ def __init__(self, path=None, autocommit=False, autocommit_after=None, lazy_indexes=False, backend=DEFAULT_BACKEND): """ Options: * ``path``: Path to the DB filen...
brunobord/meuhdb
meuhdb/core.py
MeuhDb.keys_to_values
python
def keys_to_values(self, keys): "Return the items in the keystore with keys in `keys`." return dict((k, v) for k, v in self.data.items() if k in keys)
Return the items in the keystore with keys in `keys`.
train
https://github.com/brunobord/meuhdb/blob/2ef2ea0b1065768d88f52bacf1b94b3d3ce3d9eb/meuhdb/core.py#L242-L244
null
class MeuhDb(object): """ MeuhDb is a key / JSON value store. """ def __init__(self, path=None, autocommit=False, autocommit_after=None, lazy_indexes=False, backend=DEFAULT_BACKEND): """ Options: * ``path``: Path to the DB filen...
brunobord/meuhdb
meuhdb/core.py
MeuhDb.filter_keys
python
def filter_keys(self, **kwargs): "Return a set of keys filtered according to the given arguments." self._used_index = False keys = set(self.data.keys()) for key_filter, v_filter in kwargs.items(): if key_filter in self.indexes: self._used_index = True ...
Return a set of keys filtered according to the given arguments.
train
https://github.com/brunobord/meuhdb/blob/2ef2ea0b1065768d88f52bacf1b94b3d3ce3d9eb/meuhdb/core.py#L246-L261
[ "def simple_filter(self, key, value):\n \"Search keys whose values match with the searched values\"\n searched = {key: value}\n return set([k for k, v in self.data.items() if\n intersect(searched, v) == searched])\n" ]
class MeuhDb(object): """ MeuhDb is a key / JSON value store. """ def __init__(self, path=None, autocommit=False, autocommit_after=None, lazy_indexes=False, backend=DEFAULT_BACKEND): """ Options: * ``path``: Path to the DB filen...
brunobord/meuhdb
meuhdb/core.py
MeuhDb.simple_filter
python
def simple_filter(self, key, value): "Search keys whose values match with the searched values" searched = {key: value} return set([k for k, v in self.data.items() if intersect(searched, v) == searched])
Search keys whose values match with the searched values
train
https://github.com/brunobord/meuhdb/blob/2ef2ea0b1065768d88f52bacf1b94b3d3ce3d9eb/meuhdb/core.py#L263-L267
null
class MeuhDb(object): """ MeuhDb is a key / JSON value store. """ def __init__(self, path=None, autocommit=False, autocommit_after=None, lazy_indexes=False, backend=DEFAULT_BACKEND): """ Options: * ``path``: Path to the DB filen...
brunobord/meuhdb
meuhdb/core.py
MeuhDb.filter
python
def filter(self, **kwargs): keys = self.filter_keys(**kwargs) return self.keys_to_values(keys)
Filter data according to the given arguments.
train
https://github.com/brunobord/meuhdb/blob/2ef2ea0b1065768d88f52bacf1b94b3d3ce3d9eb/meuhdb/core.py#L269-L274
[ "def keys_to_values(self, keys):\n \"Return the items in the keystore with keys in `keys`.\"\n return dict((k, v) for k, v in self.data.items() if k in keys)\n", "def filter_keys(self, **kwargs):\n \"Return a set of keys filtered according to the given arguments.\"\n self._used_index = False\n keys...
class MeuhDb(object): """ MeuhDb is a key / JSON value store. """ def __init__(self, path=None, autocommit=False, autocommit_after=None, lazy_indexes=False, backend=DEFAULT_BACKEND): """ Options: * ``path``: Path to the DB filen...
brunobord/meuhdb
meuhdb/core.py
MeuhDb.delete_from_index
python
def delete_from_index(self, key): "Delete references from the index of the key old value(s)." old_value = self.data[key] keys = set(old_value.keys()).intersection(self.indexes.keys()) for index_name in keys: if old_value[index_name] in self.indexes[index_name]: ...
Delete references from the index of the key old value(s).
train
https://github.com/brunobord/meuhdb/blob/2ef2ea0b1065768d88f52bacf1b94b3d3ce3d9eb/meuhdb/core.py#L276-L282
null
class MeuhDb(object): """ MeuhDb is a key / JSON value store. """ def __init__(self, path=None, autocommit=False, autocommit_after=None, lazy_indexes=False, backend=DEFAULT_BACKEND): """ Options: * ``path``: Path to the DB filen...
brunobord/meuhdb
meuhdb/core.py
MeuhDb.update_index
python
def update_index(self, key, value): "Update the index with the new key/values." for k, v in value.items(): if k in self.indexes: # A non-string index value switches it into a lazy one. if not isinstance(v, six.string_types): self.index_defs...
Update the index with the new key/values.
train
https://github.com/brunobord/meuhdb/blob/2ef2ea0b1065768d88f52bacf1b94b3d3ce3d9eb/meuhdb/core.py#L284-L293
null
class MeuhDb(object): """ MeuhDb is a key / JSON value store. """ def __init__(self, path=None, autocommit=False, autocommit_after=None, lazy_indexes=False, backend=DEFAULT_BACKEND): """ Options: * ``path``: Path to the DB filen...
brunobord/meuhdb
meuhdb/core.py
MeuhDb.create_index
python
def create_index(self, name, recreate=False, _type='default'): if name not in self.indexes or recreate: self.build_index(name, _type)
Create an index. If recreate is True, recreate even if already there.
train
https://github.com/brunobord/meuhdb/blob/2ef2ea0b1065768d88f52bacf1b94b3d3ce3d9eb/meuhdb/core.py#L296-L302
null
class MeuhDb(object): """ MeuhDb is a key / JSON value store. """ def __init__(self, path=None, autocommit=False, autocommit_after=None, lazy_indexes=False, backend=DEFAULT_BACKEND): """ Options: * ``path``: Path to the DB filen...
brunobord/meuhdb
meuhdb/core.py
MeuhDb.build_index
python
def build_index(self, idx_name, _type='default'): "Build the index related to the `name`." indexes = {} has_non_string_values = False for key, item in self.data.items(): if idx_name in item: value = item[idx_name] # A non-string index value swi...
Build the index related to the `name`.
train
https://github.com/brunobord/meuhdb/blob/2ef2ea0b1065768d88f52bacf1b94b3d3ce3d9eb/meuhdb/core.py#L305-L322
null
class MeuhDb(object): """ MeuhDb is a key / JSON value store. """ def __init__(self, path=None, autocommit=False, autocommit_after=None, lazy_indexes=False, backend=DEFAULT_BACKEND): """ Options: * ``path``: Path to the DB filen...
brunobord/meuhdb
meuhdb/core.py
MeuhDb._clean_index
python
def _clean_index(self): "Clean index values after loading." for idx_name, idx_def in self.index_defs.items(): if idx_def['type'] == 'lazy': self.build_index(idx_name) for index_name, values in self.indexes.items(): for value in values: if n...
Clean index values after loading.
train
https://github.com/brunobord/meuhdb/blob/2ef2ea0b1065768d88f52bacf1b94b3d3ce3d9eb/meuhdb/core.py#L330-L338
null
class MeuhDb(object): """ MeuhDb is a key / JSON value store. """ def __init__(self, path=None, autocommit=False, autocommit_after=None, lazy_indexes=False, backend=DEFAULT_BACKEND): """ Options: * ``path``: Path to the DB filen...
pasztorpisti/json-cfg
src/jsoncfg/tree_python.py
default_number_converter
python
def default_number_converter(number_str): is_int = (number_str.startswith('-') and number_str[1:].isdigit()) or number_str.isdigit() # FIXME: this handles a wider range of numbers than allowed by the json standard, # etc.: float('nan') and float('inf'). But is this a problem? return int(number_str) if i...
Converts the string representation of a json number into its python object equivalent, an int, long, float or whatever type suits.
train
https://github.com/pasztorpisti/json-cfg/blob/4627b14a92521ef8a39bbedaa7af8d380d406d07/src/jsoncfg/tree_python.py#L61-L69
null
""" Contains factories to be used with the ObjectBuilderParserListener in order to build a json tree that consists of pure python objects. With these factories we can load json string into python object hierarchies just like the python standard json.loads() but our parser allows an extended syntax (unquoted keys, comme...
pasztorpisti/json-cfg
src/jsoncfg/text_encoding.py
load_utf_text_file
python
def load_utf_text_file(file_, default_encoding='UTF-8', use_utf8_strings=True): if isinstance(file_, my_basestring): with open(file_, 'rb') as f: buf = f.read() else: buf = file_.read() return decode_utf_text_buffer(buf, default_encoding, use_utf8_strings)
Loads the specified text file and tries to decode it using one of the UTF encodings. :param file_: The path to the loadable text file or a file-like object with a read() method. :param default_encoding: The encoding to be used if the file doesn't have a BOM prefix. :param use_utf8_strings: Ignored in case o...
train
https://github.com/pasztorpisti/json-cfg/blob/4627b14a92521ef8a39bbedaa7af8d380d406d07/src/jsoncfg/text_encoding.py#L4-L20
[ "def decode_utf_text_buffer(buf, default_encoding='UTF-8', use_utf8_strings=True):\n \"\"\"\n :param buf: Binary file contents with optional BOM prefix.\n :param default_encoding: The encoding to be used if the buffer\n doesn't have a BOM prefix.\n :param use_utf8_strings: Used only in case of python...
from .compatibility import python2, my_basestring def decode_utf_text_buffer(buf, default_encoding='UTF-8', use_utf8_strings=True): """ :param buf: Binary file contents with optional BOM prefix. :param default_encoding: The encoding to be used if the buffer doesn't have a BOM prefix. :param use_u...
pasztorpisti/json-cfg
src/jsoncfg/text_encoding.py
decode_utf_text_buffer
python
def decode_utf_text_buffer(buf, default_encoding='UTF-8', use_utf8_strings=True): buf, encoding = detect_encoding_and_remove_bom(buf, default_encoding) if python2 and use_utf8_strings: if are_encoding_names_equivalent(encoding, 'UTF-8'): return buf return buf.decode(encoding).encode(...
:param buf: Binary file contents with optional BOM prefix. :param default_encoding: The encoding to be used if the buffer doesn't have a BOM prefix. :param use_utf8_strings: Used only in case of python2: You can choose utf-8 str in-memory string representation in case of python. If use_utf8_strings is ...
train
https://github.com/pasztorpisti/json-cfg/blob/4627b14a92521ef8a39bbedaa7af8d380d406d07/src/jsoncfg/text_encoding.py#L23-L40
[ "def detect_encoding_and_remove_bom(buf, default_encoding='UTF-8'):\n \"\"\"\n :param buf: Binary file contents with an optional BOM prefix.\n :param default_encoding: The encoding to be used if the buffer\n doesn't have a BOM prefix.\n :return: (buf_without_bom_prefix, encoding)\n \"\"\"\n if ...
from .compatibility import python2, my_basestring def load_utf_text_file(file_, default_encoding='UTF-8', use_utf8_strings=True): """ Loads the specified text file and tries to decode it using one of the UTF encodings. :param file_: The path to the loadable text file or a file-like object with a read() me...
pasztorpisti/json-cfg
src/jsoncfg/text_encoding.py
detect_encoding_and_remove_bom
python
def detect_encoding_and_remove_bom(buf, default_encoding='UTF-8'): if not isinstance(buf, bytes): raise TypeError('buf should be a bytes instance but it is a %s: ' % type(buf).__name__) for bom, encoding in _byte_order_marks: if buf.startswith(bom): return buf[len(bom):], encoding ...
:param buf: Binary file contents with an optional BOM prefix. :param default_encoding: The encoding to be used if the buffer doesn't have a BOM prefix. :return: (buf_without_bom_prefix, encoding)
train
https://github.com/pasztorpisti/json-cfg/blob/4627b14a92521ef8a39bbedaa7af8d380d406d07/src/jsoncfg/text_encoding.py#L49-L61
null
from .compatibility import python2, my_basestring def load_utf_text_file(file_, default_encoding='UTF-8', use_utf8_strings=True): """ Loads the specified text file and tries to decode it using one of the UTF encodings. :param file_: The path to the loadable text file or a file-like object with a read() me...
pasztorpisti/json-cfg
src/jsoncfg/config_classes.py
_process_value_fetcher_call_args
python
def _process_value_fetcher_call_args(args): if not args: return _undefined, () if isinstance(args[0], JSONValueMapper): default = _undefined mappers = args else: default = args[0] mappers = args[1:] for mapper in mappers: if not isinstance(mapper, JSONVa...
This function processes the incoming varargs of ValueNotFoundNode.__call__() and _ConfigNode.__call__(). :param args: A list or tuple containing positional function call arguments. The optional arguments we expect are the following: An optional default value followed by zero or more JSONValueMapper inst...
train
https://github.com/pasztorpisti/json-cfg/blob/4627b14a92521ef8a39bbedaa7af8d380d406d07/src/jsoncfg/config_classes.py#L110-L135
null
import numbers from collections import OrderedDict, namedtuple from .compatibility import my_basestring from .exceptions import JSONConfigException _undefined = object() class JSONConfigQueryError(JSONConfigException): """ The base class of every exceptions thrown by this library during config queries. ...
pasztorpisti/json-cfg
src/jsoncfg/config_classes.py
node_location
python
def node_location(config_node): if isinstance(config_node, ConfigNode): return _NodeLocation(config_node._line, config_node._column) if isinstance(config_node, ValueNotFoundNode): raise JSONConfigValueNotFoundError(config_node) raise TypeError('Expected a config node but received a %s instan...
Returns the location of this node in the file as a tuple (line, column). Both line and column are 1 based.
train
https://github.com/pasztorpisti/json-cfg/blob/4627b14a92521ef8a39bbedaa7af8d380d406d07/src/jsoncfg/config_classes.py#L375-L383
null
import numbers from collections import OrderedDict, namedtuple from .compatibility import my_basestring from .exceptions import JSONConfigException _undefined = object() class JSONConfigQueryError(JSONConfigException): """ The base class of every exceptions thrown by this library during config queries. ...
pasztorpisti/json-cfg
src/jsoncfg/parser.py
TextParser.column
python
def column(self): for i in my_xrange(self._column_query_pos, self.pos): if self.text[i] == '\t': self._column += self.tab_size self._column -= self._column % self.tab_size else: self._column += 1 self._column_query_pos = self.pos ...
Returns the zero based column number based on the current position of the parser.
train
https://github.com/pasztorpisti/json-cfg/blob/4627b14a92521ef8a39bbedaa7af8d380d406d07/src/jsoncfg/parser.py#L36-L46
null
class TextParser(object): """ A base class for parsers. It handles the position in the parsed text and tracks the current line/column number. """ def __init__(self, tab_size=4): super(TextParser, self).__init__() self.tab_size = tab_size self.text = None self.pos = 0 ...
pasztorpisti/json-cfg
src/jsoncfg/parser.py
TextParser.peek
python
def peek(self, offset=0): pos = self.pos + offset if pos >= self.end: return None return self.text[pos]
Looking forward in the input text without actually stepping the current position. returns None if the current position is at the end of the input.
train
https://github.com/pasztorpisti/json-cfg/blob/4627b14a92521ef8a39bbedaa7af8d380d406d07/src/jsoncfg/parser.py#L90-L96
null
class TextParser(object): """ A base class for parsers. It handles the position in the parsed text and tracks the current line/column number. """ def __init__(self, tab_size=4): super(TextParser, self).__init__() self.tab_size = tab_size self.text = None self.pos = 0 ...
pasztorpisti/json-cfg
src/jsoncfg/parser.py
TextParser.expect
python
def expect(self, c): if self.peek() != c: self.error('Expected "%c"' % (c,)) self.skip_char()
If the current position doesn't hold the specified c character then it raises an exception, otherwise it skips the specified character (moves the current position forward).
train
https://github.com/pasztorpisti/json-cfg/blob/4627b14a92521ef8a39bbedaa7af8d380d406d07/src/jsoncfg/parser.py#L98-L105
[ "def peek(self, offset=0):\n \"\"\" Looking forward in the input text without actually stepping the current position.\n returns None if the current position is at the end of the input. \"\"\"\n pos = self.pos + offset\n if pos >= self.end:\n return None\n return self.text[pos]\n" ]
class TextParser(object): """ A base class for parsers. It handles the position in the parsed text and tracks the current line/column number. """ def __init__(self, tab_size=4): super(TextParser, self).__init__() self.tab_size = tab_size self.text = None self.pos = 0 ...
pasztorpisti/json-cfg
src/jsoncfg/parser.py
JSONParser.parse
python
def parse(self, json_text, listener): listener.begin_parsing(self) try: self.init_text_parser(json_text) self.listener = listener c = self._skip_spaces_and_peek() if c == '{': if self.params.root_is_array: self.error('T...
Parses the specified json_text and emits parser events to the listener. If root_is_array then the root element of the json has to be an array/list, otherwise the expected root is a json object/dict. In case of python2 the json_text can be either an utf8 encoded string or a unicode objec...
train
https://github.com/pasztorpisti/json-cfg/blob/4627b14a92521ef8a39bbedaa7af8d380d406d07/src/jsoncfg/parser.py#L147-L177
[ "def init_text_parser(self, text):\n assert self.text is None\n self.text = text\n self.end = len(text)\n", "def error(self, message):\n \"\"\" Raises an exception with the given message and with the current position of\n the parser in the parsed json string. \"\"\"\n raise JSONConfigParserExcep...
class JSONParser(TextParser): """ A simple json parser that works with a fixed sized input buffer (without input streaming) but this should not be a problem in case of config files that usually have a small limited size. This parser emits events similarly to a SAX XML parser. The user of this class can ...
pasztorpisti/json-cfg
src/jsoncfg/parser.py
JSONParser._skip_spaces_and_peek
python
def _skip_spaces_and_peek(self): while 1: # skipping spaces self.skip_chars(self.end, lambda x: x in self.spaces) c = self.peek() if not self.params.allow_comments: return c if c != '/': return c d = self.pee...
Skips all spaces and comments. :return: The first character that follows the skipped spaces and comments or None if the end of the json string has been reached.
train
https://github.com/pasztorpisti/json-cfg/blob/4627b14a92521ef8a39bbedaa7af8d380d406d07/src/jsoncfg/parser.py#L179-L200
[ "def skip_chars(self, target_pos, is_char_skippable_func):\n assert self.pos <= target_pos <= self.end\n target_pos = min(target_pos, self.end)\n for self.pos in my_xrange(self.pos, target_pos):\n c = self.text[self.pos]\n if not is_char_skippable_func(c):\n break\n if c in ...
class JSONParser(TextParser): """ A simple json parser that works with a fixed sized input buffer (without input streaming) but this should not be a problem in case of config files that usually have a small limited size. This parser emits events similarly to a SAX XML parser. The user of this class can ...
pasztorpisti/json-cfg
src/jsoncfg/parser.py
JSONParser._parse_and_return_unquoted_string
python
def _parse_and_return_unquoted_string(self): begin = self.pos for end in my_xrange(self.pos, self.end): if self.text[end] in self.spaces_and_special_chars: break else: end = self.end if begin == end: self.error('Expected a scalar here.'...
Parses a string that has no quotation marks so it doesn't contain any special characters and we don't have to interpret any escape sequences. :return: (string, quoted=False, end_of_string_pos)
train
https://github.com/pasztorpisti/json-cfg/blob/4627b14a92521ef8a39bbedaa7af8d380d406d07/src/jsoncfg/parser.py#L307-L322
null
class JSONParser(TextParser): """ A simple json parser that works with a fixed sized input buffer (without input streaming) but this should not be a problem in case of config files that usually have a small limited size. This parser emits events similarly to a SAX XML parser. The user of this class can ...
pasztorpisti/json-cfg
src/jsoncfg/parser.py
JSONParser._parse_and_return_quoted_string
python
def _parse_and_return_quoted_string(self): result = [] pos = self.pos + 1 segment_begin = pos my_chr = my_unichr if isinstance(self.text, my_unicode) else utf8chr while pos < self.end: c = self.text[pos] if c < ' ' and c != '\t': self.skip_...
Parses a string that has quotation marks so it may contain special characters and escape sequences. :return: (unescaped_string, quoted=True, end_of_string_pos)
train
https://github.com/pasztorpisti/json-cfg/blob/4627b14a92521ef8a39bbedaa7af8d380d406d07/src/jsoncfg/parser.py#L324-L360
null
class JSONParser(TextParser): """ A simple json parser that works with a fixed sized input buffer (without input streaming) but this should not be a problem in case of config files that usually have a small limited size. This parser emits events similarly to a SAX XML parser. The user of this class can ...
pasztorpisti/json-cfg
src/jsoncfg/functions.py
loads
python
def loads(s, parser_params=JSONParserParams(), object_builder_params=PythonObjectBuilderParams()): parser = JSONParser(parser_params) listener = ObjectBuilderParserListener(object_builder_params) parser.parse(s, listener) return listener.result
Loads a json string as a python object hierarchy just like the standard json.loads(). Unlike the standard json.loads() this function uses OrderedDict instances to represent json objects but the class of the dictionary to be used is configurable. :param s: The json string to load. :params parser_params: ...
train
https://github.com/pasztorpisti/json-cfg/blob/4627b14a92521ef8a39bbedaa7af8d380d406d07/src/jsoncfg/functions.py#L11-L27
[ "def parse(self, json_text, listener):\n \"\"\"\n Parses the specified json_text and emits parser events to the listener.\n If root_is_array then the root element of the json has to be an array/list,\n otherwise the expected root is a json object/dict.\n\n In case of python2 the json_text can be eith...
""" Contains the load functions that we use as the public interface of this whole library. """ from .parser import JSONParserParams, JSONParser from .parser_listener import ObjectBuilderParserListener from .tree_python import PythonObjectBuilderParams, DefaultStringToScalarConverter from .tree_config import ConfigObjec...
pasztorpisti/json-cfg
src/jsoncfg/functions.py
loads_config
python
def loads_config(s, parser_params=JSONParserParams(), string_to_scalar_converter=DefaultStringToScalarConverter()): parser = JSONParser(parser_params) object_builder_params = ConfigObjectBuilderParams(string_to_scalar_converter=string_to_scalar_converter) listener = ObjectB...
Works similar to the loads() function but this one returns a json object hierarchy that wraps all json objects, arrays and scalars to provide a nice config query syntax. For example: my_config = loads_config(json_string) ip_address = my_config.servers.reverse_proxy.ip_address() port = my_config.serv...
train
https://github.com/pasztorpisti/json-cfg/blob/4627b14a92521ef8a39bbedaa7af8d380d406d07/src/jsoncfg/functions.py#L30-L57
[ "def parse(self, json_text, listener):\n \"\"\"\n Parses the specified json_text and emits parser events to the listener.\n If root_is_array then the root element of the json has to be an array/list,\n otherwise the expected root is a json object/dict.\n\n In case of python2 the json_text can be eith...
""" Contains the load functions that we use as the public interface of this whole library. """ from .parser import JSONParserParams, JSONParser from .parser_listener import ObjectBuilderParserListener from .tree_python import PythonObjectBuilderParams, DefaultStringToScalarConverter from .tree_config import ConfigObjec...
pasztorpisti/json-cfg
src/jsoncfg/functions.py
load
python
def load(file_, *args, **kwargs): json_str = load_utf_text_file( file_, default_encoding=kwargs.pop('default_encoding', 'UTF-8'), use_utf8_strings=kwargs.pop('use_utf8_strings', True), ) return loads(json_str, *args, **kwargs)
Does exactly the same as loads() but instead of a json string this function receives the path to a file containing the json string or a file like object with a read() method. :param file_: Filename or a file like object with read() method. :param default_encoding: The encoding to be used if the file doe...
train
https://github.com/pasztorpisti/json-cfg/blob/4627b14a92521ef8a39bbedaa7af8d380d406d07/src/jsoncfg/functions.py#L60-L77
[ "def loads(s,\n parser_params=JSONParserParams(),\n object_builder_params=PythonObjectBuilderParams()):\n \"\"\"\n Loads a json string as a python object hierarchy just like the standard json.loads(). Unlike\n the standard json.loads() this function uses OrderedDict instances to represent...
""" Contains the load functions that we use as the public interface of this whole library. """ from .parser import JSONParserParams, JSONParser from .parser_listener import ObjectBuilderParserListener from .tree_python import PythonObjectBuilderParams, DefaultStringToScalarConverter from .tree_config import ConfigObjec...
pasztorpisti/json-cfg
src/jsoncfg/functions.py
load_config
python
def load_config(file_, *args, **kwargs): json_str = load_utf_text_file( file_, default_encoding=kwargs.pop('default_encoding', 'UTF-8'), use_utf8_strings=kwargs.pop('use_utf8_strings', True), ) return loads_config(json_str, *args, **kwargs)
Does exactly the same as loads_config() but instead of a json string this function receives the path to a file containing the json string or a file like object with a read() method. :param file_: Filename or a file like object with read() method. :param default_encoding: The encoding to be used if the f...
train
https://github.com/pasztorpisti/json-cfg/blob/4627b14a92521ef8a39bbedaa7af8d380d406d07/src/jsoncfg/functions.py#L80-L97
[ "def loads_config(s,\n parser_params=JSONParserParams(),\n string_to_scalar_converter=DefaultStringToScalarConverter()):\n \"\"\"\n Works similar to the loads() function but this one returns a json object hierarchy\n that wraps all json objects, arrays and scalars to provide...
""" Contains the load functions that we use as the public interface of this whole library. """ from .parser import JSONParserParams, JSONParser from .parser_listener import ObjectBuilderParserListener from .tree_python import PythonObjectBuilderParams, DefaultStringToScalarConverter from .tree_config import ConfigObjec...
Rediker-Software/doac
doac/handlers/bearer.py
BearerHandler.access_token
python
def access_token(self, value, request): if self.validate(value, request) is not None: return None access_token = AccessToken.objects.for_token(value) return access_token
Try to get the `AccessToken` associated with the provided token. *The provided value must pass `BearerHandler.validate()`*
train
https://github.com/Rediker-Software/doac/blob/398fdd64452e4ff8662297b0381926addd77505a/doac/handlers/bearer.py#L9-L21
[ "def validate(self, value, request):\n \"\"\"\n Try to get the `AccessToken` associated with the given token.\n\n The return value is determined based n a few things:\n\n - If no token is provided (`value` is None), a 400 response will be returned.\n - If an invalid token is provided, a 401 response...
class BearerHandler: def access_token(self, value, request): """ Try to get the `AccessToken` associated with the provided token. *The provided value must pass `BearerHandler.validate()`* """ if self.validate(value, request) is not None: return None ac...
Rediker-Software/doac
doac/handlers/bearer.py
BearerHandler.validate
python
def validate(self, value, request): from django.http import HttpResponseBadRequest from doac.http import HttpResponseUnauthorized if not value: response = HttpResponseBadRequest() response["WWW-Authenticate"] = request_error_header(CredentialsNotProvided) ...
Try to get the `AccessToken` associated with the given token. The return value is determined based n a few things: - If no token is provided (`value` is None), a 400 response will be returned. - If an invalid token is provided, a 401 response will be returned. - If the token provided ...
train
https://github.com/Rediker-Software/doac/blob/398fdd64452e4ff8662297b0381926addd77505a/doac/handlers/bearer.py#L37-L65
[ "def request_error_header(exception):\n \"\"\"\n Generates the error header for a request using a Bearer token based on a given OAuth exception.\n \"\"\"\n\n from .conf import options\n\n header = \"Bearer realm=\\\"%s\\\"\" % (options.realm, )\n\n if hasattr(exception, \"error\"):\n header...
class BearerHandler: def access_token(self, value, request): """ Try to get the `AccessToken` associated with the provided token. *The provided value must pass `BearerHandler.validate()`* """ if self.validate(value, request) is not None: return None ac...
Rediker-Software/doac
doac/utils.py
prune_old_authorization_codes
python
def prune_old_authorization_codes(): from .compat import now from .models import AuthorizationCode AuthorizationCode.objects.with_expiration_before(now()).delete()
Removes all unused and expired authorization codes from the database.
train
https://github.com/Rediker-Software/doac/blob/398fdd64452e4ff8662297b0381926addd77505a/doac/utils.py#L1-L9
null
def prune_old_authorization_codes(): """ Removes all unused and expired authorization codes from the database. """ from .compat import now from .models import AuthorizationCode AuthorizationCode.objects.with_expiration_before(now()).delete() def get_handler(handler_name): """ Imports...
Rediker-Software/doac
doac/utils.py
get_handler
python
def get_handler(handler_name): from .conf import options handlers = options.handlers for handler in handlers: handler_path = handler.split(".") name = handler_path[-2] if handler_name == name: handler_module = __import__(".".join(handler_path[:-1]), {}...
Imports the module for a DOAC handler based on the string representation of the module path that is provided.
train
https://github.com/Rediker-Software/doac/blob/398fdd64452e4ff8662297b0381926addd77505a/doac/utils.py#L12-L30
null
def prune_old_authorization_codes(): """ Removes all unused and expired authorization codes from the database. """ from .compat import now from .models import AuthorizationCode AuthorizationCode.objects.with_expiration_before(now()).delete() def get_handler(handler_name): """ Imports...
Rediker-Software/doac
doac/utils.py
request_error_header
python
def request_error_header(exception): from .conf import options header = "Bearer realm=\"%s\"" % (options.realm, ) if hasattr(exception, "error"): header = header + ", error=\"%s\"" % (exception.error, ) if hasattr(exception, "reason"): header = header + ", error_descripti...
Generates the error header for a request using a Bearer token based on a given OAuth exception.
train
https://github.com/Rediker-Software/doac/blob/398fdd64452e4ff8662297b0381926addd77505a/doac/utils.py#L33-L48
null
def prune_old_authorization_codes(): """ Removes all unused and expired authorization codes from the database. """ from .compat import now from .models import AuthorizationCode AuthorizationCode.objects.with_expiration_before(now()).delete() def get_handler(handler_name): """ Imports...
Rediker-Software/doac
doac/models.py
AuthorizationToken.revoke_tokens
python
def revoke_tokens(self): self.is_active = False self.save() self.refresh_token.revoke_tokens()
Revoke the authorization token and all tokens that were generated using it.
train
https://github.com/Rediker-Software/doac/blob/398fdd64452e4ff8662297b0381926addd77505a/doac/models.py#L145-L153
[ "def save(self, *args, **kwargs):\n from .compat import now\n\n if not self.token:\n self.token = self.generate_token()\n\n if not self.expires_at:\n self.expires_at = now() + options.auth_token[\"expires\"]\n\n super(AuthorizationToken, self).save(*args, **kwargs)\n" ]
class AuthorizationToken(models.Model): user = models.ForeignKey(user_model, related_name="authorization_tokens") client = models.ForeignKey("Client", related_name="authorization_tokens") token = models.CharField( max_length=options.auth_token["length"], blank=True, help_text=AUTO_GE...
Rediker-Software/doac
doac/models.py
RefreshToken.revoke_tokens
python
def revoke_tokens(self): self.is_active = False self.save() for access_token in self.access_tokens.all(): access_token.revoke()
Revokes the refresh token and all access tokens that were generated using it.
train
https://github.com/Rediker-Software/doac/blob/398fdd64452e4ff8662297b0381926addd77505a/doac/models.py#L242-L251
[ "def save(self, *args, **kwargs):\n from .compat import now\n\n if not self.token:\n self.token = self.generate_token()\n\n if not self.expires_at:\n self.expires_at = now() + options.refresh_token[\"expires\"]\n\n super(RefreshToken, self).save(*args, **kwargs)\n" ]
class RefreshToken(models.Model): user = models.ForeignKey(user_model, related_name="refresh_tokens") client = models.ForeignKey("Client", related_name="refresh_tokens") authorization_token = models.OneToOneField("AuthorizationToken", related_name="refresh_token") token = models.CharField( max_...
Rediker-Software/doac
doac/middleware.py
AuthenticationMiddleware.process_request
python
def process_request(self, request): request.auth_type = None http_authorization = request.META.get("HTTP_AUTHORIZATION", None) if not http_authorization: return auth = http_authorization.split() self.auth_type = auth[0].lower() ...
Try to authenticate the user based on any given tokens that have been provided to the request object. This will try to detect the authentication type and assign the detected User object to the `request.user` variable, similar to the standard Django authentication.
train
https://github.com/Rediker-Software/doac/blob/398fdd64452e4ff8662297b0381926addd77505a/doac/middleware.py#L8-L43
[ "def load_handler(self):\n \"\"\"\n Load the detected handler.\n \"\"\"\n\n handler_path = self.handler_name.split(\".\")\n\n handler_module = __import__(\".\".join(handler_path[:-1]), {}, {}, str(handler_path[-1]))\n self.handler = getattr(handler_module, handler_path[-1])()\n", "def validate_a...
class AuthenticationMiddleware: def process_request(self, request): """ Try to authenticate the user based on any given tokens that have been provided to the request object. This will try to detect the authentication type and assign the detected User object to the `request.user` va...
Rediker-Software/doac
doac/middleware.py
AuthenticationMiddleware.load_handler
python
def load_handler(self): handler_path = self.handler_name.split(".") handler_module = __import__(".".join(handler_path[:-1]), {}, {}, str(handler_path[-1])) self.handler = getattr(handler_module, handler_path[-1])()
Load the detected handler.
train
https://github.com/Rediker-Software/doac/blob/398fdd64452e4ff8662297b0381926addd77505a/doac/middleware.py#L45-L53
null
class AuthenticationMiddleware: def process_request(self, request): """ Try to authenticate the user based on any given tokens that have been provided to the request object. This will try to detect the authentication type and assign the detected User object to the `request.user` va...
Rediker-Software/doac
doac/middleware.py
AuthenticationMiddleware.validate_auth_type
python
def validate_auth_type(self): for handler in HANDLERS: handler_type = handler.split(".")[-2] if handler_type == self.auth_type: self.handler_name = handler return self.handler_name = None
Validate the detected authorization type against the list of handlers. This will return the full module path to the detected handler.
train
https://github.com/Rediker-Software/doac/blob/398fdd64452e4ff8662297b0381926addd77505a/doac/middleware.py#L55-L69
null
class AuthenticationMiddleware: def process_request(self, request): """ Try to authenticate the user based on any given tokens that have been provided to the request object. This will try to detect the authentication type and assign the detected User object to the `request.user` va...
Rediker-Software/doac
doac/contrib/rest_framework/authentication.py
DoacAuthentication.authenticate
python
def authenticate(self, request): from doac.middleware import AuthenticationMiddleware try: response = AuthenticationMiddleware().process_request(request) except: raise exceptions.AuthenticationFailed("Invalid handler") if not hasattr(request, "user") or not req...
Send the request through the authentication middleware that is provided with DOAC and grab the user and token from it.
train
https://github.com/Rediker-Software/doac/blob/398fdd64452e4ff8662297b0381926addd77505a/doac/contrib/rest_framework/authentication.py#L6-L25
[ "def process_request(self, request):\n \"\"\"\n Try to authenticate the user based on any given tokens that have been provided\n to the request object. This will try to detect the authentication type and assign\n the detected User object to the `request.user` variable, similar to the standard\n Djan...
class DoacAuthentication(authentication.BaseAuthentication): def authenticate_header(self, request): """ DOAC specifies the realm as Bearer by default. """ from doac.conf import options return 'Bearer realm="%s"' % options.realm
Rediker-Software/doac
doac/decorators.py
scope_required
python
def scope_required(*scopes): def decorator(view_func): @wraps(view_func, assigned=available_attrs(view_func)) def _wrapped_view(request, *args, **kwargs): from django.http import HttpResponseBadRequest, HttpResponseForbidden from .exceptions.base import InvalidReque...
Test for specific scopes that the access token has been authenticated for before processing the request and eventual response. The scopes that are passed in determine how the decorator will respond to incoming requests: - If no scopes are passed in the arguments, the decorator will test for any availa...
train
https://github.com/Rediker-Software/doac/blob/398fdd64452e4ff8662297b0381926addd77505a/doac/decorators.py#L7-L77
[ "def decorator(view_func):\n\n @wraps(view_func, assigned=available_attrs(view_func))\n def _wrapped_view(request, *args, **kwargs):\n from django.http import HttpResponseBadRequest, HttpResponseForbidden\n from .exceptions.base import InvalidRequest, InsufficientScope\n from .models impo...
from django.utils.decorators import available_attrs from functools import wraps from .exceptions.invalid_request import CredentialsNotProvided from .exceptions.insufficient_scope import ScopeNotEnough def scope_required(*scopes): """ Test for specific scopes that the access token has been authenticated for be...
Rediker-Software/doac
doac/views.py
OAuthView.handle_exception
python
def handle_exception(self, exception): can_redirect = getattr(exception, "can_redirect", True) redirect_uri = getattr(self, "redirect_uri", None) if can_redirect and redirect_uri: return self.redirect_exception(exception) else: return self.render_exception(excep...
Handle a unspecified exception and return the correct method that should be used for handling it. If the exception has the `can_redirect` property set to False, it is rendered to the browser. Otherwise, it will be redirected to the location provided in the `RedirectUri` object that is ...
train
https://github.com/Rediker-Software/doac/blob/398fdd64452e4ff8662297b0381926addd77505a/doac/views.py#L22-L38
null
class OAuthView(View): """ All views must subclass this class. This provides common methods which are needed for validation and processing OAuth requests and responses. """ def redirect_exception(self, exception): """ Build the query string for the exception and return a redir...
Rediker-Software/doac
doac/views.py
OAuthView.redirect_exception
python
def redirect_exception(self, exception): from django.http import QueryDict, HttpResponseRedirect query = QueryDict("").copy() query["error"] = exception.error query["error_description"] = exception.reason query["state"] = self.state return HttpResponseRedirect(self.red...
Build the query string for the exception and return a redirect to the redirect uri that was associated with the request.
train
https://github.com/Rediker-Software/doac/blob/398fdd64452e4ff8662297b0381926addd77505a/doac/views.py#L40-L53
null
class OAuthView(View): """ All views must subclass this class. This provides common methods which are needed for validation and processing OAuth requests and responses. """ def handle_exception(self, exception): """ Handle a unspecified exception and return the correct method t...
Rediker-Software/doac
doac/views.py
OAuthView.render_exception_js
python
def render_exception_js(self, exception): from .http import JsonResponse response = {} response["error"] = exception.error response["error_description"] = exception.reason return JsonResponse(response, status=getattr(exception, 'code', 400))
Return a response with the body containing a JSON-formatter version of the exception.
train
https://github.com/Rediker-Software/doac/blob/398fdd64452e4ff8662297b0381926addd77505a/doac/views.py#L64-L75
null
class OAuthView(View): """ All views must subclass this class. This provides common methods which are needed for validation and processing OAuth requests and responses. """ def handle_exception(self, exception): """ Handle a unspecified exception and return the correct method t...
Rediker-Software/doac
doac/views.py
OAuthView.verify_dictionary
python
def verify_dictionary(self, dict, *args): for arg in args: setattr(self, arg, dict.get(arg, None)) if hasattr(self, "verify_" + arg): func = getattr(self, "verify_" + arg) func()
Based on a provided `dict`, validate all of the contents of that dictionary that are provided. For each argument provided that isn't the dictionary, this will set the raw value of that key as the instance variable of the same name. It will then call the verification function named `ver...
train
https://github.com/Rediker-Software/doac/blob/398fdd64452e4ff8662297b0381926addd77505a/doac/views.py#L77-L92
null
class OAuthView(View): """ All views must subclass this class. This provides common methods which are needed for validation and processing OAuth requests and responses. """ def handle_exception(self, exception): """ Handle a unspecified exception and return the correct method t...
Rediker-Software/doac
doac/views.py
OAuthView.verify_client_id
python
def verify_client_id(self): from .models import Client from .exceptions.invalid_client import ClientDoesNotExist from .exceptions.invalid_request import ClientNotProvided if self.client_id: try: self.client = Client.objects.for_id(self.client_id) ...
Verify a provided client id against the database and set the `Client` object that is associated with it to `self.client`. TODO: Document all of the thrown exceptions.
train
https://github.com/Rediker-Software/doac/blob/398fdd64452e4ff8662297b0381926addd77505a/doac/views.py#L94-L113
null
class OAuthView(View): """ All views must subclass this class. This provides common methods which are needed for validation and processing OAuth requests and responses. """ def handle_exception(self, exception): """ Handle a unspecified exception and return the correct method t...
raphaelgyory/django-rest-messaging
rest_messaging/compat.py
compat_serializer_check_is_valid
python
def compat_serializer_check_is_valid(serializer): if DRFVLIST[0] >= 3: serializer.is_valid(raise_exception=True) else: if not serializer.is_valid(): serializers.ValidationError('The serializer raises a validation error')
http://www.django-rest-framework.org/topics/3.0-announcement/#using-is_validraise_exceptiontrue
train
https://github.com/raphaelgyory/django-rest-messaging/blob/c9d5405fed7db2d79ec5c93c721a8fe42ea86958/rest_messaging/compat.py#L23-L29
null
# coding=utf8 # -*- coding: utf8 -*- # vim: set fileencoding=utf8 : from __future__ import unicode_literals from django.conf import settings from rest_framework import VERSION, serializers from rest_framework.response import Response from rest_messaging.pagination import MessagePagination DRFVLIST = [int(x) for x in...
raphaelgyory/django-rest-messaging
rest_messaging/compat.py
compat_serializer_attr
python
def compat_serializer_attr(serializer, obj): if DRFVLIST[0] == 3 and DRFVLIST[1] == 1: for i in serializer.instance: if i.id == obj.id: return i else: return obj
Required only for DRF 3.1, which does not make dynamically added attribute available in obj in serializer. This is a quick solution but works without breajing anything.
train
https://github.com/raphaelgyory/django-rest-messaging/blob/c9d5405fed7db2d79ec5c93c721a8fe42ea86958/rest_messaging/compat.py#L40-L50
null
# coding=utf8 # -*- coding: utf8 -*- # vim: set fileencoding=utf8 : from __future__ import unicode_literals from django.conf import settings from rest_framework import VERSION, serializers from rest_framework.response import Response from rest_messaging.pagination import MessagePagination DRFVLIST = [int(x) for x in...
raphaelgyory/django-rest-messaging
rest_messaging/compat.py
compat_get_paginated_response
python
def compat_get_paginated_response(view, page): if DRFVLIST[0] == 3 and DRFVLIST[1] >= 1: from rest_messaging.serializers import ComplexMessageSerializer # circular import serializer = ComplexMessageSerializer(page, many=True) return view.get_paginated_response(serializer.data) else: ...
get_paginated_response is unknown to DRF 3.0
train
https://github.com/raphaelgyory/django-rest-messaging/blob/c9d5405fed7db2d79ec5c93c721a8fe42ea86958/rest_messaging/compat.py#L67-L75
null
# coding=utf8 # -*- coding: utf8 -*- # vim: set fileencoding=utf8 : from __future__ import unicode_literals from django.conf import settings from rest_framework import VERSION, serializers from rest_framework.response import Response from rest_messaging.pagination import MessagePagination DRFVLIST = [int(x) for x in...
raphaelgyory/django-rest-messaging
rest_messaging/compat.py
compat_pagination_messages
python
def compat_pagination_messages(cls): if DRFVLIST[0] == 3 and DRFVLIST[1] >= 1: setattr(cls, "pagination_class", MessagePagination) return cls else: # DRF 2 pagination setattr(cls, "paginate_by", getattr(settings, "DJANGO_REST_MESSAGING_MESSAGES_PAGE_SIZE", 30)) return cls
For DRF 3.1 and higher, pagination is defined at the paginator level (see http://www.django-rest-framework.org/topics/3.2-announcement/). For DRF 3.0 and lower, it can be handled at the view level.
train
https://github.com/raphaelgyory/django-rest-messaging/blob/c9d5405fed7db2d79ec5c93c721a8fe42ea86958/rest_messaging/compat.py#L78-L89
null
# coding=utf8 # -*- coding: utf8 -*- # vim: set fileencoding=utf8 : from __future__ import unicode_literals from django.conf import settings from rest_framework import VERSION, serializers from rest_framework.response import Response from rest_messaging.pagination import MessagePagination DRFVLIST = [int(x) for x in...
raphaelgyory/django-rest-messaging
rest_messaging/serializers.py
ThreadSerializer.get_participants
python
def get_participants(self, obj): # we set the many to many serialization to False, because we only want it with retrieve requests if self.callback is None: return [participant.id for participant in obj.participants.all()] else: # we do not want user information ...
Allows to define a callback for serializing information about the user.
train
https://github.com/raphaelgyory/django-rest-messaging/blob/c9d5405fed7db2d79ec5c93c721a8fe42ea86958/rest_messaging/serializers.py#L26-L33
null
class ThreadSerializer(serializers.ModelSerializer): participants = compat_serializer_method_field("get_participants") removable_participants_ids = compat_serializer_method_field("get_removable_participants_ids") class Meta: model = Thread fields = ('id', 'name', 'participants', 'removable...
raphaelgyory/django-rest-messaging
rest_messaging/serializers.py
ComplexMessageSerializer.get_is_notification
python
def get_is_notification(self, obj): try: o = compat_serializer_attr(self, obj) return o.is_notification except Exception: return False
We say if the message should trigger a notification
train
https://github.com/raphaelgyory/django-rest-messaging/blob/c9d5405fed7db2d79ec5c93c721a8fe42ea86958/rest_messaging/serializers.py#L57-L63
[ "def compat_serializer_attr(serializer, obj):\n \"\"\"\n Required only for DRF 3.1, which does not make dynamically added attribute available in obj in serializer.\n This is a quick solution but works without breajing anything.\n \"\"\"\n if DRFVLIST[0] == 3 and DRFVLIST[1] == 1:\n for i in se...
class ComplexMessageSerializer(serializers.ModelSerializer): is_notification = compat_serializer_method_field("get_is_notification") readers = compat_serializer_method_field("get_readers") class Meta: model = Message fields = ('id', 'body', 'sender', 'thread', 'sent_at', 'is_notification',...
raphaelgyory/django-rest-messaging
rest_messaging/serializers.py
ComplexMessageSerializer.get_readers
python
def get_readers(self, obj): try: o = compat_serializer_attr(self, obj) return o.readers except Exception: return []
Return the ids of the people who read the message instance.
train
https://github.com/raphaelgyory/django-rest-messaging/blob/c9d5405fed7db2d79ec5c93c721a8fe42ea86958/rest_messaging/serializers.py#L65-L71
[ "def compat_serializer_attr(serializer, obj):\n \"\"\"\n Required only for DRF 3.1, which does not make dynamically added attribute available in obj in serializer.\n This is a quick solution but works without breajing anything.\n \"\"\"\n if DRFVLIST[0] == 3 and DRFVLIST[1] == 1:\n for i in se...
class ComplexMessageSerializer(serializers.ModelSerializer): is_notification = compat_serializer_method_field("get_is_notification") readers = compat_serializer_method_field("get_readers") class Meta: model = Message fields = ('id', 'body', 'sender', 'thread', 'sent_at', 'is_notification',...
raphaelgyory/django-rest-messaging
rest_messaging/models.py
ThreadManager.get_threads_where_participant_is_active
python
def get_threads_where_participant_is_active(self, participant_id): participations = Participation.objects.\ filter(participant__id=participant_id).\ exclude(date_left__lte=now()).\ distinct().\ select_related('thread') return Thread.objects.\ ...
Gets all the threads in which the current participant is involved. The method excludes threads where the participant has left.
train
https://github.com/raphaelgyory/django-rest-messaging/blob/c9d5405fed7db2d79ec5c93c721a8fe42ea86958/rest_messaging/models.py#L34-L44
null
class ThreadManager(models.Manager): def get_threads_for_participant(self, participant_id): """ Gets all the threads in which the current participant is or was involved. The method does not exclude threads where the participant has left. """ return Thread.objects.\ filter(participants__...
raphaelgyory/django-rest-messaging
rest_messaging/models.py
ThreadManager.get_active_threads_involving_all_participants
python
def get_active_threads_involving_all_participants(self, *participant_ids): query = Thread.objects.\ exclude(participation__date_left__lte=now()).\ annotate(count_participants=Count('participants')).\ filter(count_participants=len(participant_ids)) for participant_id...
Gets the threads where the specified participants are active and no one has left.
train
https://github.com/raphaelgyory/django-rest-messaging/blob/c9d5405fed7db2d79ec5c93c721a8fe42ea86958/rest_messaging/models.py#L46-L57
null
class ThreadManager(models.Manager): def get_threads_for_participant(self, participant_id): """ Gets all the threads in which the current participant is or was involved. The method does not exclude threads where the participant has left. """ return Thread.objects.\ filter(participants__...
raphaelgyory/django-rest-messaging
rest_messaging/models.py
ThreadManager.get_or_create_thread
python
def get_or_create_thread(self, request, name=None, *participant_ids): # we get the current participant # or create him if he does not exit participant_ids = list(participant_ids) if request.rest_messaging_participant.id not in participant_ids: participant_ids.append(request...
When a Participant posts a message to other participants without specifying an existing Thread, we must 1. Create a new Thread if they have not yet opened the discussion. 2. If they have already opened the discussion and multiple Threads are not allowed for the same users, we must re...
train
https://github.com/raphaelgyory/django-rest-messaging/blob/c9d5405fed7db2d79ec5c93c721a8fe42ea86958/rest_messaging/models.py#L59-L96
[ "def get_active_threads_involving_all_participants(self, *participant_ids):\n \"\"\" Gets the threads where the specified participants are active and no one has left. \"\"\"\n\n query = Thread.objects.\\\n exclude(participation__date_left__lte=now()).\\\n annotate(count_participants=Count('parti...
class ThreadManager(models.Manager): def get_threads_for_participant(self, participant_id): """ Gets all the threads in which the current participant is or was involved. The method does not exclude threads where the participant has left. """ return Thread.objects.\ filter(participants__...
raphaelgyory/django-rest-messaging
rest_messaging/models.py
MessageManager.return_daily_messages_count
python
def return_daily_messages_count(self, sender): h24 = now() - timedelta(days=1) return Message.objects.filter(sender=sender, sent_at__gte=h24).count()
Returns the number of messages sent in the last 24 hours so we can ensure the user does not exceed his messaging limits
train
https://github.com/raphaelgyory/django-rest-messaging/blob/c9d5405fed7db2d79ec5c93c721a8fe42ea86958/rest_messaging/models.py#L191-L194
null
class MessageManager(models.Manager): def check_who_read(self, messages): """ Check who read each message. """ # we get the corresponding Participation objects for m in messages: readers = [] for p in m.thread.participation_set.all(): if p.date_last_...
raphaelgyory/django-rest-messaging
rest_messaging/models.py
MessageManager.check_who_read
python
def check_who_read(self, messages): # we get the corresponding Participation objects for m in messages: readers = [] for p in m.thread.participation_set.all(): if p.date_last_check is None: pass elif p.date_last_check > m.sent_a...
Check who read each message.
train
https://github.com/raphaelgyory/django-rest-messaging/blob/c9d5405fed7db2d79ec5c93c721a8fe42ea86958/rest_messaging/models.py#L196-L209
null
class MessageManager(models.Manager): def return_daily_messages_count(self, sender): """ Returns the number of messages sent in the last 24 hours so we can ensure the user does not exceed his messaging limits """ h24 = now() - timedelta(days=1) return Message.objects.filter(sender=sender, s...
raphaelgyory/django-rest-messaging
rest_messaging/models.py
MessageManager.check_is_notification
python
def check_is_notification(self, participant_id, messages): try: # we get the last check last_check = NotificationCheck.objects.filter(participant__id=participant_id).latest('id').date_check except Exception: # we have no notification check # all the messag...
Check if each message requires a notification for the specified participant.
train
https://github.com/raphaelgyory/django-rest-messaging/blob/c9d5405fed7db2d79ec5c93c721a8fe42ea86958/rest_messaging/models.py#L211-L228
null
class MessageManager(models.Manager): def return_daily_messages_count(self, sender): """ Returns the number of messages sent in the last 24 hours so we can ensure the user does not exceed his messaging limits """ h24 = now() - timedelta(days=1) return Message.objects.filter(sender=sender, s...
raphaelgyory/django-rest-messaging
rest_messaging/models.py
MessageManager.get_lasts_messages_of_threads
python
def get_lasts_messages_of_threads(self, participant_id, check_who_read=True, check_is_notification=True): # we get the last message for each thread # we must query the messages using two queries because only Postgres supports .order_by('thread', '-sent_at').distinct('thread') threads = Thread.ma...
Returns the last message in each thread
train
https://github.com/raphaelgyory/django-rest-messaging/blob/c9d5405fed7db2d79ec5c93c721a8fe42ea86958/rest_messaging/models.py#L230-L250
[ "def check_who_read(self, messages):\n \"\"\" Check who read each message. \"\"\"\n # we get the corresponding Participation objects\n for m in messages:\n readers = []\n for p in m.thread.participation_set.all():\n if p.date_last_check is None:\n pass\n e...
class MessageManager(models.Manager): def return_daily_messages_count(self, sender): """ Returns the number of messages sent in the last 24 hours so we can ensure the user does not exceed his messaging limits """ h24 = now() - timedelta(days=1) return Message.objects.filter(sender=sender, s...
raphaelgyory/django-rest-messaging
rest_messaging/models.py
MessageManager.get_all_messages_in_thread
python
def get_all_messages_in_thread(self, participant_id, thread_id, check_who_read=True): try: messages = Message.objects.filter(thread__id=thread_id).\ order_by('-id').\ select_related('thread').\ prefetch_related('thread__participation_set', 'thread__par...
Returns all the messages in a thread.
train
https://github.com/raphaelgyory/django-rest-messaging/blob/c9d5405fed7db2d79ec5c93c721a8fe42ea86958/rest_messaging/models.py#L252-L263
[ "def check_who_read(self, messages):\n \"\"\" Check who read each message. \"\"\"\n # we get the corresponding Participation objects\n for m in messages:\n readers = []\n for p in m.thread.participation_set.all():\n if p.date_last_check is None:\n pass\n e...
class MessageManager(models.Manager): def return_daily_messages_count(self, sender): """ Returns the number of messages sent in the last 24 hours so we can ensure the user does not exceed his messaging limits """ h24 = now() - timedelta(days=1) return Message.objects.filter(sender=sender, s...
raphaelgyory/django-rest-messaging
rest_messaging/views.py
ThreadView.create
python
def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=compat_get_request_data(request)) compat_serializer_check_is_valid(serializer) self.perform_create(request, serializer) headers = self.get_success_headers(serializer.data) return Response(serializer...
We ensure the Thread only involves eligible participants.
train
https://github.com/raphaelgyory/django-rest-messaging/blob/c9d5405fed7db2d79ec5c93c721a8fe42ea86958/rest_messaging/views.py#L36-L42
[ "def compat_serializer_check_is_valid(serializer):\n \"\"\" http://www.django-rest-framework.org/topics/3.0-announcement/#using-is_validraise_exceptiontrue \"\"\"\n if DRFVLIST[0] >= 3:\n serializer.is_valid(raise_exception=True)\n else:\n if not serializer.is_valid():\n serializer...
class ThreadView(mixins.RetrieveModelMixin, mixins.CreateModelMixin, mixins.UpdateModelMixin, viewsets.GenericViewSet): """ The ThreadView allow us to create threads, and add/remove people to/from them. It does not list the messages belonging to the thread....
raphaelgyory/django-rest-messaging
rest_messaging/views.py
ThreadView.mark_thread_as_read
python
def mark_thread_as_read(self, request, pk=None): # we get the thread and check for permission thread = Thread.objects.get(id=pk) self.check_object_permissions(request, thread) # we save the date try: participation = Participation.objects.get(thread=thread, participant...
Pk is the pk of the Thread to which the messages belong.
train
https://github.com/raphaelgyory/django-rest-messaging/blob/c9d5405fed7db2d79ec5c93c721a8fe42ea86958/rest_messaging/views.py#L107-L121
null
class ThreadView(mixins.RetrieveModelMixin, mixins.CreateModelMixin, mixins.UpdateModelMixin, viewsets.GenericViewSet): """ The ThreadView allow us to create threads, and add/remove people to/from them. It does not list the messages belonging to the thread....
amcat/amcatclient
amcatclient/amcatclient.py
serialize
python
def serialize(obj): from datetime import datetime, date, time if isinstance(obj, date) and not isinstance(obj, datetime): obj = datetime.combine(obj, time.min) if isinstance(obj, datetime): return obj.isoformat()
JSON serializer that accepts datetime & date
train
https://github.com/amcat/amcatclient/blob/bda525f7ace0c26a09fa56d2baf7550f639e62ee/amcatclient/amcatclient.py#L48-L54
null
########################################################################### # (C) Vrije Universiteit, Amsterdam (the Netherlands) # # # # This file is part of AmCAT - The Amsterdam Content Analysis Toolkit # # ...
amcat/amcatclient
amcatclient/amcatclient.py
check
python
def check(response, expected_status=200, url=None): if response.status_code != expected_status: if url is None: url = response.url try: err = response.json() except: err = {} # force generic error if all(x in err for x in ("status", "message", "d...
Check whether the status code of the response equals expected_status and raise an APIError otherwise. @param url: The url of the response (for error messages). Defaults to response.url @param json: if True, return r.json(), otherwise return r.text
train
https://github.com/amcat/amcatclient/blob/bda525f7ace0c26a09fa56d2baf7550f639e62ee/amcatclient/amcatclient.py#L94-L132
[ "def _APIError(http_status, *args, **kargs):\n cls = Unauthorized if http_status == 401 else APIError\n return cls(http_status, *args, **kargs)\n" ]
########################################################################### # (C) Vrije Universiteit, Amsterdam (the Netherlands) # # # # This file is part of AmCAT - The Amsterdam Content Analysis Toolkit # # ...
amcat/amcatclient
amcatclient/amcatclient.py
AmcatAPI._get_auth
python
def _get_auth(self, user=None, password=None): fn = os.path.expanduser(AUTH_FILE) if os.path.exists(fn): for i, line in enumerate(csv.reader(open(fn))): if len(line) != 3: log.warning("Cannot parse line {i} in {fn}".format(**locals())) ...
Get the authentication info for the current user, from 1) a ~/.amcatauth file, which should be a csv file containing host, username, password entries 2) the AMCAT_USER (or USER) and AMCAT_PASSWORD environment variables
train
https://github.com/amcat/amcatclient/blob/bda525f7ace0c26a09fa56d2baf7550f639e62ee/amcatclient/amcatclient.py#L170-L195
null
class AmcatAPI(object): def __init__(self, host, user=None, password=None, token=None): """ Connection to an AmCAT server. :param host: AmCAT server address, including http(s):// :param user: Username. If not given, taken from AMCAT_USER or USER environment :param password:...
amcat/amcatclient
amcatclient/amcatclient.py
AmcatAPI.request
python
def request(self, url, method="get", format="json", data=None, expected_status=None, headers=None, use_xpost=True, **options): if expected_status is None: if method == "get": expected_status = 200 elif method == "post": expected_status = 20...
Make an HTTP request to the given relative URL with the host, user, and password information. Returns the deserialized json if successful, and raises an exception otherwise
train
https://github.com/amcat/amcatclient/blob/bda525f7ace0c26a09fa56d2baf7550f639e62ee/amcatclient/amcatclient.py#L211-L250
[ "def check(response, expected_status=200, url=None):\n \"\"\"\n Check whether the status code of the response equals expected_status and\n raise an APIError otherwise.\n @param url: The url of the response (for error messages).\n Defaults to response.url\n @param json: if True, return ...
class AmcatAPI(object): def __init__(self, host, user=None, password=None, token=None): """ Connection to an AmCAT server. :param host: AmCAT server address, including http(s):// :param user: Username. If not given, taken from AMCAT_USER or USER environment :param password:...
amcat/amcatclient
amcatclient/amcatclient.py
AmcatAPI.get_pages
python
def get_pages(self, url, page=1, page_size=100, yield_pages=False, **filters): n = 0 for page in itertools.count(page): r = self.request(url, page=page, page_size=page_size, **filters) n += len(r['results']) log.debug("Got {url} page {page} / {pages}".format(url=url, ...
Get all pages at url, yielding individual results :param url: the url to fetch :param page: start from this page :param page_size: results per page :param yield_pages: yield whole pages rather than individual results :param filters: additional filters :return: a generator...
train
https://github.com/amcat/amcatclient/blob/bda525f7ace0c26a09fa56d2baf7550f639e62ee/amcatclient/amcatclient.py#L254-L275
[ "def request(self, url, method=\"get\", format=\"json\", data=None,\n expected_status=None, headers=None, use_xpost=True, **options):\n \"\"\"\n Make an HTTP request to the given relative URL with the host,\n user, and password information. Returns the deserialized json\n if successful, and r...
class AmcatAPI(object): def __init__(self, host, user=None, password=None, token=None): """ Connection to an AmCAT server. :param host: AmCAT server address, including http(s):// :param user: Username. If not given, taken from AMCAT_USER or USER environment :param password:...
amcat/amcatclient
amcatclient/amcatclient.py
AmcatAPI.get_scroll
python
def get_scroll(self, url, page_size=100, yield_pages=False, **filters): n = 0 options = dict(page_size=page_size, **filters) format = filters.get('format') while True: r = self.request(url, use_xpost=False, **options) n += len(r['results']) log.debug("...
Scroll through the resource at url and yield the individual results :param url: url to scroll through :param page_size: results per page :param yield_pages: yield whole pages rather than individual results :param filters: Additional filters :return: a generator of objects (dicts)...
train
https://github.com/amcat/amcatclient/blob/bda525f7ace0c26a09fa56d2baf7550f639e62ee/amcatclient/amcatclient.py#L277-L301
[ "def request(self, url, method=\"get\", format=\"json\", data=None,\n expected_status=None, headers=None, use_xpost=True, **options):\n \"\"\"\n Make an HTTP request to the given relative URL with the host,\n user, and password information. Returns the deserialized json\n if successful, and r...
class AmcatAPI(object): def __init__(self, host, user=None, password=None, token=None): """ Connection to an AmCAT server. :param host: AmCAT server address, including http(s):// :param user: Username. If not given, taken from AMCAT_USER or USER environment :param password:...
amcat/amcatclient
amcatclient/amcatclient.py
AmcatAPI.get_status
python
def get_status(self): url = URL.status.format(**locals()) return self.get_request(url)
Get the AmCAT status page
train
https://github.com/amcat/amcatclient/blob/bda525f7ace0c26a09fa56d2baf7550f639e62ee/amcatclient/amcatclient.py#L303-L306
null
class AmcatAPI(object): def __init__(self, host, user=None, password=None, token=None): """ Connection to an AmCAT server. :param host: AmCAT server address, including http(s):// :param user: Username. If not given, taken from AMCAT_USER or USER environment :param password:...
amcat/amcatclient
amcatclient/amcatclient.py
AmcatAPI.aggregate
python
def aggregate(self, **filters): url = URL.aggregate.format(**locals()) return self.get_pages(url, **filters)
Conduct an aggregate query
train
https://github.com/amcat/amcatclient/blob/bda525f7ace0c26a09fa56d2baf7550f639e62ee/amcatclient/amcatclient.py#L308-L311
[ "def get_pages(self, url, page=1, page_size=100, yield_pages=False, **filters):\n \"\"\"\n Get all pages at url, yielding individual results\n :param url: the url to fetch\n :param page: start from this page\n :param page_size: results per page\n :param yield_pages: yield whole pages rather than i...
class AmcatAPI(object): def __init__(self, host, user=None, password=None, token=None): """ Connection to an AmCAT server. :param host: AmCAT server address, including http(s):// :param user: Username. If not given, taken from AMCAT_USER or USER environment :param password:...
amcat/amcatclient
amcatclient/amcatclient.py
AmcatAPI.list_sets
python
def list_sets(self, project, **filters): url = URL.articlesets.format(**locals()) return self.get_pages(url, **filters)
List the articlesets in a project
train
https://github.com/amcat/amcatclient/blob/bda525f7ace0c26a09fa56d2baf7550f639e62ee/amcatclient/amcatclient.py#L313-L316
[ "def get_pages(self, url, page=1, page_size=100, yield_pages=False, **filters):\n \"\"\"\n Get all pages at url, yielding individual results\n :param url: the url to fetch\n :param page: start from this page\n :param page_size: results per page\n :param yield_pages: yield whole pages rather than i...
class AmcatAPI(object): def __init__(self, host, user=None, password=None, token=None): """ Connection to an AmCAT server. :param host: AmCAT server address, including http(s):// :param user: Username. If not given, taken from AMCAT_USER or USER environment :param password:...
amcat/amcatclient
amcatclient/amcatclient.py
AmcatAPI.get_set
python
def get_set(self, project, articleset, **filters): url = URL.articleset.format(**locals()) return self.request(url, **filters)
List the articlesets in a project
train
https://github.com/amcat/amcatclient/blob/bda525f7ace0c26a09fa56d2baf7550f639e62ee/amcatclient/amcatclient.py#L318-L321
[ "def request(self, url, method=\"get\", format=\"json\", data=None,\n expected_status=None, headers=None, use_xpost=True, **options):\n \"\"\"\n Make an HTTP request to the given relative URL with the host,\n user, and password information. Returns the deserialized json\n if successful, and r...
class AmcatAPI(object): def __init__(self, host, user=None, password=None, token=None): """ Connection to an AmCAT server. :param host: AmCAT server address, including http(s):// :param user: Username. If not given, taken from AMCAT_USER or USER environment :param password:...
amcat/amcatclient
amcatclient/amcatclient.py
AmcatAPI.list_articles
python
def list_articles(self, project, articleset, page=1, **filters): url = URL.article.format(**locals()) return self.get_pages(url, page=page, **filters)
List the articles in a set
train
https://github.com/amcat/amcatclient/blob/bda525f7ace0c26a09fa56d2baf7550f639e62ee/amcatclient/amcatclient.py#L323-L326
[ "def get_pages(self, url, page=1, page_size=100, yield_pages=False, **filters):\n \"\"\"\n Get all pages at url, yielding individual results\n :param url: the url to fetch\n :param page: start from this page\n :param page_size: results per page\n :param yield_pages: yield whole pages rather than i...
class AmcatAPI(object): def __init__(self, host, user=None, password=None, token=None): """ Connection to an AmCAT server. :param host: AmCAT server address, including http(s):// :param user: Username. If not given, taken from AMCAT_USER or USER environment :param password:...
amcat/amcatclient
amcatclient/amcatclient.py
AmcatAPI.create_set
python
def create_set(self, project, json_data=None, **options): url = URL.articlesets.format(**locals()) if json_data is None: # form encoded request return self.request(url, method="post", data=options) else: if not isinstance(json_data, (string_types)): ...
Create a new article set. Provide the needed arguments using post_data or with key-value pairs
train
https://github.com/amcat/amcatclient/blob/bda525f7ace0c26a09fa56d2baf7550f639e62ee/amcatclient/amcatclient.py#L333-L347
[ "def request(self, url, method=\"get\", format=\"json\", data=None,\n expected_status=None, headers=None, use_xpost=True, **options):\n \"\"\"\n Make an HTTP request to the given relative URL with the host,\n user, and password information. Returns the deserialized json\n if successful, and r...
class AmcatAPI(object): def __init__(self, host, user=None, password=None, token=None): """ Connection to an AmCAT server. :param host: AmCAT server address, including http(s):// :param user: Username. If not given, taken from AMCAT_USER or USER environment :param password:...
amcat/amcatclient
amcatclient/amcatclient.py
AmcatAPI.create_articles
python
def create_articles(self, project, articleset, json_data=None, **options): url = URL.article.format(**locals()) # TODO duplicated from create_set, move into requests # (or separate post method?) if json_data is None: # form encoded request return self.request(url,...
Create one or more articles in the set. Provide the needed arguments using the json_data or with key-value pairs @param json_data: A dictionary or list of dictionaries. Each dict can contain a 'children' attribute which is another list of dictionaries.
train
https://github.com/amcat/amcatclient/blob/bda525f7ace0c26a09fa56d2baf7550f639e62ee/amcatclient/amcatclient.py#L349-L367
[ "def request(self, url, method=\"get\", format=\"json\", data=None,\n expected_status=None, headers=None, use_xpost=True, **options):\n \"\"\"\n Make an HTTP request to the given relative URL with the host,\n user, and password information. Returns the deserialized json\n if successful, and r...
class AmcatAPI(object): def __init__(self, host, user=None, password=None, token=None): """ Connection to an AmCAT server. :param host: AmCAT server address, including http(s):// :param user: Username. If not given, taken from AMCAT_USER or USER environment :param password:...
amcat/amcatclient
demo_wikinews_scraper.py
get_pages
python
def get_pages(url): while True: yield url doc = html.parse(url).find("body") links = [a for a in doc.findall(".//a") if a.text and a.text.startswith("next ")] if not links: break url = urljoin(url, links[0].get('href'))
Return the 'pages' from the starting url Technically, look for the 'next 50' link, yield and download it, repeat
train
https://github.com/amcat/amcatclient/blob/bda525f7ace0c26a09fa56d2baf7550f639e62ee/demo_wikinews_scraper.py#L45-L56
null
#!/usr/bin/python from __future__ import unicode_literals, print_function, absolute_import ########################################################################### # (C) Vrije Universiteit, Amsterdam (the Netherlands) # # # ...
amcat/amcatclient
demo_wikinews_scraper.py
get_article_urls
python
def get_article_urls(url): doc = html.parse(url).getroot() for div in doc.cssselect("div.mw-search-result-heading"): href = div.cssselect("a")[0].get('href') if ":" in href: continue # skip Category: links href = urljoin(url, href) yield href
Return the articles from a page Technically, look for a div with class mw-search-result-heading and get the first link from this div
train
https://github.com/amcat/amcatclient/blob/bda525f7ace0c26a09fa56d2baf7550f639e62ee/demo_wikinews_scraper.py#L58-L70
null
#!/usr/bin/python from __future__ import unicode_literals, print_function, absolute_import ########################################################################### # (C) Vrije Universiteit, Amsterdam (the Netherlands) # # # ...
amcat/amcatclient
demo_wikinews_scraper.py
get_article
python
def get_article(url): a = html.parse(url).getroot() title = a.cssselect(".firstHeading")[0].text_content() date = a.cssselect(".published")[0].text_content() date = datetime.datetime.strptime(date, "%A, %B %d, %Y").isoformat() paras = a.cssselect("#mw-content-text p") paras = paras[1:] # skip fi...
Return a single article as a 'amcat-ready' dict Uses the 'export' function of wikinews to get an xml article
train
https://github.com/amcat/amcatclient/blob/bda525f7ace0c26a09fa56d2baf7550f639e62ee/demo_wikinews_scraper.py#L89-L106
null
#!/usr/bin/python from __future__ import unicode_literals, print_function, absolute_import ########################################################################### # (C) Vrije Universiteit, Amsterdam (the Netherlands) # # # ...
amcat/amcatclient
demo_wikinews_scraper.py
scrape_wikinews
python
def scrape_wikinews(conn, project, articleset, query): url = "http://en.wikinews.org/w/index.php?search={}&limit=50".format(query) logging.info(url) for page in get_pages(url): urls = get_article_urls(page) arts = list(get_articles(urls)) logging.info("Adding {} articles to set {}:{}...
Scrape wikinews articles from the given query @param conn: The AmcatAPI object @param articleset: The target articleset ID @param category: The wikinews category name
train
https://github.com/amcat/amcatclient/blob/bda525f7ace0c26a09fa56d2baf7550f639e62ee/demo_wikinews_scraper.py#L118-L133
[ "def get_pages(url):\n \"\"\"\n Return the 'pages' from the starting url\n Technically, look for the 'next 50' link, yield and download it, repeat\n \"\"\"\n while True:\n yield url\n doc = html.parse(url).find(\"body\")\n links = [a for a in doc.findall(\".//a\") if a.text and ...
#!/usr/bin/python from __future__ import unicode_literals, print_function, absolute_import ########################################################################### # (C) Vrije Universiteit, Amsterdam (the Netherlands) # # # ...
rcbops/osa_differ
osa_differ/osa_differ.py
get_commits
python
def get_commits(repo_dir, old_commit, new_commit, hide_merges=True): repo = Repo(repo_dir) commits = repo.iter_commits(rev="{0}..{1}".format(old_commit, new_commit)) if hide_merges: return [x for x in commits if not x.summary.startswith("Merge ")] else: return list(commits)
Find all commits between two commit SHAs.
train
https://github.com/rcbops/osa_differ/blob/b3452436655ba3db8cc6602390fd7fdf4ef30f01/osa_differ/osa_differ.py#L181-L188
null
#!/usr/bin/env python # Copyright 2016, Major Hayden # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law o...
rcbops/osa_differ
osa_differ/osa_differ.py
get_commit_url
python
def get_commit_url(repo_url): if "github.com" in repo_url: return repo_url[:-4] if repo_url.endswith(".git") else repo_url if "git.openstack.org" in repo_url: uri = '/'.join(repo_url.split('/')[-2:]) return "https://github.com/{0}".format(uri) # If it didn't match these conditions, ...
Determine URL to view commits for repo.
train
https://github.com/rcbops/osa_differ/blob/b3452436655ba3db8cc6602390fd7fdf4ef30f01/osa_differ/osa_differ.py#L191-L200
null
#!/usr/bin/env python # Copyright 2016, Major Hayden # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law o...
rcbops/osa_differ
osa_differ/osa_differ.py
get_projects
python
def get_projects(osa_repo_dir, commit): # Check out the correct commit SHA from the repository repo = Repo(osa_repo_dir) checkout(repo, commit) yaml_files = glob.glob( '{0}/playbooks/defaults/repo_packages/*.yml'.format(osa_repo_dir) ) yaml_parsed = [] for yaml_file in yaml_files: ...
Get all projects from multiple YAML files.
train
https://github.com/rcbops/osa_differ/blob/b3452436655ba3db8cc6602390fd7fdf4ef30f01/osa_differ/osa_differ.py#L203-L219
[ "def checkout(repo, ref):\n \"\"\"Checkout a repoself.\"\"\"\n # Delete local branch if it exists, remote branch will be tracked\n # automatically. This prevents stale local branches from causing problems.\n # It also avoids problems with appending origin/ to refs as that doesn't\n # work with tags, ...
#!/usr/bin/env python # Copyright 2016, Major Hayden # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law o...