repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
wrwrwr/scikit-gof
skgof/ksdist.py
ks_unif_durbin_matrix
def ks_unif_durbin_matrix(samples, statistic): """ Calculates the probability that the statistic is less than the given value, using a fairly accurate implementation of the Durbin's matrix formula. Not an exact transliteration of the Marsaglia code, but using the same ideas. Assumes samples > 0. See: doi:10.18637/jss.v008.i18. """ # Construct the Durbin matrix. h, k = modf(samples * statistic) k = int(k) h = 1 - h m = 2 * k + 1 A = tri(m, k=1) hs = h ** arange(1, m + 1) A[:, 0] -= hs A[-1] -= hs[::-1] if h > .5: A[-1, 0] += (2 * h - 1) ** m A /= fromfunction(lambda i, j: gamma(fmax(1, i - j + 2)), (m, m)) # Calculate A ** n, expressed as P * 2 ** eP to avoid overflows. P = identity(m) s = samples eA, eP = 0, 0 while s != 1: s, b = divmod(s, 2) if b == 1: P = dot(P, A) eP += eA if P[k, k] > factor: P /= factor eP += shift A = dot(A, A) eA *= 2 if A[k, k] > factor: A /= factor eA += shift P = dot(P, A) eP += eA # Calculate n! / n ** n * P[k, k]. x = P[k, k] for i in arange(1, samples + 1): x *= i / samples if x < factorr: x *= factor eP -= shift return x * 2 ** eP
python
def ks_unif_durbin_matrix(samples, statistic): """ Calculates the probability that the statistic is less than the given value, using a fairly accurate implementation of the Durbin's matrix formula. Not an exact transliteration of the Marsaglia code, but using the same ideas. Assumes samples > 0. See: doi:10.18637/jss.v008.i18. """ # Construct the Durbin matrix. h, k = modf(samples * statistic) k = int(k) h = 1 - h m = 2 * k + 1 A = tri(m, k=1) hs = h ** arange(1, m + 1) A[:, 0] -= hs A[-1] -= hs[::-1] if h > .5: A[-1, 0] += (2 * h - 1) ** m A /= fromfunction(lambda i, j: gamma(fmax(1, i - j + 2)), (m, m)) # Calculate A ** n, expressed as P * 2 ** eP to avoid overflows. P = identity(m) s = samples eA, eP = 0, 0 while s != 1: s, b = divmod(s, 2) if b == 1: P = dot(P, A) eP += eA if P[k, k] > factor: P /= factor eP += shift A = dot(A, A) eA *= 2 if A[k, k] > factor: A /= factor eA += shift P = dot(P, A) eP += eA # Calculate n! / n ** n * P[k, k]. x = P[k, k] for i in arange(1, samples + 1): x *= i / samples if x < factorr: x *= factor eP -= shift return x * 2 ** eP
[ "def", "ks_unif_durbin_matrix", "(", "samples", ",", "statistic", ")", ":", "# Construct the Durbin matrix.", "h", ",", "k", "=", "modf", "(", "samples", "*", "statistic", ")", "k", "=", "int", "(", "k", ")", "h", "=", "1", "-", "h", "m", "=", "2", "...
Calculates the probability that the statistic is less than the given value, using a fairly accurate implementation of the Durbin's matrix formula. Not an exact transliteration of the Marsaglia code, but using the same ideas. Assumes samples > 0. See: doi:10.18637/jss.v008.i18.
[ "Calculates", "the", "probability", "that", "the", "statistic", "is", "less", "than", "the", "given", "value", "using", "a", "fairly", "accurate", "implementation", "of", "the", "Durbin", "s", "matrix", "formula", "." ]
b950572758b9ebe38b9ea954ccc360d55cdf9c39
https://github.com/wrwrwr/scikit-gof/blob/b950572758b9ebe38b9ea954ccc360d55cdf9c39/skgof/ksdist.py#L87-L133
train
48,900
wrwrwr/scikit-gof
skgof/ksdist.py
ks_unif_durbin_recurrence_rational
def ks_unif_durbin_recurrence_rational(samples, statistic): """ Calculates the probability that the statistic is less than the given value, using Durbin's recurrence and employing the standard fractions module. This is a (hopefully) exact reference implementation, likely too slow for practical usage. The statistic should be given as a Fraction instance and the result is also a Fraction. See: doi:10.18637/jss.v026.i02. """ t = statistic * samples # Python 3: int()s can be skipped. ft1 = int(floor(t)) + 1 fmt1 = int(floor(-t)) + 1 fdt1 = int(floor(2 * t)) + 1 qs = [Fraction(i ** i, factorial(i)) for i in range(ft1)] qs.extend(Fraction(i ** i, factorial(i)) - 2 * t * sum((t + j) ** (j - 1) / factorial(j) * (i - t - j) ** (i - j) / factorial(i - j) for j in range(i + fmt1)) for i in range(ft1, fdt1)) qs.extend(-sum((-1) ** j * (2 * t - j) ** j / factorial(j) * qs[i - j] for j in range(1, fdt1)) for i in range(fdt1, samples + 1)) return qs[samples] * factorial(samples) / samples ** samples
python
def ks_unif_durbin_recurrence_rational(samples, statistic): """ Calculates the probability that the statistic is less than the given value, using Durbin's recurrence and employing the standard fractions module. This is a (hopefully) exact reference implementation, likely too slow for practical usage. The statistic should be given as a Fraction instance and the result is also a Fraction. See: doi:10.18637/jss.v026.i02. """ t = statistic * samples # Python 3: int()s can be skipped. ft1 = int(floor(t)) + 1 fmt1 = int(floor(-t)) + 1 fdt1 = int(floor(2 * t)) + 1 qs = [Fraction(i ** i, factorial(i)) for i in range(ft1)] qs.extend(Fraction(i ** i, factorial(i)) - 2 * t * sum((t + j) ** (j - 1) / factorial(j) * (i - t - j) ** (i - j) / factorial(i - j) for j in range(i + fmt1)) for i in range(ft1, fdt1)) qs.extend(-sum((-1) ** j * (2 * t - j) ** j / factorial(j) * qs[i - j] for j in range(1, fdt1)) for i in range(fdt1, samples + 1)) return qs[samples] * factorial(samples) / samples ** samples
[ "def", "ks_unif_durbin_recurrence_rational", "(", "samples", ",", "statistic", ")", ":", "t", "=", "statistic", "*", "samples", "# Python 3: int()s can be skipped.", "ft1", "=", "int", "(", "floor", "(", "t", ")", ")", "+", "1", "fmt1", "=", "int", "(", "flo...
Calculates the probability that the statistic is less than the given value, using Durbin's recurrence and employing the standard fractions module. This is a (hopefully) exact reference implementation, likely too slow for practical usage. The statistic should be given as a Fraction instance and the result is also a Fraction. See: doi:10.18637/jss.v026.i02.
[ "Calculates", "the", "probability", "that", "the", "statistic", "is", "less", "than", "the", "given", "value", "using", "Durbin", "s", "recurrence", "and", "employing", "the", "standard", "fractions", "module", "." ]
b950572758b9ebe38b9ea954ccc360d55cdf9c39
https://github.com/wrwrwr/scikit-gof/blob/b950572758b9ebe38b9ea954ccc360d55cdf9c39/skgof/ksdist.py#L136-L159
train
48,901
wrwrwr/scikit-gof
skgof/ksdist.py
ks_unif_pelz_good
def ks_unif_pelz_good(samples, statistic): """ Approximates the statistic distribution by a transformed Li-Chien formula. This ought to be a bit more accurate than using the Kolmogorov limit, but should only be used with large squared sample count times statistic. See: doi:10.18637/jss.v039.i11 and http://www.jstor.org/stable/2985019. """ x = 1 / statistic r2 = 1 / samples rx = sqrt(r2) * x r2x = r2 * x r2x2 = r2x * x r4x = r2x * r2 r4x2 = r2x2 * r2 r4x3 = r2x2 * r2x r5x3 = r4x2 * rx r5x4 = r4x3 * rx r6x3 = r4x2 * r2x r7x5 = r5x4 * r2x r9x6 = r7x5 * r2x r11x8 = r9x6 * r2x2 a1 = rx * (-r6x3 / 108 + r4x2 / 18 - r4x / 36 - r2x / 3 + r2 / 6 + 2) a2 = pi2 / 3 * r5x3 * (r4x3 / 8 - r2x2 * 5 / 12 - r2x * 4 / 45 + x + 1 / 6) a3 = pi4 / 9 * r7x5 * (-r4x3 / 6 + r2x2 / 4 + r2x * 53 / 90 - 1 / 2) a4 = pi6 / 108 * r11x8 * (r2x2 / 6 - 1) a5 = pi2 / 18 * r5x3 * (r2x / 2 - 1) a6 = -pi4 * r9x6 / 108 w = -pi2 / 2 * r2x2 return hpi1d2 * ((a1 + (a2 + (a3 + a4 * hs2) * hs2) * hs2) * exp(w * hs2) + (a5 + a6 * is2) * is2 * exp(w * is2)).sum()
python
def ks_unif_pelz_good(samples, statistic): """ Approximates the statistic distribution by a transformed Li-Chien formula. This ought to be a bit more accurate than using the Kolmogorov limit, but should only be used with large squared sample count times statistic. See: doi:10.18637/jss.v039.i11 and http://www.jstor.org/stable/2985019. """ x = 1 / statistic r2 = 1 / samples rx = sqrt(r2) * x r2x = r2 * x r2x2 = r2x * x r4x = r2x * r2 r4x2 = r2x2 * r2 r4x3 = r2x2 * r2x r5x3 = r4x2 * rx r5x4 = r4x3 * rx r6x3 = r4x2 * r2x r7x5 = r5x4 * r2x r9x6 = r7x5 * r2x r11x8 = r9x6 * r2x2 a1 = rx * (-r6x3 / 108 + r4x2 / 18 - r4x / 36 - r2x / 3 + r2 / 6 + 2) a2 = pi2 / 3 * r5x3 * (r4x3 / 8 - r2x2 * 5 / 12 - r2x * 4 / 45 + x + 1 / 6) a3 = pi4 / 9 * r7x5 * (-r4x3 / 6 + r2x2 / 4 + r2x * 53 / 90 - 1 / 2) a4 = pi6 / 108 * r11x8 * (r2x2 / 6 - 1) a5 = pi2 / 18 * r5x3 * (r2x / 2 - 1) a6 = -pi4 * r9x6 / 108 w = -pi2 / 2 * r2x2 return hpi1d2 * ((a1 + (a2 + (a3 + a4 * hs2) * hs2) * hs2) * exp(w * hs2) + (a5 + a6 * is2) * is2 * exp(w * is2)).sum()
[ "def", "ks_unif_pelz_good", "(", "samples", ",", "statistic", ")", ":", "x", "=", "1", "/", "statistic", "r2", "=", "1", "/", "samples", "rx", "=", "sqrt", "(", "r2", ")", "*", "x", "r2x", "=", "r2", "*", "x", "r2x2", "=", "r2x", "*", "x", "r4x...
Approximates the statistic distribution by a transformed Li-Chien formula. This ought to be a bit more accurate than using the Kolmogorov limit, but should only be used with large squared sample count times statistic. See: doi:10.18637/jss.v039.i11 and http://www.jstor.org/stable/2985019.
[ "Approximates", "the", "statistic", "distribution", "by", "a", "transformed", "Li", "-", "Chien", "formula", "." ]
b950572758b9ebe38b9ea954ccc360d55cdf9c39
https://github.com/wrwrwr/scikit-gof/blob/b950572758b9ebe38b9ea954ccc360d55cdf9c39/skgof/ksdist.py#L172-L202
train
48,902
balabit/typesafety
typesafety/__init__.py
Typesafety.activate
def activate(self, *, filter_func=None): ''' Activate the type safety checker. After the call all functions that need to be checked will be. ''' if self.active: raise RuntimeError("Type safety check already active") self.__module_finder = ModuleFinder(Validator.decorate) if filter_func is not None: self.__module_finder.set_filter(filter_func) self.__module_finder.install()
python
def activate(self, *, filter_func=None): ''' Activate the type safety checker. After the call all functions that need to be checked will be. ''' if self.active: raise RuntimeError("Type safety check already active") self.__module_finder = ModuleFinder(Validator.decorate) if filter_func is not None: self.__module_finder.set_filter(filter_func) self.__module_finder.install()
[ "def", "activate", "(", "self", ",", "*", ",", "filter_func", "=", "None", ")", ":", "if", "self", ".", "active", ":", "raise", "RuntimeError", "(", "\"Type safety check already active\"", ")", "self", ".", "__module_finder", "=", "ModuleFinder", "(", "Validat...
Activate the type safety checker. After the call all functions that need to be checked will be.
[ "Activate", "the", "type", "safety", "checker", ".", "After", "the", "call", "all", "functions", "that", "need", "to", "be", "checked", "will", "be", "." ]
452242dd93da9ebd53c173c243156d1351cd96fd
https://github.com/balabit/typesafety/blob/452242dd93da9ebd53c173c243156d1351cd96fd/typesafety/__init__.py#L62-L74
train
48,903
OnroerendErfgoed/oe_utils
oe_utils/audit.py
audit
def audit(**kwargs): """ use this decorator to audit an operation """ def wrap(fn): @functools.wraps(fn) def advice(parent_object, *args, **kw): request = parent_object.request wijziging = request.audit_manager.create_revision() result = fn(parent_object, *args, **kw) if hasattr(request, 'user') and request.user is not None and 'actor' in request.user: actor = request.user['actor'] attributes = request.user['attributes'] wijziging.updated_by = actor.get('uri', None) if actor.get('uri') == actor.get('instantie_actor_uri'): wijziging.updated_by_omschrijving = ( attributes.get('displayname') or attributes.get('mail') or actor.get('omschrijving')) else: wijziging.updated_by_omschrijving = actor.get( 'omschrijving') else: wijziging.updated_by = 'publiek' wijziging.updated_by_omschrijving = 'publiek' r_id = request.matchdict.get('id') wijziging.resource_object_id = r_id if result is not None: try: renderer_name = request.registry.settings.get( 'audit.pyramid.json.renderer', 'jsonrenderer') json_string = renderers.render(renderer_name, result, request=request) result_object_json = json.loads(json_string) wijziging.resource_object_json = result_object_json wijziging.resource_object_id = _get_id_from_result(r_id, result_object_json, kwargs) except Exception as e: log.error(e) wijziging.versie = _get_versie_hash(wijziging) wijziging.actie = kwargs.get('actie') if kwargs.get('actie') else _action_from_request(request) request.audit_manager.save(wijziging) return result return advice return wrap
python
def audit(**kwargs): """ use this decorator to audit an operation """ def wrap(fn): @functools.wraps(fn) def advice(parent_object, *args, **kw): request = parent_object.request wijziging = request.audit_manager.create_revision() result = fn(parent_object, *args, **kw) if hasattr(request, 'user') and request.user is not None and 'actor' in request.user: actor = request.user['actor'] attributes = request.user['attributes'] wijziging.updated_by = actor.get('uri', None) if actor.get('uri') == actor.get('instantie_actor_uri'): wijziging.updated_by_omschrijving = ( attributes.get('displayname') or attributes.get('mail') or actor.get('omschrijving')) else: wijziging.updated_by_omschrijving = actor.get( 'omschrijving') else: wijziging.updated_by = 'publiek' wijziging.updated_by_omschrijving = 'publiek' r_id = request.matchdict.get('id') wijziging.resource_object_id = r_id if result is not None: try: renderer_name = request.registry.settings.get( 'audit.pyramid.json.renderer', 'jsonrenderer') json_string = renderers.render(renderer_name, result, request=request) result_object_json = json.loads(json_string) wijziging.resource_object_json = result_object_json wijziging.resource_object_id = _get_id_from_result(r_id, result_object_json, kwargs) except Exception as e: log.error(e) wijziging.versie = _get_versie_hash(wijziging) wijziging.actie = kwargs.get('actie') if kwargs.get('actie') else _action_from_request(request) request.audit_manager.save(wijziging) return result return advice return wrap
[ "def", "audit", "(", "*", "*", "kwargs", ")", ":", "def", "wrap", "(", "fn", ")", ":", "@", "functools", ".", "wraps", "(", "fn", ")", "def", "advice", "(", "parent_object", ",", "*", "args", ",", "*", "*", "kw", ")", ":", "request", "=", "pare...
use this decorator to audit an operation
[ "use", "this", "decorator", "to", "audit", "an", "operation" ]
7b2014bda8ac6bb71b7138eaa06ac17ef3ff4a6d
https://github.com/OnroerendErfgoed/oe_utils/blob/7b2014bda8ac6bb71b7138eaa06ac17ef3ff4a6d/oe_utils/audit.py#L40-L94
train
48,904
OnroerendErfgoed/oe_utils
oe_utils/audit.py
audit_with_request
def audit_with_request(**kwargs): """ use this decorator to audit an operation with a request as input variable """ def wrap(fn): @audit(**kwargs) def operation(parent_object, *args, **kw): return fn(parent_object.request, *args, **kw) @functools.wraps(fn) def advice_with_request(the_request, *args, **kw): class ParentObject: request = the_request return operation(ParentObject(), *args, **kw) return advice_with_request return wrap
python
def audit_with_request(**kwargs): """ use this decorator to audit an operation with a request as input variable """ def wrap(fn): @audit(**kwargs) def operation(parent_object, *args, **kw): return fn(parent_object.request, *args, **kw) @functools.wraps(fn) def advice_with_request(the_request, *args, **kw): class ParentObject: request = the_request return operation(ParentObject(), *args, **kw) return advice_with_request return wrap
[ "def", "audit_with_request", "(", "*", "*", "kwargs", ")", ":", "def", "wrap", "(", "fn", ")", ":", "@", "audit", "(", "*", "*", "kwargs", ")", "def", "operation", "(", "parent_object", ",", "*", "args", ",", "*", "*", "kw", ")", ":", "return", "...
use this decorator to audit an operation with a request as input variable
[ "use", "this", "decorator", "to", "audit", "an", "operation", "with", "a", "request", "as", "input", "variable" ]
7b2014bda8ac6bb71b7138eaa06ac17ef3ff4a6d
https://github.com/OnroerendErfgoed/oe_utils/blob/7b2014bda8ac6bb71b7138eaa06ac17ef3ff4a6d/oe_utils/audit.py#L97-L115
train
48,905
quantopian/serializable-traitlets
straitlets/traits.py
cross_validation_lock
def cross_validation_lock(obj): """ A contextmanager for holding Traited object's cross-validators. This should be used in circumstances where you want to call _validate, but don't want to fire cross-validators. """ # TODO: Replace this with usage of public API when # https://github.com/ipython/traitlets/pull/166 lands upstream. orig = getattr(obj, '_cross_validation_lock', False) try: obj._cross_validation_lock = True yield finally: obj._cross_validation_lock = orig
python
def cross_validation_lock(obj): """ A contextmanager for holding Traited object's cross-validators. This should be used in circumstances where you want to call _validate, but don't want to fire cross-validators. """ # TODO: Replace this with usage of public API when # https://github.com/ipython/traitlets/pull/166 lands upstream. orig = getattr(obj, '_cross_validation_lock', False) try: obj._cross_validation_lock = True yield finally: obj._cross_validation_lock = orig
[ "def", "cross_validation_lock", "(", "obj", ")", ":", "# TODO: Replace this with usage of public API when", "# https://github.com/ipython/traitlets/pull/166 lands upstream.", "orig", "=", "getattr", "(", "obj", ",", "'_cross_validation_lock'", ",", "False", ")", "try", ":", "...
A contextmanager for holding Traited object's cross-validators. This should be used in circumstances where you want to call _validate, but don't want to fire cross-validators.
[ "A", "contextmanager", "for", "holding", "Traited", "object", "s", "cross", "-", "validators", "." ]
dd334366d1130825aea55d3dfecd6756973594e0
https://github.com/quantopian/serializable-traitlets/blob/dd334366d1130825aea55d3dfecd6756973594e0/straitlets/traits.py#L19-L33
train
48,906
OnroerendErfgoed/oe_utils
oe_utils/deploy/__init__.py
copy_and_replace
def copy_and_replace(file_in, file_out, mapping, **kwargs): ''' Copy a file and replace some placeholders with new values. ''' separator = '@@' if 'separator' in kwargs: separator = kwargs['separator'] file_in = open(file_in, 'r') file_out = open(file_out, 'w') s = file_in.read() for find, replace in mapping: find = separator + find + separator print(u'Replacing {0} with {1}'.format(find, replace)) s = s.replace(find, replace) file_out.write(s)
python
def copy_and_replace(file_in, file_out, mapping, **kwargs): ''' Copy a file and replace some placeholders with new values. ''' separator = '@@' if 'separator' in kwargs: separator = kwargs['separator'] file_in = open(file_in, 'r') file_out = open(file_out, 'w') s = file_in.read() for find, replace in mapping: find = separator + find + separator print(u'Replacing {0} with {1}'.format(find, replace)) s = s.replace(find, replace) file_out.write(s)
[ "def", "copy_and_replace", "(", "file_in", ",", "file_out", ",", "mapping", ",", "*", "*", "kwargs", ")", ":", "separator", "=", "'@@'", "if", "'separator'", "in", "kwargs", ":", "separator", "=", "kwargs", "[", "'separator'", "]", "file_in", "=", "open", ...
Copy a file and replace some placeholders with new values.
[ "Copy", "a", "file", "and", "replace", "some", "placeholders", "with", "new", "values", "." ]
7b2014bda8ac6bb71b7138eaa06ac17ef3ff4a6d
https://github.com/OnroerendErfgoed/oe_utils/blob/7b2014bda8ac6bb71b7138eaa06ac17ef3ff4a6d/oe_utils/deploy/__init__.py#L4-L18
train
48,907
OnroerendErfgoed/oe_utils
oe_utils/data/data_types.py
MutableList.coerce
def coerce(cls, key, value): """ Convert plain list to MutableList. """ if not isinstance(value, MutableList): if isinstance(value, list): return MutableList(value) # this call will raise ValueError return Mutable.coerce(key, value) else: return value
python
def coerce(cls, key, value): """ Convert plain list to MutableList. """ if not isinstance(value, MutableList): if isinstance(value, list): return MutableList(value) # this call will raise ValueError return Mutable.coerce(key, value) else: return value
[ "def", "coerce", "(", "cls", ",", "key", ",", "value", ")", ":", "if", "not", "isinstance", "(", "value", ",", "MutableList", ")", ":", "if", "isinstance", "(", "value", ",", "list", ")", ":", "return", "MutableList", "(", "value", ")", "# this call wi...
Convert plain list to MutableList.
[ "Convert", "plain", "list", "to", "MutableList", "." ]
7b2014bda8ac6bb71b7138eaa06ac17ef3ff4a6d
https://github.com/OnroerendErfgoed/oe_utils/blob/7b2014bda8ac6bb71b7138eaa06ac17ef3ff4a6d/oe_utils/data/data_types.py#L8-L18
train
48,908
LordGaav/python-chaos
chaos/multiprocessing/workers.py
Workers.registerWorker
def registerWorker(self, name, worker): """ Register a new Worker, under the given descriptive name. Trying to register multiple workers under the same name will raise an Exception. Parameters ---------- name: string Name to register the given worker under. worker: multiprocessing.Process, or a subclass Process object to register. """ if not isinstance(worker, multiprocessing.Process): self.logger.error("Process {0} is not actually a Process!".format(name)) raise Exception("Process {0} is not actually a Process!".format(name)) if name in self.worker_list: self.logger.error("Process {0} already registered!".format(name)) raise Exception("Process {0} already registered!".format(name)) self.worker_list[name] = worker self.logger.debug("Registered worker {0}".format(name)) return worker
python
def registerWorker(self, name, worker): """ Register a new Worker, under the given descriptive name. Trying to register multiple workers under the same name will raise an Exception. Parameters ---------- name: string Name to register the given worker under. worker: multiprocessing.Process, or a subclass Process object to register. """ if not isinstance(worker, multiprocessing.Process): self.logger.error("Process {0} is not actually a Process!".format(name)) raise Exception("Process {0} is not actually a Process!".format(name)) if name in self.worker_list: self.logger.error("Process {0} already registered!".format(name)) raise Exception("Process {0} already registered!".format(name)) self.worker_list[name] = worker self.logger.debug("Registered worker {0}".format(name)) return worker
[ "def", "registerWorker", "(", "self", ",", "name", ",", "worker", ")", ":", "if", "not", "isinstance", "(", "worker", ",", "multiprocessing", ".", "Process", ")", ":", "self", ".", "logger", ".", "error", "(", "\"Process {0} is not actually a Process!\"", ".",...
Register a new Worker, under the given descriptive name. Trying to register multiple workers under the same name will raise an Exception. Parameters ---------- name: string Name to register the given worker under. worker: multiprocessing.Process, or a subclass Process object to register.
[ "Register", "a", "new", "Worker", "under", "the", "given", "descriptive", "name", "." ]
52cd29a6fd15693ee1e53786b93bcb23fbf84ddd
https://github.com/LordGaav/python-chaos/blob/52cd29a6fd15693ee1e53786b93bcb23fbf84ddd/chaos/multiprocessing/workers.py#L33-L57
train
48,909
LordGaav/python-chaos
chaos/multiprocessing/workers.py
Workers.getWorker
def getWorker(self, name): """ Retrieve the Worker registered under the given name. If the given name does not exists in the Worker list, an Exception is raised. Parameters ---------- name: string Name of the Worker to retrieve """ if not name in self.worker_list: self.logger.error("Worker {0} is not registered!".format(name)) raise Exception("Worker {0} is not registered!".format(name)) return self.worker_list[name]
python
def getWorker(self, name): """ Retrieve the Worker registered under the given name. If the given name does not exists in the Worker list, an Exception is raised. Parameters ---------- name: string Name of the Worker to retrieve """ if not name in self.worker_list: self.logger.error("Worker {0} is not registered!".format(name)) raise Exception("Worker {0} is not registered!".format(name)) return self.worker_list[name]
[ "def", "getWorker", "(", "self", ",", "name", ")", ":", "if", "not", "name", "in", "self", ".", "worker_list", ":", "self", ".", "logger", ".", "error", "(", "\"Worker {0} is not registered!\"", ".", "format", "(", "name", ")", ")", "raise", "Exception", ...
Retrieve the Worker registered under the given name. If the given name does not exists in the Worker list, an Exception is raised. Parameters ---------- name: string Name of the Worker to retrieve
[ "Retrieve", "the", "Worker", "registered", "under", "the", "given", "name", "." ]
52cd29a6fd15693ee1e53786b93bcb23fbf84ddd
https://github.com/LordGaav/python-chaos/blob/52cd29a6fd15693ee1e53786b93bcb23fbf84ddd/chaos/multiprocessing/workers.py#L65-L80
train
48,910
LordGaav/python-chaos
chaos/multiprocessing/workers.py
Workers.unregisterWorker
def unregisterWorker(self, name): """ Unregister the Worker registered under the given name. Make sure that the given Worker is properly stopped, or that a reference is kept in another place. Once unregistered, this class will not keep any other references to the Worker. Parameters ---------- name: string Name of the Worker to unregister """ if not name in self.worker_list: self.logger.error("Worker {0} is not registered!".format(name)) raise Exception("Worker {0} is not registered!".format(name)) del self.worker_list[name] self.logger.debug("Unregistered worker {0}".format(name))
python
def unregisterWorker(self, name): """ Unregister the Worker registered under the given name. Make sure that the given Worker is properly stopped, or that a reference is kept in another place. Once unregistered, this class will not keep any other references to the Worker. Parameters ---------- name: string Name of the Worker to unregister """ if not name in self.worker_list: self.logger.error("Worker {0} is not registered!".format(name)) raise Exception("Worker {0} is not registered!".format(name)) del self.worker_list[name] self.logger.debug("Unregistered worker {0}".format(name))
[ "def", "unregisterWorker", "(", "self", ",", "name", ")", ":", "if", "not", "name", "in", "self", ".", "worker_list", ":", "self", ".", "logger", ".", "error", "(", "\"Worker {0} is not registered!\"", ".", "format", "(", "name", ")", ")", "raise", "Except...
Unregister the Worker registered under the given name. Make sure that the given Worker is properly stopped, or that a reference is kept in another place. Once unregistered, this class will not keep any other references to the Worker. Parameters ---------- name: string Name of the Worker to unregister
[ "Unregister", "the", "Worker", "registered", "under", "the", "given", "name", "." ]
52cd29a6fd15693ee1e53786b93bcb23fbf84ddd
https://github.com/LordGaav/python-chaos/blob/52cd29a6fd15693ee1e53786b93bcb23fbf84ddd/chaos/multiprocessing/workers.py#L82-L100
train
48,911
LordGaav/python-chaos
chaos/multiprocessing/workers.py
Workers.startAll
def startAll(self): """ Start all registered Workers. """ self.logger.info("Starting all workers...") for worker in self.getWorkers(): process = self.getWorker(worker) self.logger.debug("Starting {0}".format(process.name)) process.start() self.logger.info("Started all workers")
python
def startAll(self): """ Start all registered Workers. """ self.logger.info("Starting all workers...") for worker in self.getWorkers(): process = self.getWorker(worker) self.logger.debug("Starting {0}".format(process.name)) process.start() self.logger.info("Started all workers")
[ "def", "startAll", "(", "self", ")", ":", "self", ".", "logger", ".", "info", "(", "\"Starting all workers...\"", ")", "for", "worker", "in", "self", ".", "getWorkers", "(", ")", ":", "process", "=", "self", ".", "getWorker", "(", "worker", ")", "self", ...
Start all registered Workers.
[ "Start", "all", "registered", "Workers", "." ]
52cd29a6fd15693ee1e53786b93bcb23fbf84ddd
https://github.com/LordGaav/python-chaos/blob/52cd29a6fd15693ee1e53786b93bcb23fbf84ddd/chaos/multiprocessing/workers.py#L102-L113
train
48,912
ReadabilityHoldings/python-readability-api
readability/utils.py
cast_datetime_filter
def cast_datetime_filter(value): """Cast a datetime filter value. :param value: string representation of a value that needs to be casted to a `datetime` object. """ if isinstance(value, str): dtime = parse_datetime(value) elif isinstance(value, datetime): dtime = value else: raise ValueError('Received value of type {0}'.format(type(value))) return dtime.isoformat()
python
def cast_datetime_filter(value): """Cast a datetime filter value. :param value: string representation of a value that needs to be casted to a `datetime` object. """ if isinstance(value, str): dtime = parse_datetime(value) elif isinstance(value, datetime): dtime = value else: raise ValueError('Received value of type {0}'.format(type(value))) return dtime.isoformat()
[ "def", "cast_datetime_filter", "(", "value", ")", ":", "if", "isinstance", "(", "value", ",", "str", ")", ":", "dtime", "=", "parse_datetime", "(", "value", ")", "elif", "isinstance", "(", "value", ",", "datetime", ")", ":", "dtime", "=", "value", "else"...
Cast a datetime filter value. :param value: string representation of a value that needs to be casted to a `datetime` object.
[ "Cast", "a", "datetime", "filter", "value", "." ]
4b746166877d5a8dc29222aedccb18c2506a5385
https://github.com/ReadabilityHoldings/python-readability-api/blob/4b746166877d5a8dc29222aedccb18c2506a5385/readability/utils.py#L46-L61
train
48,913
ReadabilityHoldings/python-readability-api
readability/utils.py
filter_args_to_dict
def filter_args_to_dict(filter_dict, accepted_filter_keys=[]): """Cast and validate filter args. :param filter_dict: Filter kwargs :param accepted_filter_keys: List of keys that are acceptable to use. """ out_dict = {} for k, v in filter_dict.items(): # make sure that the filter k is acceptable # and that there is a value associated with the key if k not in accepted_filter_keys or v is None: logger.debug( 'Filter was not in accepted_filter_keys or value is None.') # skip it continue filter_type = filter_type_map.get(k, None) if filter_type is None: logger.debug('Filter key not foud in map.') # hmm, this was an acceptable filter type but not in the map... # Going to skip it. continue # map of casting funcitons to filter types filter_cast_map = { 'int': cast_integer_filter, 'datetime': cast_datetime_filter } cast_function = filter_cast_map.get(filter_type, None) # if we get a cast function, call it with v. If not, just use v. if cast_function: out_value = cast_function(v) else: out_value = v out_dict[k] = out_value return out_dict
python
def filter_args_to_dict(filter_dict, accepted_filter_keys=[]): """Cast and validate filter args. :param filter_dict: Filter kwargs :param accepted_filter_keys: List of keys that are acceptable to use. """ out_dict = {} for k, v in filter_dict.items(): # make sure that the filter k is acceptable # and that there is a value associated with the key if k not in accepted_filter_keys or v is None: logger.debug( 'Filter was not in accepted_filter_keys or value is None.') # skip it continue filter_type = filter_type_map.get(k, None) if filter_type is None: logger.debug('Filter key not foud in map.') # hmm, this was an acceptable filter type but not in the map... # Going to skip it. continue # map of casting funcitons to filter types filter_cast_map = { 'int': cast_integer_filter, 'datetime': cast_datetime_filter } cast_function = filter_cast_map.get(filter_type, None) # if we get a cast function, call it with v. If not, just use v. if cast_function: out_value = cast_function(v) else: out_value = v out_dict[k] = out_value return out_dict
[ "def", "filter_args_to_dict", "(", "filter_dict", ",", "accepted_filter_keys", "=", "[", "]", ")", ":", "out_dict", "=", "{", "}", "for", "k", ",", "v", "in", "filter_dict", ".", "items", "(", ")", ":", "# make sure that the filter k is acceptable", "# and that ...
Cast and validate filter args. :param filter_dict: Filter kwargs :param accepted_filter_keys: List of keys that are acceptable to use.
[ "Cast", "and", "validate", "filter", "args", "." ]
4b746166877d5a8dc29222aedccb18c2506a5385
https://github.com/ReadabilityHoldings/python-readability-api/blob/4b746166877d5a8dc29222aedccb18c2506a5385/readability/utils.py#L75-L113
train
48,914
hyperboria/python-cjdns
cjdns/bencode.py
bencode
def bencode(obj): """Bencodes obj and returns it as a string""" if isinstance(obj, int): return "i" + str(obj) + "e" if isinstance(obj, str): if not obj: return None return str(len(obj)) + ":" + obj if isinstance(obj, list): res = "l" for elem in obj: elem = bencode(elem) if elem: res += elem return res + "e" if isinstance(obj, dict): res = "d" for key in sorted(obj.keys()): if key in obj: value = bencode(obj[key]) key = bencode(key) if key and value: res += key + value return res + "e" if isinstance(obj, unicode): return bencode(obj.encode('utf-8')) if isinstance(obj, collections.OrderedDict): return bencode(dict(obj)) raise Exception("Unknown object: %s (%s)" % (repr(obj), repr(type(obj))))
python
def bencode(obj): """Bencodes obj and returns it as a string""" if isinstance(obj, int): return "i" + str(obj) + "e" if isinstance(obj, str): if not obj: return None return str(len(obj)) + ":" + obj if isinstance(obj, list): res = "l" for elem in obj: elem = bencode(elem) if elem: res += elem return res + "e" if isinstance(obj, dict): res = "d" for key in sorted(obj.keys()): if key in obj: value = bencode(obj[key]) key = bencode(key) if key and value: res += key + value return res + "e" if isinstance(obj, unicode): return bencode(obj.encode('utf-8')) if isinstance(obj, collections.OrderedDict): return bencode(dict(obj)) raise Exception("Unknown object: %s (%s)" % (repr(obj), repr(type(obj))))
[ "def", "bencode", "(", "obj", ")", ":", "if", "isinstance", "(", "obj", ",", "int", ")", ":", "return", "\"i\"", "+", "str", "(", "obj", ")", "+", "\"e\"", "if", "isinstance", "(", "obj", ",", "str", ")", ":", "if", "not", "obj", ":", "return", ...
Bencodes obj and returns it as a string
[ "Bencodes", "obj", "and", "returns", "it", "as", "a", "string" ]
a9ae5d6d2e99c18f9fc50a9589729cd176efa900
https://github.com/hyperboria/python-cjdns/blob/a9ae5d6d2e99c18f9fc50a9589729cd176efa900/cjdns/bencode.py#L26-L60
train
48,915
hyperboria/python-cjdns
cjdns/bencode.py
bdecode
def bdecode(text): """Decodes a bencoded bytearray and returns it as a python object""" text = text.decode('utf-8') def bdecode_next(start): """bdecode helper function""" if text[start] == 'i': end = text.find('e', start) return int(text[start+1:end], 10), end + 1 if text[start] == 'l': res = [] start += 1 while text[start] != 'e': elem, start = bdecode_next(start) res.append(elem) return res, start + 1 if text[start] == 'd': res = {} start += 1 while text[start] != 'e': key, start = bdecode_next(start) value, start = bdecode_next(start) res[key] = value return res, start + 1 lenend = text.find(':', start) length = int(text[start:lenend], 10) end = lenend + length + 1 return text[lenend+1:end], end return bdecode_next(0)[0]
python
def bdecode(text): """Decodes a bencoded bytearray and returns it as a python object""" text = text.decode('utf-8') def bdecode_next(start): """bdecode helper function""" if text[start] == 'i': end = text.find('e', start) return int(text[start+1:end], 10), end + 1 if text[start] == 'l': res = [] start += 1 while text[start] != 'e': elem, start = bdecode_next(start) res.append(elem) return res, start + 1 if text[start] == 'd': res = {} start += 1 while text[start] != 'e': key, start = bdecode_next(start) value, start = bdecode_next(start) res[key] = value return res, start + 1 lenend = text.find(':', start) length = int(text[start:lenend], 10) end = lenend + length + 1 return text[lenend+1:end], end return bdecode_next(0)[0]
[ "def", "bdecode", "(", "text", ")", ":", "text", "=", "text", ".", "decode", "(", "'utf-8'", ")", "def", "bdecode_next", "(", "start", ")", ":", "\"\"\"bdecode helper function\"\"\"", "if", "text", "[", "start", "]", "==", "'i'", ":", "end", "=", "text",...
Decodes a bencoded bytearray and returns it as a python object
[ "Decodes", "a", "bencoded", "bytearray", "and", "returns", "it", "as", "a", "python", "object" ]
a9ae5d6d2e99c18f9fc50a9589729cd176efa900
https://github.com/hyperboria/python-cjdns/blob/a9ae5d6d2e99c18f9fc50a9589729cd176efa900/cjdns/bencode.py#L63-L94
train
48,916
jakewins/neo4jdb-python
pavement.py
change_password
def change_password(): """ Changes the standard password from neo4j to testing to be able to run the test suite. """ basic_auth = '%s:%s' % (DEFAULT_USERNAME, DEFAULT_PASSWORD) try: # Python 2 auth = base64.encodestring(basic_auth) except TypeError: # Python 3 auth = base64.encodestring(bytes(basic_auth, 'utf-8')).decode() headers = { "Content-Type": "application/json", "Accept": "application/json", "Authorization": "Basic %s" % auth.strip() } response = None retry = 0 while not response: # Retry if the server is not ready yet sleep(1) con = http.HTTPConnection('localhost:7474', timeout=10) try: con.request('GET', 'http://localhost:7474/user/neo4j', headers=headers) response = json.loads(con.getresponse().read().decode('utf-8')) except ValueError: con.close() retry += 1 if retry > 10: print("Could not change password for user neo4j") break if response and response.get('password_change_required', None): payload = json.dumps({'password': 'testing'}) con.request('POST', 'http://localhost:7474/user/neo4j/password', payload, headers) print("Password changed for user neo4j") con.close()
python
def change_password(): """ Changes the standard password from neo4j to testing to be able to run the test suite. """ basic_auth = '%s:%s' % (DEFAULT_USERNAME, DEFAULT_PASSWORD) try: # Python 2 auth = base64.encodestring(basic_auth) except TypeError: # Python 3 auth = base64.encodestring(bytes(basic_auth, 'utf-8')).decode() headers = { "Content-Type": "application/json", "Accept": "application/json", "Authorization": "Basic %s" % auth.strip() } response = None retry = 0 while not response: # Retry if the server is not ready yet sleep(1) con = http.HTTPConnection('localhost:7474', timeout=10) try: con.request('GET', 'http://localhost:7474/user/neo4j', headers=headers) response = json.loads(con.getresponse().read().decode('utf-8')) except ValueError: con.close() retry += 1 if retry > 10: print("Could not change password for user neo4j") break if response and response.get('password_change_required', None): payload = json.dumps({'password': 'testing'}) con.request('POST', 'http://localhost:7474/user/neo4j/password', payload, headers) print("Password changed for user neo4j") con.close()
[ "def", "change_password", "(", ")", ":", "basic_auth", "=", "'%s:%s'", "%", "(", "DEFAULT_USERNAME", ",", "DEFAULT_PASSWORD", ")", "try", ":", "# Python 2", "auth", "=", "base64", ".", "encodestring", "(", "basic_auth", ")", "except", "TypeError", ":", "# Pyth...
Changes the standard password from neo4j to testing to be able to run the test suite.
[ "Changes", "the", "standard", "password", "from", "neo4j", "to", "testing", "to", "be", "able", "to", "run", "the", "test", "suite", "." ]
cd78cb8397885f219500fb1080d301f0c900f7be
https://github.com/jakewins/neo4jdb-python/blob/cd78cb8397885f219500fb1080d301f0c900f7be/pavement.py#L75-L109
train
48,917
LordGaav/python-chaos
chaos/arguments.py
get_default_config_file
def get_default_config_file(argparser, suppress=None, default_override=None): """ Turn an ArgumentParser into a ConfigObj compatible configuration file. This method will take the given argparser, and loop over all options contained. The configuration file is formatted as follows: # <option help info> <option destination variable>=<option default value> Arguments --------- argparser: ArgumentParser suppress: list of strings All options specified will be suppressed from the config file. Useful to avoid adding stuff like version or help. default_override: dict This method will use the defaults from the given ArgumentParser, unless the option is specified here. If specified, the default from this dict will be used instead. The format is { "option": <new default value>, ... } . """ if not suppress: suppress = [] if not default_override: default_override = {} lines = [] seen_arguments = [] for arg in argparser._actions: if arg.dest in suppress: continue if arg.dest in seen_arguments: continue default = arg.default if arg.dest in default_override.keys(): default = default_override[arg.dest] lines.append("# {0}\n{1}={2}\n".format(arg.help, arg.dest, default)) seen_arguments.append(arg.dest) return "".join(lines)
python
def get_default_config_file(argparser, suppress=None, default_override=None): """ Turn an ArgumentParser into a ConfigObj compatible configuration file. This method will take the given argparser, and loop over all options contained. The configuration file is formatted as follows: # <option help info> <option destination variable>=<option default value> Arguments --------- argparser: ArgumentParser suppress: list of strings All options specified will be suppressed from the config file. Useful to avoid adding stuff like version or help. default_override: dict This method will use the defaults from the given ArgumentParser, unless the option is specified here. If specified, the default from this dict will be used instead. The format is { "option": <new default value>, ... } . """ if not suppress: suppress = [] if not default_override: default_override = {} lines = [] seen_arguments = [] for arg in argparser._actions: if arg.dest in suppress: continue if arg.dest in seen_arguments: continue default = arg.default if arg.dest in default_override.keys(): default = default_override[arg.dest] lines.append("# {0}\n{1}={2}\n".format(arg.help, arg.dest, default)) seen_arguments.append(arg.dest) return "".join(lines)
[ "def", "get_default_config_file", "(", "argparser", ",", "suppress", "=", "None", ",", "default_override", "=", "None", ")", ":", "if", "not", "suppress", ":", "suppress", "=", "[", "]", "if", "not", "default_override", ":", "default_override", "=", "{", "}"...
Turn an ArgumentParser into a ConfigObj compatible configuration file. This method will take the given argparser, and loop over all options contained. The configuration file is formatted as follows: # <option help info> <option destination variable>=<option default value> Arguments --------- argparser: ArgumentParser suppress: list of strings All options specified will be suppressed from the config file. Useful to avoid adding stuff like version or help. default_override: dict This method will use the defaults from the given ArgumentParser, unless the option is specified here. If specified, the default from this dict will be used instead. The format is { "option": <new default value>, ... } .
[ "Turn", "an", "ArgumentParser", "into", "a", "ConfigObj", "compatible", "configuration", "file", "." ]
52cd29a6fd15693ee1e53786b93bcb23fbf84ddd
https://github.com/LordGaav/python-chaos/blob/52cd29a6fd15693ee1e53786b93bcb23fbf84ddd/chaos/arguments.py#L82-L119
train
48,918
LordGaav/python-chaos
chaos/amqp/queue.py
Queue._perform_binds
def _perform_binds(self, binds): """ Binds queues to exchanges. Parameters ---------- binds: list of dicts a list of dicts with the following keys: queue: string - name of the queue to bind exchange: string - name of the exchange to bind routing_key: string - routing key to use for this bind """ for bind in binds: self.logger.debug("Binding queue {0} to exchange {1} with key {2}".format(bind['queue'], bind['exchange'], bind['routing_key'])) self.channel.queue_bind(**bind)
python
def _perform_binds(self, binds): """ Binds queues to exchanges. Parameters ---------- binds: list of dicts a list of dicts with the following keys: queue: string - name of the queue to bind exchange: string - name of the exchange to bind routing_key: string - routing key to use for this bind """ for bind in binds: self.logger.debug("Binding queue {0} to exchange {1} with key {2}".format(bind['queue'], bind['exchange'], bind['routing_key'])) self.channel.queue_bind(**bind)
[ "def", "_perform_binds", "(", "self", ",", "binds", ")", ":", "for", "bind", "in", "binds", ":", "self", ".", "logger", ".", "debug", "(", "\"Binding queue {0} to exchange {1} with key {2}\"", ".", "format", "(", "bind", "[", "'queue'", "]", ",", "bind", "["...
Binds queues to exchanges. Parameters ---------- binds: list of dicts a list of dicts with the following keys: queue: string - name of the queue to bind exchange: string - name of the exchange to bind routing_key: string - routing key to use for this bind
[ "Binds", "queues", "to", "exchanges", "." ]
52cd29a6fd15693ee1e53786b93bcb23fbf84ddd
https://github.com/LordGaav/python-chaos/blob/52cd29a6fd15693ee1e53786b93bcb23fbf84ddd/chaos/amqp/queue.py#L70-L84
train
48,919
LordGaav/python-chaos
chaos/amqp/queue.py
Queue._perform_unbinds
def _perform_unbinds(self, binds): """ Unbinds queues from exchanges. Parameters ---------- binds: list of dicts A list of dicts with the following keys: queue: string - name of the queue to bind exchange: string - name of the exchange to bind routing_key: string - routing key to use for this bind """ for bind in binds: self.logger.debug("Unbinding queue {0} from exchange {1} with key {2}".format(bind['queue'], bind['exchange'], bind['routing_key'])) self.channel.queue_unbind(**bind)
python
def _perform_unbinds(self, binds): """ Unbinds queues from exchanges. Parameters ---------- binds: list of dicts A list of dicts with the following keys: queue: string - name of the queue to bind exchange: string - name of the exchange to bind routing_key: string - routing key to use for this bind """ for bind in binds: self.logger.debug("Unbinding queue {0} from exchange {1} with key {2}".format(bind['queue'], bind['exchange'], bind['routing_key'])) self.channel.queue_unbind(**bind)
[ "def", "_perform_unbinds", "(", "self", ",", "binds", ")", ":", "for", "bind", "in", "binds", ":", "self", ".", "logger", ".", "debug", "(", "\"Unbinding queue {0} from exchange {1} with key {2}\"", ".", "format", "(", "bind", "[", "'queue'", "]", ",", "bind",...
Unbinds queues from exchanges. Parameters ---------- binds: list of dicts A list of dicts with the following keys: queue: string - name of the queue to bind exchange: string - name of the exchange to bind routing_key: string - routing key to use for this bind
[ "Unbinds", "queues", "from", "exchanges", "." ]
52cd29a6fd15693ee1e53786b93bcb23fbf84ddd
https://github.com/LordGaav/python-chaos/blob/52cd29a6fd15693ee1e53786b93bcb23fbf84ddd/chaos/amqp/queue.py#L86-L100
train
48,920
LordGaav/python-chaos
chaos/amqp/queue.py
Queue.close
def close(self): """ Closes the internal connection. """ self.cancel() self.logger.debug("Closing AMQP connection") try: self.connection.close() except Exception, eee: self.logger.warning("Received an error while trying to close AMQP connection: " + str(eee))
python
def close(self): """ Closes the internal connection. """ self.cancel() self.logger.debug("Closing AMQP connection") try: self.connection.close() except Exception, eee: self.logger.warning("Received an error while trying to close AMQP connection: " + str(eee))
[ "def", "close", "(", "self", ")", ":", "self", ".", "cancel", "(", ")", "self", ".", "logger", ".", "debug", "(", "\"Closing AMQP connection\"", ")", "try", ":", "self", ".", "connection", ".", "close", "(", ")", "except", "Exception", ",", "eee", ":",...
Closes the internal connection.
[ "Closes", "the", "internal", "connection", "." ]
52cd29a6fd15693ee1e53786b93bcb23fbf84ddd
https://github.com/LordGaav/python-chaos/blob/52cd29a6fd15693ee1e53786b93bcb23fbf84ddd/chaos/amqp/queue.py#L102-L111
train
48,921
LordGaav/python-chaos
chaos/amqp/queue.py
Queue.cancel
def cancel(self, consumer_tag=None): """ Cancels the current consuming action by using the stored consumer_tag. If a consumer_tag is given, that one is used instead. Parameters ---------- consumer_tag: string Tag of consumer to cancel """ if not consumer_tag: if not hasattr(self, "consumer_tag"): return consumer_tag = self.consumer_tag self.channel.basic_cancel(consumer_tag)
python
def cancel(self, consumer_tag=None): """ Cancels the current consuming action by using the stored consumer_tag. If a consumer_tag is given, that one is used instead. Parameters ---------- consumer_tag: string Tag of consumer to cancel """ if not consumer_tag: if not hasattr(self, "consumer_tag"): return consumer_tag = self.consumer_tag self.channel.basic_cancel(consumer_tag)
[ "def", "cancel", "(", "self", ",", "consumer_tag", "=", "None", ")", ":", "if", "not", "consumer_tag", ":", "if", "not", "hasattr", "(", "self", ",", "\"consumer_tag\"", ")", ":", "return", "consumer_tag", "=", "self", ".", "consumer_tag", "self", ".", "...
Cancels the current consuming action by using the stored consumer_tag. If a consumer_tag is given, that one is used instead. Parameters ---------- consumer_tag: string Tag of consumer to cancel
[ "Cancels", "the", "current", "consuming", "action", "by", "using", "the", "stored", "consumer_tag", ".", "If", "a", "consumer_tag", "is", "given", "that", "one", "is", "used", "instead", "." ]
52cd29a6fd15693ee1e53786b93bcb23fbf84ddd
https://github.com/LordGaav/python-chaos/blob/52cd29a6fd15693ee1e53786b93bcb23fbf84ddd/chaos/amqp/queue.py#L113-L126
train
48,922
unfoldingWord-dev/python-gogs-client
gogs_client/entities.py
json_get
def json_get(parsed_json, key): """ Retrieves the key from a parsed_json dictionary, or raises an exception if the key is not present """ if key not in parsed_json: raise ValueError("JSON does not contain a {} field".format(key)) return parsed_json[key]
python
def json_get(parsed_json, key): """ Retrieves the key from a parsed_json dictionary, or raises an exception if the key is not present """ if key not in parsed_json: raise ValueError("JSON does not contain a {} field".format(key)) return parsed_json[key]
[ "def", "json_get", "(", "parsed_json", ",", "key", ")", ":", "if", "key", "not", "in", "parsed_json", ":", "raise", "ValueError", "(", "\"JSON does not contain a {} field\"", ".", "format", "(", "key", ")", ")", "return", "parsed_json", "[", "key", "]" ]
Retrieves the key from a parsed_json dictionary, or raises an exception if the key is not present
[ "Retrieves", "the", "key", "from", "a", "parsed_json", "dictionary", "or", "raises", "an", "exception", "if", "the", "key", "is", "not", "present" ]
b7f27f4995abf914c0db8a424760f5b27331939d
https://github.com/unfoldingWord-dev/python-gogs-client/blob/b7f27f4995abf914c0db8a424760f5b27331939d/gogs_client/entities.py#L10-L17
train
48,923
hyperboria/python-cjdns
setup.py
readme
def readme(fname): """Reads a markdown file and returns the contents formatted as rst""" md = open(os.path.join(os.path.dirname(__file__), fname)).read() output = md try: import pypandoc output = pypandoc.convert(md, 'rst', format='md') except ImportError: pass return output
python
def readme(fname): """Reads a markdown file and returns the contents formatted as rst""" md = open(os.path.join(os.path.dirname(__file__), fname)).read() output = md try: import pypandoc output = pypandoc.convert(md, 'rst', format='md') except ImportError: pass return output
[ "def", "readme", "(", "fname", ")", ":", "md", "=", "open", "(", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ",", "fname", ")", ")", ".", "read", "(", ")", "output", "=", "md", "try", ":", "im...
Reads a markdown file and returns the contents formatted as rst
[ "Reads", "a", "markdown", "file", "and", "returns", "the", "contents", "formatted", "as", "rst" ]
a9ae5d6d2e99c18f9fc50a9589729cd176efa900
https://github.com/hyperboria/python-cjdns/blob/a9ae5d6d2e99c18f9fc50a9589729cd176efa900/setup.py#L20-L29
train
48,924
LordGaav/python-chaos
chaos/config.py
get_config
def get_config(config_base, custom_file=None, configspec=None): """ Loads a configuration file from multiple locations, and merge the results into one. This function will load configuration files from a number of locations in sequence, and will overwrite values in the previous level if they are redefined in the current. The levels are in sequence: 1. Distribution level configuration in the program directory called $config_base.config. 2. System-wide level configuration in /etc/$config_base.config 3. User level configuration in ~/.$config_base.config 4. An optionally specified $custom_file Parameters ---------- config_base: string Basename of the configuration file, typically the same as the name of the program. custom_file: string Absolute path to a custom configuration file. configspec: ConfigObj Used to sanitize the values in the resulting ConfigObj. Validation errors are currently not exposed to the caller. """ logger = logging.getLogger(__name__) logger.debug("Expanding variables") home = os.path.expanduser("~") loc = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) logger.debug("Create empty config") config = ConfigObj() # Merge in config file in program dir if os.path.isfile(os.path.join(loc, "%s.config" % config_base)): logger.debug("Loading config from workingdir") cfg = ConfigObj(os.path.join(loc, "%s.config" % config_base), configspec=configspec) if configspec: cfg.validate(Validator()) config.merge(cfg) # Merge in system-wide config (Unix specific) if os.path.isfile("/etc/%s.config" % config_base): logger.debug("Loading config from /etc") cfg = ConfigObj("/etc/%s.config" % config_base, configspec=configspec) if configspec: cfg.validate(Validator()) config.merge(cfg) # Merge in user specific config if os.path.isfile(os.path.join(home, ".%s.config" % config_base)): logger.debug("Loading config from homedir") cfg = ConfigObj(os.path.join(home, ".%s.config" % config_base), configspec=configspec) if configspec: cfg.validate(Validator()) config.merge(cfg) # Config file provided on command line has preference if custom_file: logger.debug("Loading custom config file") cfg = ConfigObj(custom_file, configspec=configspec) if configspec: cfg.validate(Validator()) config.merge(cfg) return config
python
def get_config(config_base, custom_file=None, configspec=None): """ Loads a configuration file from multiple locations, and merge the results into one. This function will load configuration files from a number of locations in sequence, and will overwrite values in the previous level if they are redefined in the current. The levels are in sequence: 1. Distribution level configuration in the program directory called $config_base.config. 2. System-wide level configuration in /etc/$config_base.config 3. User level configuration in ~/.$config_base.config 4. An optionally specified $custom_file Parameters ---------- config_base: string Basename of the configuration file, typically the same as the name of the program. custom_file: string Absolute path to a custom configuration file. configspec: ConfigObj Used to sanitize the values in the resulting ConfigObj. Validation errors are currently not exposed to the caller. """ logger = logging.getLogger(__name__) logger.debug("Expanding variables") home = os.path.expanduser("~") loc = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) logger.debug("Create empty config") config = ConfigObj() # Merge in config file in program dir if os.path.isfile(os.path.join(loc, "%s.config" % config_base)): logger.debug("Loading config from workingdir") cfg = ConfigObj(os.path.join(loc, "%s.config" % config_base), configspec=configspec) if configspec: cfg.validate(Validator()) config.merge(cfg) # Merge in system-wide config (Unix specific) if os.path.isfile("/etc/%s.config" % config_base): logger.debug("Loading config from /etc") cfg = ConfigObj("/etc/%s.config" % config_base, configspec=configspec) if configspec: cfg.validate(Validator()) config.merge(cfg) # Merge in user specific config if os.path.isfile(os.path.join(home, ".%s.config" % config_base)): logger.debug("Loading config from homedir") cfg = ConfigObj(os.path.join(home, ".%s.config" % config_base), configspec=configspec) if configspec: cfg.validate(Validator()) config.merge(cfg) # Config file provided on command line has preference if custom_file: logger.debug("Loading custom config file") cfg = ConfigObj(custom_file, configspec=configspec) if configspec: cfg.validate(Validator()) config.merge(cfg) return config
[ "def", "get_config", "(", "config_base", ",", "custom_file", "=", "None", ",", "configspec", "=", "None", ")", ":", "logger", "=", "logging", ".", "getLogger", "(", "__name__", ")", "logger", ".", "debug", "(", "\"Expanding variables\"", ")", "home", "=", ...
Loads a configuration file from multiple locations, and merge the results into one. This function will load configuration files from a number of locations in sequence, and will overwrite values in the previous level if they are redefined in the current. The levels are in sequence: 1. Distribution level configuration in the program directory called $config_base.config. 2. System-wide level configuration in /etc/$config_base.config 3. User level configuration in ~/.$config_base.config 4. An optionally specified $custom_file Parameters ---------- config_base: string Basename of the configuration file, typically the same as the name of the program. custom_file: string Absolute path to a custom configuration file. configspec: ConfigObj Used to sanitize the values in the resulting ConfigObj. Validation errors are currently not exposed to the caller.
[ "Loads", "a", "configuration", "file", "from", "multiple", "locations", "and", "merge", "the", "results", "into", "one", "." ]
52cd29a6fd15693ee1e53786b93bcb23fbf84ddd
https://github.com/LordGaav/python-chaos/blob/52cd29a6fd15693ee1e53786b93bcb23fbf84ddd/chaos/config.py#L32-L98
train
48,925
LordGaav/python-chaos
chaos/config.py
get_config_dir
def get_config_dir(path, pattern="*.config", configspec=None, allow_errors=False): """ Load an entire directory of configuration files, merging them into one. This function will load multiple configuration files matching the given pattern, in the given path, and merge them. The found files are first sorted alphabetically, and then loaded and merged. A good practice is to use ConfigObj sections, for easy loading of information like per-host configuration. Parameters ---------- path: string Absolute path to a directory of ConfigObj files pattern: string Globbing pattern used to find files. Defaults to *.config. configspec: ConfigObj Used to sanitize the values in the resulting ConfigObj. Validation errors are currently not exposed to the caller. allow_errors: boolean If False, errors raised by ConfigObj are not caught. If True, errors raise by ConfigObj are caught, and an error is logged using logger. """ logger = logging.getLogger(__name__) logger.debug("Loading all files matching {0} in {1}".format(pattern, path)) files = Globber(path, include=[pattern], recursive=False).glob() files = sorted(files) config = ConfigObj() for filename in files: logger.debug("- Loading config for {0}".format(filename)) try: conf = ConfigObj(filename, configspec=configspec) except ConfigObjError, coe: logger.error("An error occurred while parsing {0}: {1}".format(filename, str(coe))) continue if configspec: conf.validate(Validator()) config.merge(conf) return config
python
def get_config_dir(path, pattern="*.config", configspec=None, allow_errors=False): """ Load an entire directory of configuration files, merging them into one. This function will load multiple configuration files matching the given pattern, in the given path, and merge them. The found files are first sorted alphabetically, and then loaded and merged. A good practice is to use ConfigObj sections, for easy loading of information like per-host configuration. Parameters ---------- path: string Absolute path to a directory of ConfigObj files pattern: string Globbing pattern used to find files. Defaults to *.config. configspec: ConfigObj Used to sanitize the values in the resulting ConfigObj. Validation errors are currently not exposed to the caller. allow_errors: boolean If False, errors raised by ConfigObj are not caught. If True, errors raise by ConfigObj are caught, and an error is logged using logger. """ logger = logging.getLogger(__name__) logger.debug("Loading all files matching {0} in {1}".format(pattern, path)) files = Globber(path, include=[pattern], recursive=False).glob() files = sorted(files) config = ConfigObj() for filename in files: logger.debug("- Loading config for {0}".format(filename)) try: conf = ConfigObj(filename, configspec=configspec) except ConfigObjError, coe: logger.error("An error occurred while parsing {0}: {1}".format(filename, str(coe))) continue if configspec: conf.validate(Validator()) config.merge(conf) return config
[ "def", "get_config_dir", "(", "path", ",", "pattern", "=", "\"*.config\"", ",", "configspec", "=", "None", ",", "allow_errors", "=", "False", ")", ":", "logger", "=", "logging", ".", "getLogger", "(", "__name__", ")", "logger", ".", "debug", "(", "\"Loadin...
Load an entire directory of configuration files, merging them into one. This function will load multiple configuration files matching the given pattern, in the given path, and merge them. The found files are first sorted alphabetically, and then loaded and merged. A good practice is to use ConfigObj sections, for easy loading of information like per-host configuration. Parameters ---------- path: string Absolute path to a directory of ConfigObj files pattern: string Globbing pattern used to find files. Defaults to *.config. configspec: ConfigObj Used to sanitize the values in the resulting ConfigObj. Validation errors are currently not exposed to the caller. allow_errors: boolean If False, errors raised by ConfigObj are not caught. If True, errors raise by ConfigObj are caught, and an error is logged using logger.
[ "Load", "an", "entire", "directory", "of", "configuration", "files", "merging", "them", "into", "one", "." ]
52cd29a6fd15693ee1e53786b93bcb23fbf84ddd
https://github.com/LordGaav/python-chaos/blob/52cd29a6fd15693ee1e53786b93bcb23fbf84ddd/chaos/config.py#L100-L142
train
48,926
genepattern/nbtools
nbtools/jsobject/utils.py
SimplePromise.resolve
def resolve(self, *pargs, **kwargs): """Resolve the promise.""" self._cached = (pargs, kwargs) self._try_then()
python
def resolve(self, *pargs, **kwargs): """Resolve the promise.""" self._cached = (pargs, kwargs) self._try_then()
[ "def", "resolve", "(", "self", ",", "*", "pargs", ",", "*", "*", "kwargs", ")", ":", "self", ".", "_cached", "=", "(", "pargs", ",", "kwargs", ")", "self", ".", "_try_then", "(", ")" ]
Resolve the promise.
[ "Resolve", "the", "promise", "." ]
2f74703f59926d8565f9714b1458dc87da8f8574
https://github.com/genepattern/nbtools/blob/2f74703f59926d8565f9714b1458dc87da8f8574/nbtools/jsobject/utils.py#L25-L28
train
48,927
genepattern/nbtools
nbtools/jsobject/utils.py
SimplePromise._try_then
def _try_then(self): """Check to see if self has been resolved yet, if so invoke then.""" if self._cached is not None and self._callback is not None: self._callback(*self._cached[0], **self._cached[1])
python
def _try_then(self): """Check to see if self has been resolved yet, if so invoke then.""" if self._cached is not None and self._callback is not None: self._callback(*self._cached[0], **self._cached[1])
[ "def", "_try_then", "(", "self", ")", ":", "if", "self", ".", "_cached", "is", "not", "None", "and", "self", ".", "_callback", "is", "not", "None", ":", "self", ".", "_callback", "(", "*", "self", ".", "_cached", "[", "0", "]", ",", "*", "*", "se...
Check to see if self has been resolved yet, if so invoke then.
[ "Check", "to", "see", "if", "self", "has", "been", "resolved", "yet", "if", "so", "invoke", "then", "." ]
2f74703f59926d8565f9714b1458dc87da8f8574
https://github.com/genepattern/nbtools/blob/2f74703f59926d8565f9714b1458dc87da8f8574/nbtools/jsobject/utils.py#L30-L33
train
48,928
genepattern/nbtools
nbtools/jsobject/utils.py
SimplePromise.wait_for
def wait_for(self, timeout=3000): """Hault execution until self resolves.""" results = [None] results_called = [False] def results_callback(val): results[0] = val results_called[0] = True self.then(results_callback) start = time.time() while not results_called[0]: if time.time() - start > timeout / 1000.: raise Exception('Timeout of %d ms reached' % timeout) ip.kernel.do_one_iteration() return results[0]
python
def wait_for(self, timeout=3000): """Hault execution until self resolves.""" results = [None] results_called = [False] def results_callback(val): results[0] = val results_called[0] = True self.then(results_callback) start = time.time() while not results_called[0]: if time.time() - start > timeout / 1000.: raise Exception('Timeout of %d ms reached' % timeout) ip.kernel.do_one_iteration() return results[0]
[ "def", "wait_for", "(", "self", ",", "timeout", "=", "3000", ")", ":", "results", "=", "[", "None", "]", "results_called", "=", "[", "False", "]", "def", "results_callback", "(", "val", ")", ":", "results", "[", "0", "]", "=", "val", "results_called", ...
Hault execution until self resolves.
[ "Hault", "execution", "until", "self", "resolves", "." ]
2f74703f59926d8565f9714b1458dc87da8f8574
https://github.com/genepattern/nbtools/blob/2f74703f59926d8565f9714b1458dc87da8f8574/nbtools/jsobject/utils.py#L35-L51
train
48,929
genepattern/nbtools
nbtools/widgets.py
UIBuilder._is_primitive
def _is_primitive(thing): """Determine if the value is a primitive""" primitive = (int, str, bool, float) return isinstance(thing, primitive)
python
def _is_primitive(thing): """Determine if the value is a primitive""" primitive = (int, str, bool, float) return isinstance(thing, primitive)
[ "def", "_is_primitive", "(", "thing", ")", ":", "primitive", "=", "(", "int", ",", "str", ",", "bool", ",", "float", ")", "return", "isinstance", "(", "thing", ",", "primitive", ")" ]
Determine if the value is a primitive
[ "Determine", "if", "the", "value", "is", "a", "primitive" ]
2f74703f59926d8565f9714b1458dc87da8f8574
https://github.com/genepattern/nbtools/blob/2f74703f59926d8565f9714b1458dc87da8f8574/nbtools/widgets.py#L222-L225
train
48,930
genepattern/nbtools
nbtools/widgets.py
UIBuilder._guess_type
def _guess_type(val): """Guess the input type of the parameter based off the default value, if unknown use text""" if isinstance(val, bool): return "choice" elif isinstance(val, int): return "number" elif isinstance(val, float): return "number" elif isinstance(val, str): return "text" elif hasattr(val, 'read'): return "file" else: return "text"
python
def _guess_type(val): """Guess the input type of the parameter based off the default value, if unknown use text""" if isinstance(val, bool): return "choice" elif isinstance(val, int): return "number" elif isinstance(val, float): return "number" elif isinstance(val, str): return "text" elif hasattr(val, 'read'): return "file" else: return "text"
[ "def", "_guess_type", "(", "val", ")", ":", "if", "isinstance", "(", "val", ",", "bool", ")", ":", "return", "\"choice\"", "elif", "isinstance", "(", "val", ",", "int", ")", ":", "return", "\"number\"", "elif", "isinstance", "(", "val", ",", "float", "...
Guess the input type of the parameter based off the default value, if unknown use text
[ "Guess", "the", "input", "type", "of", "the", "parameter", "based", "off", "the", "default", "value", "if", "unknown", "use", "text" ]
2f74703f59926d8565f9714b1458dc87da8f8574
https://github.com/genepattern/nbtools/blob/2f74703f59926d8565f9714b1458dc87da8f8574/nbtools/widgets.py#L237-L250
train
48,931
genepattern/nbtools
nbtools/widgets.py
UIBuilder._params
def _params(sig): """Read params, values and annotations from the signature""" params = [] for p in sig.parameters: param = sig.parameters[p] optional = param.default != inspect.Signature.empty default = UIBuilder._safe_default(param.default) if param.default != inspect.Signature.empty else '' annotation = param.annotation if param.annotation != inspect.Signature.empty else '' type = UIBuilder._guess_type(default) # Create the parameter attribute dict p_attr = { "name": param.name, "label": param.name, "optional": optional, "default": default, "description": annotation, "hide": False, "type": type, "kinds": None, "choices": [], "id": None, "events": None } # Special choices handling for boolean parameters if isinstance(default, bool): p_attr['choices'] = { 'True': 'true', 'False': 'false' } # Append it to the list params.append(p_attr) return params
python
def _params(sig): """Read params, values and annotations from the signature""" params = [] for p in sig.parameters: param = sig.parameters[p] optional = param.default != inspect.Signature.empty default = UIBuilder._safe_default(param.default) if param.default != inspect.Signature.empty else '' annotation = param.annotation if param.annotation != inspect.Signature.empty else '' type = UIBuilder._guess_type(default) # Create the parameter attribute dict p_attr = { "name": param.name, "label": param.name, "optional": optional, "default": default, "description": annotation, "hide": False, "type": type, "kinds": None, "choices": [], "id": None, "events": None } # Special choices handling for boolean parameters if isinstance(default, bool): p_attr['choices'] = { 'True': 'true', 'False': 'false' } # Append it to the list params.append(p_attr) return params
[ "def", "_params", "(", "sig", ")", ":", "params", "=", "[", "]", "for", "p", "in", "sig", ".", "parameters", ":", "param", "=", "sig", ".", "parameters", "[", "p", "]", "optional", "=", "param", ".", "default", "!=", "inspect", ".", "Signature", "....
Read params, values and annotations from the signature
[ "Read", "params", "values", "and", "annotations", "from", "the", "signature" ]
2f74703f59926d8565f9714b1458dc87da8f8574
https://github.com/genepattern/nbtools/blob/2f74703f59926d8565f9714b1458dc87da8f8574/nbtools/widgets.py#L253-L287
train
48,932
genepattern/nbtools
nbtools/widgets.py
UIBuilder._import
def _import(func): """Return the namespace path to the function""" func_name = func.__name__ # from foo.bar import func // func() # WARNING: May be broken in IPython, in which case the widget will use a fallback if func_name in globals(): return func_name # import foo.bar // foo.bar.func() module_name = func.__module__ submodules = module_name.split('.') if submodules[0] in globals(): return module_name + '.' + func_name # from foo import bar // bar.func() for i in range(len(submodules)): m = submodules[i] if m in globals(): return '.'.join(submodules[i:]) + '.' + func_name # import foo.bar as fb // fb.func() module_ref = sys.modules[func.__module__] all_globals = globals() for n in all_globals: if all_globals[n] == module_ref: return n + '.' + func_name # Not Found, return function name return func_name
python
def _import(func): """Return the namespace path to the function""" func_name = func.__name__ # from foo.bar import func // func() # WARNING: May be broken in IPython, in which case the widget will use a fallback if func_name in globals(): return func_name # import foo.bar // foo.bar.func() module_name = func.__module__ submodules = module_name.split('.') if submodules[0] in globals(): return module_name + '.' + func_name # from foo import bar // bar.func() for i in range(len(submodules)): m = submodules[i] if m in globals(): return '.'.join(submodules[i:]) + '.' + func_name # import foo.bar as fb // fb.func() module_ref = sys.modules[func.__module__] all_globals = globals() for n in all_globals: if all_globals[n] == module_ref: return n + '.' + func_name # Not Found, return function name return func_name
[ "def", "_import", "(", "func", ")", ":", "func_name", "=", "func", ".", "__name__", "# from foo.bar import func // func()", "# WARNING: May be broken in IPython, in which case the widget will use a fallback", "if", "func_name", "in", "globals", "(", ")", ":", "return", "fun...
Return the namespace path to the function
[ "Return", "the", "namespace", "path", "to", "the", "function" ]
2f74703f59926d8565f9714b1458dc87da8f8574
https://github.com/genepattern/nbtools/blob/2f74703f59926d8565f9714b1458dc87da8f8574/nbtools/widgets.py#L290-L321
train
48,933
LordGaav/python-chaos
chaos/logging.py
get_logger
def get_logger(name=None, level=logging.NOTSET, handlers=None): """ Create a Python logging Logger for the given name. A special case is when the name is None, as this will represent the root Logger object. When handlers are specified, the currently configured handlers for this name are removed, and the specified handlers are set. Parameters ---------- name: string Name of the Logger to create. Specify None to designate the root Logger. level: string One of: CRITICAL, ERROR, WARNING, INFO or DEBUG. Alternatively, use the `logging` constants: logging.CRITICAL, logging.ERROR, etc. handlers: dict Keys specifies the handler, value may optionally contain configuration, or be specified as None. Supported handlers are: - console: logging to stdout. Optionally specify a custom Handler using 'handler'. - file: logging to a specific file. Specify the file as 'logfile'. - syslog: logging to syslog. All handlers support custom output formats by specifying a 'format'. """ logger = logging.getLogger(name) if name is None: name = "root" if handlers is None: handlers = [] logger.setLevel(level) if len(handlers) != 0: logger.handlers = [] if "console" in handlers: if not isinstance(handlers['console'], collections.Iterable): handlers['console'] = {} if "handler" in handlers['console']: strm = handlers['console']['handler'] else: strm = logging.StreamHandler() if "format" in handlers['console']: fmt = logging.Formatter(handlers['console']['format']) else: fmt = logging.Formatter('%(message)s') strm.setLevel(level) strm.setFormatter(fmt) logger.addHandler(strm) if "file" in handlers: if not isinstance(handlers['file'], collections.Iterable): raise TypeError("file handler config must be a dict") if "logfile" not in handlers['file']: raise ValueError("file handler config must contain logfile path name") fil = logging.handlers.WatchedFileHandler(handlers['file']['logfile']) if "format" in handlers['file']: fmt = logging.Formatter(handlers['file']['format']) else: fmt = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') fil.setLevel(level) fil.setFormatter(fmt) logger.addHandler(fil) if "syslog" in handlers: if not isinstance(handlers['syslog'], collections.Iterable): handlers['syslog'] = {} sysl = logging.handlers.SysLogHandler(address='/dev/log', facility=logging.handlers.SysLogHandler.LOG_SYSLOG) if "format" in handlers['syslog']: fmt = logging.Formatter(handlers['syslog']['format']) else: fmt = logging.Formatter('%(name)s[%(process)s] %(levelname)-8s: %(message)s') sysl.setLevel(level) sysl.setFormatter(fmt) logger.addHandler(sysl) return logger
python
def get_logger(name=None, level=logging.NOTSET, handlers=None): """ Create a Python logging Logger for the given name. A special case is when the name is None, as this will represent the root Logger object. When handlers are specified, the currently configured handlers for this name are removed, and the specified handlers are set. Parameters ---------- name: string Name of the Logger to create. Specify None to designate the root Logger. level: string One of: CRITICAL, ERROR, WARNING, INFO or DEBUG. Alternatively, use the `logging` constants: logging.CRITICAL, logging.ERROR, etc. handlers: dict Keys specifies the handler, value may optionally contain configuration, or be specified as None. Supported handlers are: - console: logging to stdout. Optionally specify a custom Handler using 'handler'. - file: logging to a specific file. Specify the file as 'logfile'. - syslog: logging to syslog. All handlers support custom output formats by specifying a 'format'. """ logger = logging.getLogger(name) if name is None: name = "root" if handlers is None: handlers = [] logger.setLevel(level) if len(handlers) != 0: logger.handlers = [] if "console" in handlers: if not isinstance(handlers['console'], collections.Iterable): handlers['console'] = {} if "handler" in handlers['console']: strm = handlers['console']['handler'] else: strm = logging.StreamHandler() if "format" in handlers['console']: fmt = logging.Formatter(handlers['console']['format']) else: fmt = logging.Formatter('%(message)s') strm.setLevel(level) strm.setFormatter(fmt) logger.addHandler(strm) if "file" in handlers: if not isinstance(handlers['file'], collections.Iterable): raise TypeError("file handler config must be a dict") if "logfile" not in handlers['file']: raise ValueError("file handler config must contain logfile path name") fil = logging.handlers.WatchedFileHandler(handlers['file']['logfile']) if "format" in handlers['file']: fmt = logging.Formatter(handlers['file']['format']) else: fmt = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') fil.setLevel(level) fil.setFormatter(fmt) logger.addHandler(fil) if "syslog" in handlers: if not isinstance(handlers['syslog'], collections.Iterable): handlers['syslog'] = {} sysl = logging.handlers.SysLogHandler(address='/dev/log', facility=logging.handlers.SysLogHandler.LOG_SYSLOG) if "format" in handlers['syslog']: fmt = logging.Formatter(handlers['syslog']['format']) else: fmt = logging.Formatter('%(name)s[%(process)s] %(levelname)-8s: %(message)s') sysl.setLevel(level) sysl.setFormatter(fmt) logger.addHandler(sysl) return logger
[ "def", "get_logger", "(", "name", "=", "None", ",", "level", "=", "logging", ".", "NOTSET", ",", "handlers", "=", "None", ")", ":", "logger", "=", "logging", ".", "getLogger", "(", "name", ")", "if", "name", "is", "None", ":", "name", "=", "\"root\""...
Create a Python logging Logger for the given name. A special case is when the name is None, as this will represent the root Logger object. When handlers are specified, the currently configured handlers for this name are removed, and the specified handlers are set. Parameters ---------- name: string Name of the Logger to create. Specify None to designate the root Logger. level: string One of: CRITICAL, ERROR, WARNING, INFO or DEBUG. Alternatively, use the `logging` constants: logging.CRITICAL, logging.ERROR, etc. handlers: dict Keys specifies the handler, value may optionally contain configuration, or be specified as None. Supported handlers are: - console: logging to stdout. Optionally specify a custom Handler using 'handler'. - file: logging to a specific file. Specify the file as 'logfile'. - syslog: logging to syslog. All handlers support custom output formats by specifying a 'format'.
[ "Create", "a", "Python", "logging", "Logger", "for", "the", "given", "name", ".", "A", "special", "case", "is", "when", "the", "name", "is", "None", "as", "this", "will", "represent", "the", "root", "Logger", "object", "." ]
52cd29a6fd15693ee1e53786b93bcb23fbf84ddd
https://github.com/LordGaav/python-chaos/blob/52cd29a6fd15693ee1e53786b93bcb23fbf84ddd/chaos/logging.py#L30-L118
train
48,934
cbetz/untappd-python
untappd/__init__.py
Untappd._attach_endpoints
def _attach_endpoints(self): """Dynamically attaches endpoint callables to this client""" for name, value in inspect.getmembers(self): if inspect.isclass(value) and issubclass(value, self._Endpoint) and (value is not self._Endpoint): endpoint_instance = value(self.requester) setattr(self, endpoint_instance.endpoint_base, endpoint_instance) if not hasattr(endpoint_instance, 'get_endpoints'): endpoint_instance.get_endpoints = () if not hasattr(endpoint_instance, 'post_endpoints'): endpoint_instance.post_endpoints = () if not hasattr(endpoint_instance, 'is_callable'): endpoint_instance.is_callable = False for endpoint in (endpoint_instance.get_endpoints + endpoint_instance.post_endpoints): function = endpoint_instance.create_endpoint_function(endpoint) function_name = endpoint.replace('/', '_') setattr(endpoint_instance, function_name, function) function.__name__ = str(function_name) function.__doc__ = 'Tells the object to make a request to the {0} endpoint'.format(endpoint)
python
def _attach_endpoints(self): """Dynamically attaches endpoint callables to this client""" for name, value in inspect.getmembers(self): if inspect.isclass(value) and issubclass(value, self._Endpoint) and (value is not self._Endpoint): endpoint_instance = value(self.requester) setattr(self, endpoint_instance.endpoint_base, endpoint_instance) if not hasattr(endpoint_instance, 'get_endpoints'): endpoint_instance.get_endpoints = () if not hasattr(endpoint_instance, 'post_endpoints'): endpoint_instance.post_endpoints = () if not hasattr(endpoint_instance, 'is_callable'): endpoint_instance.is_callable = False for endpoint in (endpoint_instance.get_endpoints + endpoint_instance.post_endpoints): function = endpoint_instance.create_endpoint_function(endpoint) function_name = endpoint.replace('/', '_') setattr(endpoint_instance, function_name, function) function.__name__ = str(function_name) function.__doc__ = 'Tells the object to make a request to the {0} endpoint'.format(endpoint)
[ "def", "_attach_endpoints", "(", "self", ")", ":", "for", "name", ",", "value", "in", "inspect", ".", "getmembers", "(", "self", ")", ":", "if", "inspect", ".", "isclass", "(", "value", ")", "and", "issubclass", "(", "value", ",", "self", ".", "_Endpoi...
Dynamically attaches endpoint callables to this client
[ "Dynamically", "attaches", "endpoint", "callables", "to", "this", "client" ]
0f98a58948a77f89fe5e1875f5b01cb00623aa9a
https://github.com/cbetz/untappd-python/blob/0f98a58948a77f89fe5e1875f5b01cb00623aa9a/untappd/__init__.py#L55-L72
train
48,935
LordGaav/python-chaos
chaos/threading/threads.py
Threads.registerThread
def registerThread(self, name, thread): """ Register a new Thread , under the given descriptive name. Trying to register multiple threads under the same name will raise an Exception. Parameters ---------- name: string Name to register the given thread under. thread: threading.Thread, or a subclass Thread object to register. """ if not isinstance(thread, threading.Thread): self.logger.error("Thread {0} is not actually a Thread!".format(name)) raise Exception("Thread {0} is not actually a Thread!".format(name)) if name in self.thread_list: self.logger.error("Thread {0} already registered!".format(name)) raise Exception("Thread {0} already registered!".format(name)) self.thread_list[name] = thread self.logger.debug("Registered thread {0}".format(name)) return thread
python
def registerThread(self, name, thread): """ Register a new Thread , under the given descriptive name. Trying to register multiple threads under the same name will raise an Exception. Parameters ---------- name: string Name to register the given thread under. thread: threading.Thread, or a subclass Thread object to register. """ if not isinstance(thread, threading.Thread): self.logger.error("Thread {0} is not actually a Thread!".format(name)) raise Exception("Thread {0} is not actually a Thread!".format(name)) if name in self.thread_list: self.logger.error("Thread {0} already registered!".format(name)) raise Exception("Thread {0} already registered!".format(name)) self.thread_list[name] = thread self.logger.debug("Registered thread {0}".format(name)) return thread
[ "def", "registerThread", "(", "self", ",", "name", ",", "thread", ")", ":", "if", "not", "isinstance", "(", "thread", ",", "threading", ".", "Thread", ")", ":", "self", ".", "logger", ".", "error", "(", "\"Thread {0} is not actually a Thread!\"", ".", "forma...
Register a new Thread , under the given descriptive name. Trying to register multiple threads under the same name will raise an Exception. Parameters ---------- name: string Name to register the given thread under. thread: threading.Thread, or a subclass Thread object to register.
[ "Register", "a", "new", "Thread", "under", "the", "given", "descriptive", "name", "." ]
52cd29a6fd15693ee1e53786b93bcb23fbf84ddd
https://github.com/LordGaav/python-chaos/blob/52cd29a6fd15693ee1e53786b93bcb23fbf84ddd/chaos/threading/threads.py#L33-L57
train
48,936
LordGaav/python-chaos
chaos/threading/threads.py
Threads.getThread
def getThread(self, name): """ Retrieve the Thread registered under the given name. If the given name does not exists in the Thread list, an Exception is raised. Parameters ---------- name: string Name of the Thread to retrieve """ if not name in self.thread_list: self.logger.error("Thread {0} is not registered!".format(name)) raise Exception("Thread {0} is not registered!".format(name)) return self.thread_list[name]
python
def getThread(self, name): """ Retrieve the Thread registered under the given name. If the given name does not exists in the Thread list, an Exception is raised. Parameters ---------- name: string Name of the Thread to retrieve """ if not name in self.thread_list: self.logger.error("Thread {0} is not registered!".format(name)) raise Exception("Thread {0} is not registered!".format(name)) return self.thread_list[name]
[ "def", "getThread", "(", "self", ",", "name", ")", ":", "if", "not", "name", "in", "self", ".", "thread_list", ":", "self", ".", "logger", ".", "error", "(", "\"Thread {0} is not registered!\"", ".", "format", "(", "name", ")", ")", "raise", "Exception", ...
Retrieve the Thread registered under the given name. If the given name does not exists in the Thread list, an Exception is raised. Parameters ---------- name: string Name of the Thread to retrieve
[ "Retrieve", "the", "Thread", "registered", "under", "the", "given", "name", "." ]
52cd29a6fd15693ee1e53786b93bcb23fbf84ddd
https://github.com/LordGaav/python-chaos/blob/52cd29a6fd15693ee1e53786b93bcb23fbf84ddd/chaos/threading/threads.py#L65-L80
train
48,937
LordGaav/python-chaos
chaos/threading/threads.py
Threads.unregisterThread
def unregisterThread(self, name): """ Unregister the Thread registered under the given name. Make sure that the given Thread is properly stopped, or that a reference is kept in another place. Once unregistered, this class will not keep any other references to the Thread. Parameters ---------- name: string Name of the Thread to unregister """ if not name in self.thread_list: self.logger.error("Thread {0} is not registered!".format(name)) raise Exception("Thread {0} is not registered!".format(name)) del self.thread_list[name] self.logger.debug("Unregistered thread {0}".format(name))
python
def unregisterThread(self, name): """ Unregister the Thread registered under the given name. Make sure that the given Thread is properly stopped, or that a reference is kept in another place. Once unregistered, this class will not keep any other references to the Thread. Parameters ---------- name: string Name of the Thread to unregister """ if not name in self.thread_list: self.logger.error("Thread {0} is not registered!".format(name)) raise Exception("Thread {0} is not registered!".format(name)) del self.thread_list[name] self.logger.debug("Unregistered thread {0}".format(name))
[ "def", "unregisterThread", "(", "self", ",", "name", ")", ":", "if", "not", "name", "in", "self", ".", "thread_list", ":", "self", ".", "logger", ".", "error", "(", "\"Thread {0} is not registered!\"", ".", "format", "(", "name", ")", ")", "raise", "Except...
Unregister the Thread registered under the given name. Make sure that the given Thread is properly stopped, or that a reference is kept in another place. Once unregistered, this class will not keep any other references to the Thread. Parameters ---------- name: string Name of the Thread to unregister
[ "Unregister", "the", "Thread", "registered", "under", "the", "given", "name", "." ]
52cd29a6fd15693ee1e53786b93bcb23fbf84ddd
https://github.com/LordGaav/python-chaos/blob/52cd29a6fd15693ee1e53786b93bcb23fbf84ddd/chaos/threading/threads.py#L82-L100
train
48,938
LordGaav/python-chaos
chaos/threading/threads.py
Threads.startAll
def startAll(self): """ Start all registered Threads. """ self.logger.info("Starting all threads...") for thread in self.getThreads(): thr = self.getThread(thread) self.logger.debug("Starting {0}".format(thr.name)) thr.start() self.logger.info("Started all threads")
python
def startAll(self): """ Start all registered Threads. """ self.logger.info("Starting all threads...") for thread in self.getThreads(): thr = self.getThread(thread) self.logger.debug("Starting {0}".format(thr.name)) thr.start() self.logger.info("Started all threads")
[ "def", "startAll", "(", "self", ")", ":", "self", ".", "logger", ".", "info", "(", "\"Starting all threads...\"", ")", "for", "thread", "in", "self", ".", "getThreads", "(", ")", ":", "thr", "=", "self", ".", "getThread", "(", "thread", ")", "self", "....
Start all registered Threads.
[ "Start", "all", "registered", "Threads", "." ]
52cd29a6fd15693ee1e53786b93bcb23fbf84ddd
https://github.com/LordGaav/python-chaos/blob/52cd29a6fd15693ee1e53786b93bcb23fbf84ddd/chaos/threading/threads.py#L102-L113
train
48,939
mishbahr/django-usersettings2
usersettings/context_processors.py
usersettings
def usersettings(request): """ Returns the current ``UserSettings`` based on the SITE_ID in the project's settings as context variables If there is no 'usersettings' attribute in the request, fetches the current UserSettings (from usersettings.shortcuts.get_current_usersettings). """ if hasattr(request, 'usersettings'): usersettings = request.usersettings else: from .shortcuts import get_current_usersettings usersettings = get_current_usersettings() return { 'usersettings': usersettings }
python
def usersettings(request): """ Returns the current ``UserSettings`` based on the SITE_ID in the project's settings as context variables If there is no 'usersettings' attribute in the request, fetches the current UserSettings (from usersettings.shortcuts.get_current_usersettings). """ if hasattr(request, 'usersettings'): usersettings = request.usersettings else: from .shortcuts import get_current_usersettings usersettings = get_current_usersettings() return { 'usersettings': usersettings }
[ "def", "usersettings", "(", "request", ")", ":", "if", "hasattr", "(", "request", ",", "'usersettings'", ")", ":", "usersettings", "=", "request", ".", "usersettings", "else", ":", "from", ".", "shortcuts", "import", "get_current_usersettings", "usersettings", "...
Returns the current ``UserSettings`` based on the SITE_ID in the project's settings as context variables If there is no 'usersettings' attribute in the request, fetches the current UserSettings (from usersettings.shortcuts.get_current_usersettings).
[ "Returns", "the", "current", "UserSettings", "based", "on", "the", "SITE_ID", "in", "the", "project", "s", "settings", "as", "context", "variables" ]
cbc2f4b2e01d5401bec8a3fa39151730cd2dcd2a
https://github.com/mishbahr/django-usersettings2/blob/cbc2f4b2e01d5401bec8a3fa39151730cd2dcd2a/usersettings/context_processors.py#L2-L18
train
48,940
jeremymcrae/denovonear
denovonear/ensembl_requester.py
EnsemblRequest.check_ensembl_api_version
def check_ensembl_api_version(self): """ check the ensembl api version matches a currently working version This function is included so when the api version changes, we notice the change, and we can manually check the responses for the new version. """ self.attempt = 0 headers = {"content-type": "application/json"} ext = "/info/rest" r = self.ensembl_request(ext, headers) response = json.loads(r) self.cache.set_ensembl_api_version(response["release"])
python
def check_ensembl_api_version(self): """ check the ensembl api version matches a currently working version This function is included so when the api version changes, we notice the change, and we can manually check the responses for the new version. """ self.attempt = 0 headers = {"content-type": "application/json"} ext = "/info/rest" r = self.ensembl_request(ext, headers) response = json.loads(r) self.cache.set_ensembl_api_version(response["release"])
[ "def", "check_ensembl_api_version", "(", "self", ")", ":", "self", ".", "attempt", "=", "0", "headers", "=", "{", "\"content-type\"", ":", "\"application/json\"", "}", "ext", "=", "\"/info/rest\"", "r", "=", "self", ".", "ensembl_request", "(", "ext", ",", "...
check the ensembl api version matches a currently working version This function is included so when the api version changes, we notice the change, and we can manually check the responses for the new version.
[ "check", "the", "ensembl", "api", "version", "matches", "a", "currently", "working", "version", "This", "function", "is", "included", "so", "when", "the", "api", "version", "changes", "we", "notice", "the", "change", "and", "we", "can", "manually", "check", ...
feaab0fc77e89d70b31e8092899e4f0e68bac9fe
https://github.com/jeremymcrae/denovonear/blob/feaab0fc77e89d70b31e8092899e4f0e68bac9fe/denovonear/ensembl_requester.py#L55-L68
train
48,941
jeremymcrae/denovonear
denovonear/ensembl_requester.py
EnsemblRequest.open_url
def open_url(self, url, headers): """ open url with python libraries """ data = self.cache.get_cached_data(url) if data is not None: return data, 200, headers self.rate_limit_ensembl_requests() req = request.Request(url, headers=headers) try: handler = request.urlopen(req) except HTTPError as error: # if we get a http error, we still process the status code, since a # later step deals with different status codes differently. handler = error except (URLError, ConnectionResetError, TimeoutError): # if we get a ConnectionResetError, assume something has gone wrong # with the server. Later code will wait before retrying. return '', 500, headers status_code = handler.getcode() response = handler.read() if IS_PYTHON3: response = response.decode("utf-8") # parse the headers into a key, value dictionary headers = dict(zip(map(str.lower, handler.headers.keys()), handler.headers.values())) now = time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime()) logging.warning("{}\t{}\t{}".format(now, status_code, url)) return response, status_code, headers
python
def open_url(self, url, headers): """ open url with python libraries """ data = self.cache.get_cached_data(url) if data is not None: return data, 200, headers self.rate_limit_ensembl_requests() req = request.Request(url, headers=headers) try: handler = request.urlopen(req) except HTTPError as error: # if we get a http error, we still process the status code, since a # later step deals with different status codes differently. handler = error except (URLError, ConnectionResetError, TimeoutError): # if we get a ConnectionResetError, assume something has gone wrong # with the server. Later code will wait before retrying. return '', 500, headers status_code = handler.getcode() response = handler.read() if IS_PYTHON3: response = response.decode("utf-8") # parse the headers into a key, value dictionary headers = dict(zip(map(str.lower, handler.headers.keys()), handler.headers.values())) now = time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime()) logging.warning("{}\t{}\t{}".format(now, status_code, url)) return response, status_code, headers
[ "def", "open_url", "(", "self", ",", "url", ",", "headers", ")", ":", "data", "=", "self", ".", "cache", ".", "get_cached_data", "(", "url", ")", "if", "data", "is", "not", "None", ":", "return", "data", ",", "200", ",", "headers", "self", ".", "ra...
open url with python libraries
[ "open", "url", "with", "python", "libraries" ]
feaab0fc77e89d70b31e8092899e4f0e68bac9fe
https://github.com/jeremymcrae/denovonear/blob/feaab0fc77e89d70b31e8092899e4f0e68bac9fe/denovonear/ensembl_requester.py#L70-L103
train
48,942
jeremymcrae/denovonear
denovonear/ensembl_requester.py
EnsemblRequest.ensembl_request
def ensembl_request(self, ext, headers): """ obtain sequence via the ensembl REST API """ self.attempt += 1 if self.attempt > 5: raise ValueError("too many attempts, figure out why its failing") response, status, requested_headers = self.open_url(self.server + ext, headers=headers) # we might end up passing too many simultaneous requests, or too many # requests per hour, just wait until the period is finished before # retrying if status == 429: if "retry-after" in requested_headers: time.sleep(float(requested_headers["retry-after"])) elif "x-ratelimit-reset" in requested_headers: time.sleep(int(requested_headers["x-ratelimit-reset"])) return self.ensembl_request(ext, headers) # retry after 30 seconds if we get service unavailable error elif status in [500, 503, 504]: time.sleep(30) return self.ensembl_request(ext, headers) elif status != 200: raise ValueError("Invalid Ensembl response for {}\nheaders: {}\nresponse: {}".format(\ self.server + ext, requested_headers, response)) # sometimes ensembl returns odd data. I don't know what it is, but the # json interpreter can't handle it. Rather than trying to catch it, # simply re-request the data if requested_headers["content-type"] == "application/json": try: json.loads(response) except ValueError: now = time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime()) logging.warning("{}\t{}\t{}\t{}\t{}".format(now, status, self.server + ext, "cannot obtain json output")) return self.ensembl_request(ext, requested_headers) self.cache.cache_url_data(self.server + ext, response) return response
python
def ensembl_request(self, ext, headers): """ obtain sequence via the ensembl REST API """ self.attempt += 1 if self.attempt > 5: raise ValueError("too many attempts, figure out why its failing") response, status, requested_headers = self.open_url(self.server + ext, headers=headers) # we might end up passing too many simultaneous requests, or too many # requests per hour, just wait until the period is finished before # retrying if status == 429: if "retry-after" in requested_headers: time.sleep(float(requested_headers["retry-after"])) elif "x-ratelimit-reset" in requested_headers: time.sleep(int(requested_headers["x-ratelimit-reset"])) return self.ensembl_request(ext, headers) # retry after 30 seconds if we get service unavailable error elif status in [500, 503, 504]: time.sleep(30) return self.ensembl_request(ext, headers) elif status != 200: raise ValueError("Invalid Ensembl response for {}\nheaders: {}\nresponse: {}".format(\ self.server + ext, requested_headers, response)) # sometimes ensembl returns odd data. I don't know what it is, but the # json interpreter can't handle it. Rather than trying to catch it, # simply re-request the data if requested_headers["content-type"] == "application/json": try: json.loads(response) except ValueError: now = time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime()) logging.warning("{}\t{}\t{}\t{}\t{}".format(now, status, self.server + ext, "cannot obtain json output")) return self.ensembl_request(ext, requested_headers) self.cache.cache_url_data(self.server + ext, response) return response
[ "def", "ensembl_request", "(", "self", ",", "ext", ",", "headers", ")", ":", "self", ".", "attempt", "+=", "1", "if", "self", ".", "attempt", ">", "5", ":", "raise", "ValueError", "(", "\"too many attempts, figure out why its failing\"", ")", "response", ",", ...
obtain sequence via the ensembl REST API
[ "obtain", "sequence", "via", "the", "ensembl", "REST", "API" ]
feaab0fc77e89d70b31e8092899e4f0e68bac9fe
https://github.com/jeremymcrae/denovonear/blob/feaab0fc77e89d70b31e8092899e4f0e68bac9fe/denovonear/ensembl_requester.py#L105-L148
train
48,943
jeremymcrae/denovonear
denovonear/ensembl_requester.py
EnsemblRequest.get_genes_for_hgnc_id
def get_genes_for_hgnc_id(self, hgnc_symbol): """ obtain the ensembl gene IDs that correspond to a HGNC symbol """ headers = {"content-type": "application/json"} # http://grch37.rest.ensembl.org/xrefs/symbol/homo_sapiens/KMT2A?content-type=application/json self.attempt = 0 ext = "/xrefs/symbol/homo_sapiens/{}".format(hgnc_symbol) r = self.ensembl_request(ext, headers) genes = [] for item in json.loads(r): if item["type"] == "gene": genes.append(item["id"]) return genes
python
def get_genes_for_hgnc_id(self, hgnc_symbol): """ obtain the ensembl gene IDs that correspond to a HGNC symbol """ headers = {"content-type": "application/json"} # http://grch37.rest.ensembl.org/xrefs/symbol/homo_sapiens/KMT2A?content-type=application/json self.attempt = 0 ext = "/xrefs/symbol/homo_sapiens/{}".format(hgnc_symbol) r = self.ensembl_request(ext, headers) genes = [] for item in json.loads(r): if item["type"] == "gene": genes.append(item["id"]) return genes
[ "def", "get_genes_for_hgnc_id", "(", "self", ",", "hgnc_symbol", ")", ":", "headers", "=", "{", "\"content-type\"", ":", "\"application/json\"", "}", "# http://grch37.rest.ensembl.org/xrefs/symbol/homo_sapiens/KMT2A?content-type=application/json", "self", ".", "attempt", "=", ...
obtain the ensembl gene IDs that correspond to a HGNC symbol
[ "obtain", "the", "ensembl", "gene", "IDs", "that", "correspond", "to", "a", "HGNC", "symbol" ]
feaab0fc77e89d70b31e8092899e4f0e68bac9fe
https://github.com/jeremymcrae/denovonear/blob/feaab0fc77e89d70b31e8092899e4f0e68bac9fe/denovonear/ensembl_requester.py#L150-L167
train
48,944
jeremymcrae/denovonear
denovonear/ensembl_requester.py
EnsemblRequest.get_genomic_seq_for_region
def get_genomic_seq_for_region(self, chrom, start_pos, end_pos): """ obtain the sequence for a genomic region """ headers = {"content-type": "text/plain"} self.attempt = 0 ext = "/sequence/region/human/{}:{}..{}:1".format(chrom, start_pos, end_pos) return self.ensembl_request(ext, headers)
python
def get_genomic_seq_for_region(self, chrom, start_pos, end_pos): """ obtain the sequence for a genomic region """ headers = {"content-type": "text/plain"} self.attempt = 0 ext = "/sequence/region/human/{}:{}..{}:1".format(chrom, start_pos, end_pos) return self.ensembl_request(ext, headers)
[ "def", "get_genomic_seq_for_region", "(", "self", ",", "chrom", ",", "start_pos", ",", "end_pos", ")", ":", "headers", "=", "{", "\"content-type\"", ":", "\"text/plain\"", "}", "self", ".", "attempt", "=", "0", "ext", "=", "\"/sequence/region/human/{}:{}..{}:1\"",...
obtain the sequence for a genomic region
[ "obtain", "the", "sequence", "for", "a", "genomic", "region" ]
feaab0fc77e89d70b31e8092899e4f0e68bac9fe
https://github.com/jeremymcrae/denovonear/blob/feaab0fc77e89d70b31e8092899e4f0e68bac9fe/denovonear/ensembl_requester.py#L297-L306
train
48,945
jeremymcrae/denovonear
denovonear/ensembl_requester.py
EnsemblRequest.rate_limit_ensembl_requests
def rate_limit_ensembl_requests(self): """ limit ensembl requests to one per 0.067 s """ current_time = time.time() diff_time = current_time - self.prior_time # sleep until the current rate limit period is finished if diff_time < self.rate_limit: time.sleep(self.rate_limit - diff_time) # set the access time to now, for later checks self.prior_time = time.time()
python
def rate_limit_ensembl_requests(self): """ limit ensembl requests to one per 0.067 s """ current_time = time.time() diff_time = current_time - self.prior_time # sleep until the current rate limit period is finished if diff_time < self.rate_limit: time.sleep(self.rate_limit - diff_time) # set the access time to now, for later checks self.prior_time = time.time()
[ "def", "rate_limit_ensembl_requests", "(", "self", ")", ":", "current_time", "=", "time", ".", "time", "(", ")", "diff_time", "=", "current_time", "-", "self", ".", "prior_time", "# sleep until the current rate limit period is finished", "if", "diff_time", "<", "self"...
limit ensembl requests to one per 0.067 s
[ "limit", "ensembl", "requests", "to", "one", "per", "0", ".", "067", "s" ]
feaab0fc77e89d70b31e8092899e4f0e68bac9fe
https://github.com/jeremymcrae/denovonear/blob/feaab0fc77e89d70b31e8092899e4f0e68bac9fe/denovonear/ensembl_requester.py#L368-L380
train
48,946
LordGaav/python-chaos
chaos/cli.py
call_simple_cli
def call_simple_cli(command, cwd=None, universal_newlines=False, redirect_stderr=False): """ Simple wrapper around SimpleCliTool. Simple. """ return SimpleCliTool()._call_cli(command, cwd, universal_newlines, redirect_stderr)
python
def call_simple_cli(command, cwd=None, universal_newlines=False, redirect_stderr=False): """ Simple wrapper around SimpleCliTool. Simple. """ return SimpleCliTool()._call_cli(command, cwd, universal_newlines, redirect_stderr)
[ "def", "call_simple_cli", "(", "command", ",", "cwd", "=", "None", ",", "universal_newlines", "=", "False", ",", "redirect_stderr", "=", "False", ")", ":", "return", "SimpleCliTool", "(", ")", ".", "_call_cli", "(", "command", ",", "cwd", ",", "universal_new...
Simple wrapper around SimpleCliTool. Simple.
[ "Simple", "wrapper", "around", "SimpleCliTool", ".", "Simple", "." ]
52cd29a6fd15693ee1e53786b93bcb23fbf84ddd
https://github.com/LordGaav/python-chaos/blob/52cd29a6fd15693ee1e53786b93bcb23fbf84ddd/chaos/cli.py#L31-L33
train
48,947
genepattern/nbtools
nbtools/jsobject/jsobject.py
BrowserContext._on_msg
def _on_msg(self, msg): """Handle messages from the front-end""" data = msg['content']['data'] # If the message is a call invoke, run the function and send # the results. if 'callback' in data: guid = data['callback'] callback = callback_registry[guid] args = data['arguments'] args = [self.deserialize(a) for a in args] index = data['index'] results = callback(*args) return self.serialize(self._send('return', index=index, results=results)) # The message is not a call invoke, it must be an object # that is a response to a Python request. else: index = data['index'] immutable = data['immutable'] value = data['value'] if index in self._callbacks: self._callbacks[index].resolve({ 'immutable': immutable, 'value': value }) del self._callbacks[index]
python
def _on_msg(self, msg): """Handle messages from the front-end""" data = msg['content']['data'] # If the message is a call invoke, run the function and send # the results. if 'callback' in data: guid = data['callback'] callback = callback_registry[guid] args = data['arguments'] args = [self.deserialize(a) for a in args] index = data['index'] results = callback(*args) return self.serialize(self._send('return', index=index, results=results)) # The message is not a call invoke, it must be an object # that is a response to a Python request. else: index = data['index'] immutable = data['immutable'] value = data['value'] if index in self._callbacks: self._callbacks[index].resolve({ 'immutable': immutable, 'value': value }) del self._callbacks[index]
[ "def", "_on_msg", "(", "self", ",", "msg", ")", ":", "data", "=", "msg", "[", "'content'", "]", "[", "'data'", "]", "# If the message is a call invoke, run the function and send", "# the results.", "if", "'callback'", "in", "data", ":", "guid", "=", "data", "[",...
Handle messages from the front-end
[ "Handle", "messages", "from", "the", "front", "-", "end" ]
2f74703f59926d8565f9714b1458dc87da8f8574
https://github.com/genepattern/nbtools/blob/2f74703f59926d8565f9714b1458dc87da8f8574/nbtools/jsobject/jsobject.py#L60-L87
train
48,948
genepattern/nbtools
nbtools/jsobject/jsobject.py
BrowserContext.serialize
def serialize(self, obj): """Serialize an object for sending to the front-end.""" if hasattr(obj, '_jsid'): return {'immutable': False, 'value': obj._jsid} else: obj_json = {'immutable': True} try: json.dumps(obj) obj_json['value'] = obj except: pass if callable(obj): guid = str(uuid.uuid4()) callback_registry[guid] = obj obj_json['callback'] = guid return obj_json
python
def serialize(self, obj): """Serialize an object for sending to the front-end.""" if hasattr(obj, '_jsid'): return {'immutable': False, 'value': obj._jsid} else: obj_json = {'immutable': True} try: json.dumps(obj) obj_json['value'] = obj except: pass if callable(obj): guid = str(uuid.uuid4()) callback_registry[guid] = obj obj_json['callback'] = guid return obj_json
[ "def", "serialize", "(", "self", ",", "obj", ")", ":", "if", "hasattr", "(", "obj", ",", "'_jsid'", ")", ":", "return", "{", "'immutable'", ":", "False", ",", "'value'", ":", "obj", ".", "_jsid", "}", "else", ":", "obj_json", "=", "{", "'immutable'",...
Serialize an object for sending to the front-end.
[ "Serialize", "an", "object", "for", "sending", "to", "the", "front", "-", "end", "." ]
2f74703f59926d8565f9714b1458dc87da8f8574
https://github.com/genepattern/nbtools/blob/2f74703f59926d8565f9714b1458dc87da8f8574/nbtools/jsobject/jsobject.py#L89-L104
train
48,949
genepattern/nbtools
nbtools/jsobject/jsobject.py
BrowserContext.deserialize
def deserialize(self, obj): """Deserialize an object from the front-end.""" if obj['immutable']: return obj['value'] else: guid = obj['value'] if not guid in object_registry: instance = JSObject(self, guid) object_registry[guid] = instance return object_registry[guid]
python
def deserialize(self, obj): """Deserialize an object from the front-end.""" if obj['immutable']: return obj['value'] else: guid = obj['value'] if not guid in object_registry: instance = JSObject(self, guid) object_registry[guid] = instance return object_registry[guid]
[ "def", "deserialize", "(", "self", ",", "obj", ")", ":", "if", "obj", "[", "'immutable'", "]", ":", "return", "obj", "[", "'value'", "]", "else", ":", "guid", "=", "obj", "[", "'value'", "]", "if", "not", "guid", "in", "object_registry", ":", "instan...
Deserialize an object from the front-end.
[ "Deserialize", "an", "object", "from", "the", "front", "-", "end", "." ]
2f74703f59926d8565f9714b1458dc87da8f8574
https://github.com/genepattern/nbtools/blob/2f74703f59926d8565f9714b1458dc87da8f8574/nbtools/jsobject/jsobject.py#L106-L115
train
48,950
genepattern/nbtools
nbtools/jsobject/jsobject.py
BrowserContext._send
def _send(self, method, **parameters): """Sends a message to the front-end and returns a promise.""" msg = { 'index': self._calls, 'method': method, } msg.update(parameters) promise = SimplePromise() self._callbacks[self._calls] = promise self._calls += 1 self._comm.send(msg) return promise
python
def _send(self, method, **parameters): """Sends a message to the front-end and returns a promise.""" msg = { 'index': self._calls, 'method': method, } msg.update(parameters) promise = SimplePromise() self._callbacks[self._calls] = promise self._calls += 1 self._comm.send(msg) return promise
[ "def", "_send", "(", "self", ",", "method", ",", "*", "*", "parameters", ")", ":", "msg", "=", "{", "'index'", ":", "self", ".", "_calls", ",", "'method'", ":", "method", ",", "}", "msg", ".", "update", "(", "parameters", ")", "promise", "=", "Simp...
Sends a message to the front-end and returns a promise.
[ "Sends", "a", "message", "to", "the", "front", "-", "end", "and", "returns", "a", "promise", "." ]
2f74703f59926d8565f9714b1458dc87da8f8574
https://github.com/genepattern/nbtools/blob/2f74703f59926d8565f9714b1458dc87da8f8574/nbtools/jsobject/jsobject.py#L127-L141
train
48,951
LordGaav/python-chaos
chaos/amqp/rpc.py
Rpc.register_response
def register_response(self, correlation_id=None): """ Register the receiving of a RPC response. Will return the given correlation_id after registering, or if correlation_id is None, will generate a correlation_id and return it after registering. If the given correlation_id has already been used, an KeyError will be raised. UUID version 1 will be used when generating correlation_ids. Depending on the underlying system and implementation, this will guarantee that generated values are unique between workers. At least CPython guarantees this behaviour. Parameters ---------- correlation_id: string Identifier under which to expect a RPC callback. If None, a correlation_id will be generated. """ if not correlation_id: correlation_id = str(uuid.uuid1()) if correlation_id in self.responses: raise KeyError("Correlation_id {0} was already registered, and therefor not unique.".format(correlation_id)) self.responses[correlation_id] = None return correlation_id
python
def register_response(self, correlation_id=None): """ Register the receiving of a RPC response. Will return the given correlation_id after registering, or if correlation_id is None, will generate a correlation_id and return it after registering. If the given correlation_id has already been used, an KeyError will be raised. UUID version 1 will be used when generating correlation_ids. Depending on the underlying system and implementation, this will guarantee that generated values are unique between workers. At least CPython guarantees this behaviour. Parameters ---------- correlation_id: string Identifier under which to expect a RPC callback. If None, a correlation_id will be generated. """ if not correlation_id: correlation_id = str(uuid.uuid1()) if correlation_id in self.responses: raise KeyError("Correlation_id {0} was already registered, and therefor not unique.".format(correlation_id)) self.responses[correlation_id] = None return correlation_id
[ "def", "register_response", "(", "self", ",", "correlation_id", "=", "None", ")", ":", "if", "not", "correlation_id", ":", "correlation_id", "=", "str", "(", "uuid", ".", "uuid1", "(", ")", ")", "if", "correlation_id", "in", "self", ".", "responses", ":", ...
Register the receiving of a RPC response. Will return the given correlation_id after registering, or if correlation_id is None, will generate a correlation_id and return it after registering. If the given correlation_id has already been used, an KeyError will be raised. UUID version 1 will be used when generating correlation_ids. Depending on the underlying system and implementation, this will guarantee that generated values are unique between workers. At least CPython guarantees this behaviour. Parameters ---------- correlation_id: string Identifier under which to expect a RPC callback. If None, a correlation_id will be generated.
[ "Register", "the", "receiving", "of", "a", "RPC", "response", ".", "Will", "return", "the", "given", "correlation_id", "after", "registering", "or", "if", "correlation_id", "is", "None", "will", "generate", "a", "correlation_id", "and", "return", "it", "after", ...
52cd29a6fd15693ee1e53786b93bcb23fbf84ddd
https://github.com/LordGaav/python-chaos/blob/52cd29a6fd15693ee1e53786b93bcb23fbf84ddd/chaos/amqp/rpc.py#L169-L191
train
48,952
LordGaav/python-chaos
chaos/amqp/rpc.py
Rpc.retrieve_response
def retrieve_response(self, correlation_id): """ Retrieve a registered RPC response. If the correlation_id was not registered, an KeyError will the raised. If not value has been received yet, None will be returned. After retrieving the response, the value will be unset internally. The returned value will include the entire RabbitMQ message, consisting of a dict with the following keys: method_frame: dict Information about the message header_frame: dict Headers of the message body: string Body of the message Parameters ---------- correlation_id: string Identifier to retrieve the RPC response for """ if correlation_id not in self.responses: raise KeyError("Given RPC response correlation_id was not registered.") if not self.responses[correlation_id]: return None response = self.responses[correlation_id] del(self.responses[correlation_id]) return response
python
def retrieve_response(self, correlation_id): """ Retrieve a registered RPC response. If the correlation_id was not registered, an KeyError will the raised. If not value has been received yet, None will be returned. After retrieving the response, the value will be unset internally. The returned value will include the entire RabbitMQ message, consisting of a dict with the following keys: method_frame: dict Information about the message header_frame: dict Headers of the message body: string Body of the message Parameters ---------- correlation_id: string Identifier to retrieve the RPC response for """ if correlation_id not in self.responses: raise KeyError("Given RPC response correlation_id was not registered.") if not self.responses[correlation_id]: return None response = self.responses[correlation_id] del(self.responses[correlation_id]) return response
[ "def", "retrieve_response", "(", "self", ",", "correlation_id", ")", ":", "if", "correlation_id", "not", "in", "self", ".", "responses", ":", "raise", "KeyError", "(", "\"Given RPC response correlation_id was not registered.\"", ")", "if", "not", "self", ".", "respo...
Retrieve a registered RPC response. If the correlation_id was not registered, an KeyError will the raised. If not value has been received yet, None will be returned. After retrieving the response, the value will be unset internally. The returned value will include the entire RabbitMQ message, consisting of a dict with the following keys: method_frame: dict Information about the message header_frame: dict Headers of the message body: string Body of the message Parameters ---------- correlation_id: string Identifier to retrieve the RPC response for
[ "Retrieve", "a", "registered", "RPC", "response", ".", "If", "the", "correlation_id", "was", "not", "registered", "an", "KeyError", "will", "the", "raised", ".", "If", "not", "value", "has", "been", "received", "yet", "None", "will", "be", "returned", ".", ...
52cd29a6fd15693ee1e53786b93bcb23fbf84ddd
https://github.com/LordGaav/python-chaos/blob/52cd29a6fd15693ee1e53786b93bcb23fbf84ddd/chaos/amqp/rpc.py#L199-L225
train
48,953
LordGaav/python-chaos
chaos/amqp/rpc.py
Rpc.request_response
def request_response(self, exchange, routing_key, message, properties=None, correlation_id=None, timeout=6): """ This function wraps publish, and sets the properties necessary to allow end-to-end communication using the Rpc paradigm. This function assumes that the named exchange and routing_key combination will result in a AMQP queue to pickup the request, and reply using another AMQP message. To achieve this, the following properties are set, along with any custom properties: * correlation_id: a correlation_id is generated using register_response. It is assumed that the responding service will also provide the same id in the response. * reply_to: this is set to the internal RPC queue name, so we can pickup responses. The mandatory bit will be set on the message as a mechanism to detect if the message was delivered to a queue. This is to avoid needlessly waiting on a reply, when the message wasn't delivered in the first place. Parameters ---------- exchange: string Exchange to publish to. routing_key: string Routing key to use for this message. message: string Message to publish. properties: dict Properties to set on message. This parameter is optional, but if set, at least the following options must be set: content_type: string - what content_type to specify, default is 'text/plain'. delivery_mode: int - what delivery_mode to use. By default message are not persistent, but this can be set by specifying PERSISTENT_MESSAGE . correlation_id: string Custom correlation_id. This identifier is subject to the same semantics and logic as register_response(). timeout: int How many seconds to wait for a reply. If no reply is received, an MessageDeliveryTimeout is raised. Set to False to wait forever. """ if not properties: properties = {} properties['correlation_id'] = self.register_response(correlation_id) properties['reply_to'] = self.rpc_queue_name if not self.publish(exchange, routing_key, message, properties, mandatory=True): self.retrieve_response(properties['correlation_id']) raise MessageNotDelivered("Message was not delivered to a queue") start = int(time.time()) ## Newer versions of pika (>v0.10) don't have a force_data_events any more if hasattr(self.channel, "force_data_events"): self.channel.force_data_events(True) while properties['correlation_id'] not in self.retrieve_available_responses(): self.connection.process_data_events() if timeout and (int(time.time()) - start) > timeout: self.retrieve_response(properties['correlation_id']) raise MessageDeliveryTimeout("No response received from RPC server within specified period") return self.retrieve_response(properties['correlation_id'])
python
def request_response(self, exchange, routing_key, message, properties=None, correlation_id=None, timeout=6): """ This function wraps publish, and sets the properties necessary to allow end-to-end communication using the Rpc paradigm. This function assumes that the named exchange and routing_key combination will result in a AMQP queue to pickup the request, and reply using another AMQP message. To achieve this, the following properties are set, along with any custom properties: * correlation_id: a correlation_id is generated using register_response. It is assumed that the responding service will also provide the same id in the response. * reply_to: this is set to the internal RPC queue name, so we can pickup responses. The mandatory bit will be set on the message as a mechanism to detect if the message was delivered to a queue. This is to avoid needlessly waiting on a reply, when the message wasn't delivered in the first place. Parameters ---------- exchange: string Exchange to publish to. routing_key: string Routing key to use for this message. message: string Message to publish. properties: dict Properties to set on message. This parameter is optional, but if set, at least the following options must be set: content_type: string - what content_type to specify, default is 'text/plain'. delivery_mode: int - what delivery_mode to use. By default message are not persistent, but this can be set by specifying PERSISTENT_MESSAGE . correlation_id: string Custom correlation_id. This identifier is subject to the same semantics and logic as register_response(). timeout: int How many seconds to wait for a reply. If no reply is received, an MessageDeliveryTimeout is raised. Set to False to wait forever. """ if not properties: properties = {} properties['correlation_id'] = self.register_response(correlation_id) properties['reply_to'] = self.rpc_queue_name if not self.publish(exchange, routing_key, message, properties, mandatory=True): self.retrieve_response(properties['correlation_id']) raise MessageNotDelivered("Message was not delivered to a queue") start = int(time.time()) ## Newer versions of pika (>v0.10) don't have a force_data_events any more if hasattr(self.channel, "force_data_events"): self.channel.force_data_events(True) while properties['correlation_id'] not in self.retrieve_available_responses(): self.connection.process_data_events() if timeout and (int(time.time()) - start) > timeout: self.retrieve_response(properties['correlation_id']) raise MessageDeliveryTimeout("No response received from RPC server within specified period") return self.retrieve_response(properties['correlation_id'])
[ "def", "request_response", "(", "self", ",", "exchange", ",", "routing_key", ",", "message", ",", "properties", "=", "None", ",", "correlation_id", "=", "None", ",", "timeout", "=", "6", ")", ":", "if", "not", "properties", ":", "properties", "=", "{", "...
This function wraps publish, and sets the properties necessary to allow end-to-end communication using the Rpc paradigm. This function assumes that the named exchange and routing_key combination will result in a AMQP queue to pickup the request, and reply using another AMQP message. To achieve this, the following properties are set, along with any custom properties: * correlation_id: a correlation_id is generated using register_response. It is assumed that the responding service will also provide the same id in the response. * reply_to: this is set to the internal RPC queue name, so we can pickup responses. The mandatory bit will be set on the message as a mechanism to detect if the message was delivered to a queue. This is to avoid needlessly waiting on a reply, when the message wasn't delivered in the first place. Parameters ---------- exchange: string Exchange to publish to. routing_key: string Routing key to use for this message. message: string Message to publish. properties: dict Properties to set on message. This parameter is optional, but if set, at least the following options must be set: content_type: string - what content_type to specify, default is 'text/plain'. delivery_mode: int - what delivery_mode to use. By default message are not persistent, but this can be set by specifying PERSISTENT_MESSAGE . correlation_id: string Custom correlation_id. This identifier is subject to the same semantics and logic as register_response(). timeout: int How many seconds to wait for a reply. If no reply is received, an MessageDeliveryTimeout is raised. Set to False to wait forever.
[ "This", "function", "wraps", "publish", "and", "sets", "the", "properties", "necessary", "to", "allow", "end", "-", "to", "-", "end", "communication", "using", "the", "Rpc", "paradigm", "." ]
52cd29a6fd15693ee1e53786b93bcb23fbf84ddd
https://github.com/LordGaav/python-chaos/blob/52cd29a6fd15693ee1e53786b93bcb23fbf84ddd/chaos/amqp/rpc.py#L227-L280
train
48,954
mishbahr/django-usersettings2
usersettings/models.py
UserSettingsManager.get_current
def get_current(self): """ Returns the current ``UserSettings`` based on the SITE_ID in the project's settings. The ``UserSettings`` object is cached the first time it's retrieved from the database. """ from django.conf import settings try: site_id = settings.SITE_ID except AttributeError: raise ImproperlyConfigured( 'You\'re using the Django "sites framework" without having ' 'set the SITE_ID setting. Create a site in your database and ' 'set the SITE_ID setting to fix this error.') try: current_usersettings = USERSETTINGS_CACHE[site_id] except KeyError: current_usersettings = self.get(site_id=site_id) USERSETTINGS_CACHE[site_id] = current_usersettings return current_usersettings
python
def get_current(self): """ Returns the current ``UserSettings`` based on the SITE_ID in the project's settings. The ``UserSettings`` object is cached the first time it's retrieved from the database. """ from django.conf import settings try: site_id = settings.SITE_ID except AttributeError: raise ImproperlyConfigured( 'You\'re using the Django "sites framework" without having ' 'set the SITE_ID setting. Create a site in your database and ' 'set the SITE_ID setting to fix this error.') try: current_usersettings = USERSETTINGS_CACHE[site_id] except KeyError: current_usersettings = self.get(site_id=site_id) USERSETTINGS_CACHE[site_id] = current_usersettings return current_usersettings
[ "def", "get_current", "(", "self", ")", ":", "from", "django", ".", "conf", "import", "settings", "try", ":", "site_id", "=", "settings", ".", "SITE_ID", "except", "AttributeError", ":", "raise", "ImproperlyConfigured", "(", "'You\\'re using the Django \"sites frame...
Returns the current ``UserSettings`` based on the SITE_ID in the project's settings. The ``UserSettings`` object is cached the first time it's retrieved from the database.
[ "Returns", "the", "current", "UserSettings", "based", "on", "the", "SITE_ID", "in", "the", "project", "s", "settings", ".", "The", "UserSettings", "object", "is", "cached", "the", "first", "time", "it", "s", "retrieved", "from", "the", "database", "." ]
cbc2f4b2e01d5401bec8a3fa39151730cd2dcd2a
https://github.com/mishbahr/django-usersettings2/blob/cbc2f4b2e01d5401bec8a3fa39151730cd2dcd2a/usersettings/models.py#L22-L42
train
48,955
unfoldingWord-dev/python-gogs-client
gogs_client/_implementation/http_utils.py
append_url
def append_url(base_url, path): """ Append path to base_url in a sensible way. """ if base_url[-1] != "/": base_url += "/" if path[0] == "/": path = path[1:] return urljoin(base_url, path)
python
def append_url(base_url, path): """ Append path to base_url in a sensible way. """ if base_url[-1] != "/": base_url += "/" if path[0] == "/": path = path[1:] return urljoin(base_url, path)
[ "def", "append_url", "(", "base_url", ",", "path", ")", ":", "if", "base_url", "[", "-", "1", "]", "!=", "\"/\"", ":", "base_url", "+=", "\"/\"", "if", "path", "[", "0", "]", "==", "\"/\"", ":", "path", "=", "path", "[", "1", ":", "]", "return", ...
Append path to base_url in a sensible way.
[ "Append", "path", "to", "base_url", "in", "a", "sensible", "way", "." ]
b7f27f4995abf914c0db8a424760f5b27331939d
https://github.com/unfoldingWord-dev/python-gogs-client/blob/b7f27f4995abf914c0db8a424760f5b27331939d/gogs_client/_implementation/http_utils.py#L49-L57
train
48,956
hyperboria/python-cjdns
cjdns/cjdns.py
_randomString
def _randomString(): """Random string for message signing""" return ''.join( random.choice(string.ascii_uppercase + string.digits) for x in range(10))
python
def _randomString(): """Random string for message signing""" return ''.join( random.choice(string.ascii_uppercase + string.digits) for x in range(10))
[ "def", "_randomString", "(", ")", ":", "return", "''", ".", "join", "(", "random", ".", "choice", "(", "string", ".", "ascii_uppercase", "+", "string", ".", "digits", ")", "for", "x", "in", "range", "(", "10", ")", ")" ]
Random string for message signing
[ "Random", "string", "for", "message", "signing" ]
a9ae5d6d2e99c18f9fc50a9589729cd176efa900
https://github.com/hyperboria/python-cjdns/blob/a9ae5d6d2e99c18f9fc50a9589729cd176efa900/cjdns/cjdns.py#L63-L68
train
48,957
hyperboria/python-cjdns
cjdns/cjdns.py
_callFunc
def _callFunc(session, funcName, password, args): """Call custom cjdns admin function""" txid = _randomString() sock = session.socket sock.send(bytearray('d1:q6:cookie4:txid10:%se' % txid, 'utf-8')) msg = _getMessage(session, txid) cookie = msg['cookie'] txid = _randomString() tohash = (password + cookie).encode('utf-8') req = { 'q': funcName, 'hash': hashlib.sha256(tohash).hexdigest(), 'cookie': cookie, 'args': args, 'txid': txid } if password: req['aq'] = req['q'] req['q'] = 'auth' reqBenc = bencode(req).encode('utf-8') req['hash'] = hashlib.sha256(reqBenc).hexdigest() reqBenc = bencode(req) sock.send(bytearray(reqBenc, 'utf-8')) return _getMessage(session, txid)
python
def _callFunc(session, funcName, password, args): """Call custom cjdns admin function""" txid = _randomString() sock = session.socket sock.send(bytearray('d1:q6:cookie4:txid10:%se' % txid, 'utf-8')) msg = _getMessage(session, txid) cookie = msg['cookie'] txid = _randomString() tohash = (password + cookie).encode('utf-8') req = { 'q': funcName, 'hash': hashlib.sha256(tohash).hexdigest(), 'cookie': cookie, 'args': args, 'txid': txid } if password: req['aq'] = req['q'] req['q'] = 'auth' reqBenc = bencode(req).encode('utf-8') req['hash'] = hashlib.sha256(reqBenc).hexdigest() reqBenc = bencode(req) sock.send(bytearray(reqBenc, 'utf-8')) return _getMessage(session, txid)
[ "def", "_callFunc", "(", "session", ",", "funcName", ",", "password", ",", "args", ")", ":", "txid", "=", "_randomString", "(", ")", "sock", "=", "session", ".", "socket", "sock", ".", "send", "(", "bytearray", "(", "'d1:q6:cookie4:txid10:%se'", "%", "txid...
Call custom cjdns admin function
[ "Call", "custom", "cjdns", "admin", "function" ]
a9ae5d6d2e99c18f9fc50a9589729cd176efa900
https://github.com/hyperboria/python-cjdns/blob/a9ae5d6d2e99c18f9fc50a9589729cd176efa900/cjdns/cjdns.py#L71-L97
train
48,958
hyperboria/python-cjdns
cjdns/cjdns.py
_receiverThread
def _receiverThread(session): """Receiving messages from cjdns admin server""" timeOfLastSend = time.time() timeOfLastRecv = time.time() try: while True: if timeOfLastSend + KEEPALIVE_INTERVAL_SECONDS < time.time(): if timeOfLastRecv + 10 < time.time(): raise exceptions.PingTimeout() session.socket.send( b'd1:q18:Admin_asyncEnabled4:txid8:keepalive') timeOfLastSend = time.time() try: data = session.socket.recv(BUFFER_SIZE) except socket.timeout: continue try: benc = bdecode(data) except (KeyError, ValueError): logger.error("error decoding [%s]", data) continue if benc['txid'] == 'keepaliv': if benc['asyncEnabled'] == 0: raise exceptions.SessionLost() timeOfLastRecv = time.time() else: session.queue.put(benc) except KeyboardInterrupt: logger.exception("interrupted") import thread thread.interrupt_main()
python
def _receiverThread(session): """Receiving messages from cjdns admin server""" timeOfLastSend = time.time() timeOfLastRecv = time.time() try: while True: if timeOfLastSend + KEEPALIVE_INTERVAL_SECONDS < time.time(): if timeOfLastRecv + 10 < time.time(): raise exceptions.PingTimeout() session.socket.send( b'd1:q18:Admin_asyncEnabled4:txid8:keepalive') timeOfLastSend = time.time() try: data = session.socket.recv(BUFFER_SIZE) except socket.timeout: continue try: benc = bdecode(data) except (KeyError, ValueError): logger.error("error decoding [%s]", data) continue if benc['txid'] == 'keepaliv': if benc['asyncEnabled'] == 0: raise exceptions.SessionLost() timeOfLastRecv = time.time() else: session.queue.put(benc) except KeyboardInterrupt: logger.exception("interrupted") import thread thread.interrupt_main()
[ "def", "_receiverThread", "(", "session", ")", ":", "timeOfLastSend", "=", "time", ".", "time", "(", ")", "timeOfLastRecv", "=", "time", ".", "time", "(", ")", "try", ":", "while", "True", ":", "if", "timeOfLastSend", "+", "KEEPALIVE_INTERVAL_SECONDS", "<", ...
Receiving messages from cjdns admin server
[ "Receiving", "messages", "from", "cjdns", "admin", "server" ]
a9ae5d6d2e99c18f9fc50a9589729cd176efa900
https://github.com/hyperboria/python-cjdns/blob/a9ae5d6d2e99c18f9fc50a9589729cd176efa900/cjdns/cjdns.py#L100-L135
train
48,959
hyperboria/python-cjdns
cjdns/cjdns.py
_getMessage
def _getMessage(session, txid): """Getting message associated with txid""" while True: if txid in session.messages: msg = session.messages[txid] del session.messages[txid] return msg else: try: # apparently any timeout at all allows the thread to be # stopped but none make it unstoppable with ctrl+c nextMessage = session.queue.get(timeout=100) except queue.Empty: continue if 'txid' in nextMessage: session.messages[nextMessage['txid']] = nextMessage else: logger.info("message with no txid: %s" % nextMessage)
python
def _getMessage(session, txid): """Getting message associated with txid""" while True: if txid in session.messages: msg = session.messages[txid] del session.messages[txid] return msg else: try: # apparently any timeout at all allows the thread to be # stopped but none make it unstoppable with ctrl+c nextMessage = session.queue.get(timeout=100) except queue.Empty: continue if 'txid' in nextMessage: session.messages[nextMessage['txid']] = nextMessage else: logger.info("message with no txid: %s" % nextMessage)
[ "def", "_getMessage", "(", "session", ",", "txid", ")", ":", "while", "True", ":", "if", "txid", "in", "session", ".", "messages", ":", "msg", "=", "session", ".", "messages", "[", "txid", "]", "del", "session", ".", "messages", "[", "txid", "]", "re...
Getting message associated with txid
[ "Getting", "message", "associated", "with", "txid" ]
a9ae5d6d2e99c18f9fc50a9589729cd176efa900
https://github.com/hyperboria/python-cjdns/blob/a9ae5d6d2e99c18f9fc50a9589729cd176efa900/cjdns/cjdns.py#L138-L156
train
48,960
hyperboria/python-cjdns
cjdns/cjdns.py
_functionFabric
def _functionFabric(func_name, argList, oargList, password): """Function fabric for Session class""" def functionHandler(self, *args, **kwargs): call_args = {} for (key, value) in oargList.items(): call_args[key] = value for i, arg in enumerate(argList): if i < len(args): call_args[arg] = args[i] for (key, value) in kwargs.items(): call_args[key] = value return _callFunc(self, func_name, password, call_args) functionHandler.__name__ = str(func_name) return functionHandler
python
def _functionFabric(func_name, argList, oargList, password): """Function fabric for Session class""" def functionHandler(self, *args, **kwargs): call_args = {} for (key, value) in oargList.items(): call_args[key] = value for i, arg in enumerate(argList): if i < len(args): call_args[arg] = args[i] for (key, value) in kwargs.items(): call_args[key] = value return _callFunc(self, func_name, password, call_args) functionHandler.__name__ = str(func_name) return functionHandler
[ "def", "_functionFabric", "(", "func_name", ",", "argList", ",", "oargList", ",", "password", ")", ":", "def", "functionHandler", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "call_args", "=", "{", "}", "for", "(", "key", ",", "v...
Function fabric for Session class
[ "Function", "fabric", "for", "Session", "class" ]
a9ae5d6d2e99c18f9fc50a9589729cd176efa900
https://github.com/hyperboria/python-cjdns/blob/a9ae5d6d2e99c18f9fc50a9589729cd176efa900/cjdns/cjdns.py#L159-L178
train
48,961
hyperboria/python-cjdns
cjdns/cjdns.py
connect
def connect(ipAddr, port, password): """Connect to cjdns admin with this attributes""" sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.connect((ipAddr, port)) sock.settimeout(2) # Make sure it pongs. sock.send(b'd1:q4:pinge') data = sock.recv(BUFFER_SIZE) if not data.endswith(b'1:q4:ponge'): raise exceptions.NotACjdnsAdminSocket("Looks like %s:%d is to a non-cjdns socket.", (ipAddr, port)) # Get the functions and make the object page = 0 availableFunctions = {} while True: sock.send(bytearray( 'd1:q24:Admin_availableFunctions4:argsd4:pagei%seee' % page, 'utf-8')) data = sock.recv(BUFFER_SIZE) benc = bdecode(data) for func in benc['availableFunctions']: availableFunctions[func] = benc['availableFunctions'][func] if 'more' not in benc: break page = page+1 funcArgs = {} funcOargs = {} for (i, func) in availableFunctions.items(): items = func.items() # grab all the required args first # append all the optional args rargList = [arg for arg, atts in items if atts['required']] argList = rargList + [ arg for arg, atts in items if not atts['required']] # for each optional arg setup a default value with # a type which will be ignored by the core. oargList = {} for (arg, atts) in items: if not atts['required']: oargList[arg] = ( "''" if func[arg]['type'] == 'Int' else "") setattr(Session, i, _functionFabric( i, argList, oargList, password)) funcArgs[i] = rargList funcOargs[i] = oargList session = Session(sock) kat = threading.Thread(target=_receiverThread, args=[session]) kat.setDaemon(True) kat.start() # Check our password. ret = _callFunc(session, "ping", password, {}) if 'error' in ret: raise exceptions.InvalidAdminPassword(ret.get("error")) session._functions = "" funcOargs_c = {} for func in funcOargs: funcOargs_c[func] = list([ key + "=" + str(value) for (key, value) in funcOargs[func].items() ]) for func in availableFunctions: session._functions += ( func + "(" + ', '.join(funcArgs[func] + funcOargs_c[func]) + ")\n") return session
python
def connect(ipAddr, port, password): """Connect to cjdns admin with this attributes""" sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.connect((ipAddr, port)) sock.settimeout(2) # Make sure it pongs. sock.send(b'd1:q4:pinge') data = sock.recv(BUFFER_SIZE) if not data.endswith(b'1:q4:ponge'): raise exceptions.NotACjdnsAdminSocket("Looks like %s:%d is to a non-cjdns socket.", (ipAddr, port)) # Get the functions and make the object page = 0 availableFunctions = {} while True: sock.send(bytearray( 'd1:q24:Admin_availableFunctions4:argsd4:pagei%seee' % page, 'utf-8')) data = sock.recv(BUFFER_SIZE) benc = bdecode(data) for func in benc['availableFunctions']: availableFunctions[func] = benc['availableFunctions'][func] if 'more' not in benc: break page = page+1 funcArgs = {} funcOargs = {} for (i, func) in availableFunctions.items(): items = func.items() # grab all the required args first # append all the optional args rargList = [arg for arg, atts in items if atts['required']] argList = rargList + [ arg for arg, atts in items if not atts['required']] # for each optional arg setup a default value with # a type which will be ignored by the core. oargList = {} for (arg, atts) in items: if not atts['required']: oargList[arg] = ( "''" if func[arg]['type'] == 'Int' else "") setattr(Session, i, _functionFabric( i, argList, oargList, password)) funcArgs[i] = rargList funcOargs[i] = oargList session = Session(sock) kat = threading.Thread(target=_receiverThread, args=[session]) kat.setDaemon(True) kat.start() # Check our password. ret = _callFunc(session, "ping", password, {}) if 'error' in ret: raise exceptions.InvalidAdminPassword(ret.get("error")) session._functions = "" funcOargs_c = {} for func in funcOargs: funcOargs_c[func] = list([ key + "=" + str(value) for (key, value) in funcOargs[func].items() ]) for func in availableFunctions: session._functions += ( func + "(" + ', '.join(funcArgs[func] + funcOargs_c[func]) + ")\n") return session
[ "def", "connect", "(", "ipAddr", ",", "port", ",", "password", ")", ":", "sock", "=", "socket", ".", "socket", "(", "socket", ".", "AF_INET", ",", "socket", ".", "SOCK_DGRAM", ")", "sock", ".", "connect", "(", "(", "ipAddr", ",", "port", ")", ")", ...
Connect to cjdns admin with this attributes
[ "Connect", "to", "cjdns", "admin", "with", "this", "attributes" ]
a9ae5d6d2e99c18f9fc50a9589729cd176efa900
https://github.com/hyperboria/python-cjdns/blob/a9ae5d6d2e99c18f9fc50a9589729cd176efa900/cjdns/cjdns.py#L181-L260
train
48,962
hyperboria/python-cjdns
cjdns/cjdns.py
connectWithAdminInfo
def connectWithAdminInfo(path=None): """Connect to cjdns admin with data from user file""" if path is None: path = os.path.expanduser('~/.cjdnsadmin') try: with open(path, 'r') as adminInfo: data = json.load(adminInfo) except IOError: logger.info('~/.cjdnsadmin not found; using default credentials', file=sys.stderr) data = { 'password': 'NONE', 'addr': '127.0.0.1', 'port': 11234, } return connect(data['addr'], data['port'], data['password'])
python
def connectWithAdminInfo(path=None): """Connect to cjdns admin with data from user file""" if path is None: path = os.path.expanduser('~/.cjdnsadmin') try: with open(path, 'r') as adminInfo: data = json.load(adminInfo) except IOError: logger.info('~/.cjdnsadmin not found; using default credentials', file=sys.stderr) data = { 'password': 'NONE', 'addr': '127.0.0.1', 'port': 11234, } return connect(data['addr'], data['port'], data['password'])
[ "def", "connectWithAdminInfo", "(", "path", "=", "None", ")", ":", "if", "path", "is", "None", ":", "path", "=", "os", ".", "path", ".", "expanduser", "(", "'~/.cjdnsadmin'", ")", "try", ":", "with", "open", "(", "path", ",", "'r'", ")", "as", "admin...
Connect to cjdns admin with data from user file
[ "Connect", "to", "cjdns", "admin", "with", "data", "from", "user", "file" ]
a9ae5d6d2e99c18f9fc50a9589729cd176efa900
https://github.com/hyperboria/python-cjdns/blob/a9ae5d6d2e99c18f9fc50a9589729cd176efa900/cjdns/cjdns.py#L263-L279
train
48,963
jeremymcrae/denovonear
denovonear/__main__.py
get_options
def get_options(): """ get the command line switches """ parser = argparse.ArgumentParser(description='denovonear cli interface') ############################################################################ # CLI options in common parent = argparse.ArgumentParser(add_help=False) parent.add_argument("--out", help="output filename") parent.add_argument("--rates", help="Path to file containing sequence context-based mutation rates.") parent.add_argument("--genome-build", choices=["grch37", "GRCh37", "grch38", "GRCh38"], default="grch37", help="Genome build " "that the de novo coordinates are based on (GRCh37 or GRCh38") parent.add_argument("--cache-folder", default=os.path.join(os.path.expanduser('~'), ".cache", 'denovonear'), help="where to cache Ensembl data (default is ~/.cache/denovonear)") subparsers = parser.add_subparsers() ############################################################################ # CLI options for clustering cluster = subparsers.add_parser('cluster', parents=[parent], description="Tests the proximity of de novo mutations in genes.") cluster.add_argument("--in", dest="input", required=True, help="Path to " "file listing known mutations in genes. See example file in data folder " "for format.") cluster.set_defaults(func=clustering) ############################################################################ # CLI options for identifing transcripts to use transcripts = subparsers.add_parser('transcripts', parents=[parent], description="Identify transcripts for a gene containing de novo events.") transcripts.add_argument("--de-novos", required=True, help="Path to " "file listing de novo variants in genes.") transcripts.set_defaults(func=find_transcripts) group = transcripts.add_mutually_exclusive_group(required=True) group.add_argument("--all-transcripts", action="store_true", default=False, help="Flag if you want to identify all transcripts with more than " "one de novo on it.") group.add_argument("--minimise-transcripts", action="store_true", default=False, help="Flag if you want to identify the minimal set of " "transcripts to contain all de novos.") ############################################################################ # CLI options for identifing transcripts to use rater = subparsers.add_parser("rates", parents=[parent], description="determine mutation rates for genes given transcript IDs.") rater.add_argument("--genes", help="Path to file " "listing HGNC symbols, with one or more transcript IDs per gene. " "The tab-separated input format is gene symbol followed by transcript " "ID. Alternative transcripts are listed on separate lines.") rater.set_defaults(func=gene_rates) args = parser.parse_args() if 'func' not in args: print('Use one of the subcommands: cluster, rates, or transcripts\n') parser.print_help() sys.exit() return args
python
def get_options(): """ get the command line switches """ parser = argparse.ArgumentParser(description='denovonear cli interface') ############################################################################ # CLI options in common parent = argparse.ArgumentParser(add_help=False) parent.add_argument("--out", help="output filename") parent.add_argument("--rates", help="Path to file containing sequence context-based mutation rates.") parent.add_argument("--genome-build", choices=["grch37", "GRCh37", "grch38", "GRCh38"], default="grch37", help="Genome build " "that the de novo coordinates are based on (GRCh37 or GRCh38") parent.add_argument("--cache-folder", default=os.path.join(os.path.expanduser('~'), ".cache", 'denovonear'), help="where to cache Ensembl data (default is ~/.cache/denovonear)") subparsers = parser.add_subparsers() ############################################################################ # CLI options for clustering cluster = subparsers.add_parser('cluster', parents=[parent], description="Tests the proximity of de novo mutations in genes.") cluster.add_argument("--in", dest="input", required=True, help="Path to " "file listing known mutations in genes. See example file in data folder " "for format.") cluster.set_defaults(func=clustering) ############################################################################ # CLI options for identifing transcripts to use transcripts = subparsers.add_parser('transcripts', parents=[parent], description="Identify transcripts for a gene containing de novo events.") transcripts.add_argument("--de-novos", required=True, help="Path to " "file listing de novo variants in genes.") transcripts.set_defaults(func=find_transcripts) group = transcripts.add_mutually_exclusive_group(required=True) group.add_argument("--all-transcripts", action="store_true", default=False, help="Flag if you want to identify all transcripts with more than " "one de novo on it.") group.add_argument("--minimise-transcripts", action="store_true", default=False, help="Flag if you want to identify the minimal set of " "transcripts to contain all de novos.") ############################################################################ # CLI options for identifing transcripts to use rater = subparsers.add_parser("rates", parents=[parent], description="determine mutation rates for genes given transcript IDs.") rater.add_argument("--genes", help="Path to file " "listing HGNC symbols, with one or more transcript IDs per gene. " "The tab-separated input format is gene symbol followed by transcript " "ID. Alternative transcripts are listed on separate lines.") rater.set_defaults(func=gene_rates) args = parser.parse_args() if 'func' not in args: print('Use one of the subcommands: cluster, rates, or transcripts\n') parser.print_help() sys.exit() return args
[ "def", "get_options", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "'denovonear cli interface'", ")", "############################################################################", "# CLI options in common", "parent", "=", "argparse...
get the command line switches
[ "get", "the", "command", "line", "switches" ]
feaab0fc77e89d70b31e8092899e4f0e68bac9fe
https://github.com/jeremymcrae/denovonear/blob/feaab0fc77e89d70b31e8092899e4f0e68bac9fe/denovonear/__main__.py#L159-L221
train
48,964
hyperboria/python-cjdns
cjdns/key_utils.py
to_ipv6
def to_ipv6(key): """Get IPv6 address from a public key.""" if key[-2:] != '.k': raise ValueError('Key does not end with .k') key_bytes = base32.decode(key[:-2]) hash_one = sha512(key_bytes).digest() hash_two = sha512(hash_one).hexdigest() return ':'.join([hash_two[i:i+4] for i in range(0, 32, 4)])
python
def to_ipv6(key): """Get IPv6 address from a public key.""" if key[-2:] != '.k': raise ValueError('Key does not end with .k') key_bytes = base32.decode(key[:-2]) hash_one = sha512(key_bytes).digest() hash_two = sha512(hash_one).hexdigest() return ':'.join([hash_two[i:i+4] for i in range(0, 32, 4)])
[ "def", "to_ipv6", "(", "key", ")", ":", "if", "key", "[", "-", "2", ":", "]", "!=", "'.k'", ":", "raise", "ValueError", "(", "'Key does not end with .k'", ")", "key_bytes", "=", "base32", ".", "decode", "(", "key", "[", ":", "-", "2", "]", ")", "ha...
Get IPv6 address from a public key.
[ "Get", "IPv6", "address", "from", "a", "public", "key", "." ]
a9ae5d6d2e99c18f9fc50a9589729cd176efa900
https://github.com/hyperboria/python-cjdns/blob/a9ae5d6d2e99c18f9fc50a9589729cd176efa900/cjdns/key_utils.py#L18-L28
train
48,965
LordGaav/python-chaos
chaos/globber.py
Globber.glob
def glob(self): """ Traverse directory, and return all absolute filenames of files that match the globbing patterns. """ matches = [] for root, dirnames, filenames in os.walk(self.path): if not self.recursive: while len(dirnames) > 0: dirnames.pop() for include in self.include: for filename in fnmatch.filter(filenames, include): matches.append(os.path.join(root, filename)) return matches
python
def glob(self): """ Traverse directory, and return all absolute filenames of files that match the globbing patterns. """ matches = [] for root, dirnames, filenames in os.walk(self.path): if not self.recursive: while len(dirnames) > 0: dirnames.pop() for include in self.include: for filename in fnmatch.filter(filenames, include): matches.append(os.path.join(root, filename)) return matches
[ "def", "glob", "(", "self", ")", ":", "matches", "=", "[", "]", "for", "root", ",", "dirnames", ",", "filenames", "in", "os", ".", "walk", "(", "self", ".", "path", ")", ":", "if", "not", "self", ".", "recursive", ":", "while", "len", "(", "dirna...
Traverse directory, and return all absolute filenames of files that match the globbing patterns.
[ "Traverse", "directory", "and", "return", "all", "absolute", "filenames", "of", "files", "that", "match", "the", "globbing", "patterns", "." ]
52cd29a6fd15693ee1e53786b93bcb23fbf84ddd
https://github.com/LordGaav/python-chaos/blob/52cd29a6fd15693ee1e53786b93bcb23fbf84ddd/chaos/globber.py#L49-L62
train
48,966
mishbahr/django-usersettings2
usersettings/admin.py
SettingsAdmin.select_site_view
def select_site_view(self, request, form_url=''): """ Display a choice form to select which site to add settings. """ if not self.has_add_permission(request): raise PermissionDenied extra_qs = '' if request.META['QUERY_STRING']: extra_qs = '&' + request.META['QUERY_STRING'] site_choices = self.get_site_choices() if len(site_choices) == 1: return HttpResponseRedirect('?site_id={0}{1}'.format(site_choices[0][0], extra_qs)) # Create form form = self.select_site_form( data=request.POST if request.method == 'POST' else None, initial={'site': site_choices[0][0]} ) form.fields['site'].choices = site_choices if form.is_valid(): return HttpResponseRedirect( '?site_id={0}{1}'.format(form.cleaned_data['site'], extra_qs)) # Wrap in all admin layout fieldsets = ((None, {'fields': ('site',)}),) adminForm = AdminForm(form, fieldsets, {}, model_admin=self) media = self.media + adminForm.media context = { 'title': _('Add %s') % force_text(self.opts.verbose_name), 'adminform': adminForm, 'is_popup': '_popup' in request.GET, 'media': mark_safe(media), 'errors': AdminErrorList(form, ()), 'app_label': self.opts.app_label, } return self.render_select_site_form(request, context, form_url)
python
def select_site_view(self, request, form_url=''): """ Display a choice form to select which site to add settings. """ if not self.has_add_permission(request): raise PermissionDenied extra_qs = '' if request.META['QUERY_STRING']: extra_qs = '&' + request.META['QUERY_STRING'] site_choices = self.get_site_choices() if len(site_choices) == 1: return HttpResponseRedirect('?site_id={0}{1}'.format(site_choices[0][0], extra_qs)) # Create form form = self.select_site_form( data=request.POST if request.method == 'POST' else None, initial={'site': site_choices[0][0]} ) form.fields['site'].choices = site_choices if form.is_valid(): return HttpResponseRedirect( '?site_id={0}{1}'.format(form.cleaned_data['site'], extra_qs)) # Wrap in all admin layout fieldsets = ((None, {'fields': ('site',)}),) adminForm = AdminForm(form, fieldsets, {}, model_admin=self) media = self.media + adminForm.media context = { 'title': _('Add %s') % force_text(self.opts.verbose_name), 'adminform': adminForm, 'is_popup': '_popup' in request.GET, 'media': mark_safe(media), 'errors': AdminErrorList(form, ()), 'app_label': self.opts.app_label, } return self.render_select_site_form(request, context, form_url)
[ "def", "select_site_view", "(", "self", ",", "request", ",", "form_url", "=", "''", ")", ":", "if", "not", "self", ".", "has_add_permission", "(", "request", ")", ":", "raise", "PermissionDenied", "extra_qs", "=", "''", "if", "request", ".", "META", "[", ...
Display a choice form to select which site to add settings.
[ "Display", "a", "choice", "form", "to", "select", "which", "site", "to", "add", "settings", "." ]
cbc2f4b2e01d5401bec8a3fa39151730cd2dcd2a
https://github.com/mishbahr/django-usersettings2/blob/cbc2f4b2e01d5401bec8a3fa39151730cd2dcd2a/usersettings/admin.py#L84-L126
train
48,967
mishbahr/django-usersettings2
usersettings/admin.py
SettingsAdmin.render_select_site_form
def render_select_site_form(self, request, context, form_url=''): """ Render the site choice form. """ app_label = self.opts.app_label context.update({ 'has_change_permission': self.has_change_permission(request), 'form_url': mark_safe(form_url), 'opts': self.opts, 'add': True, 'save_on_top': self.save_on_top, }) return render_to_response(self.select_site_form_template or [ 'admin/%s/%s/select_site_form.html' % (app_label, self.opts.object_name.lower()), 'admin/%s/select_site_form.html' % app_label, 'admin/usersettings/select_site_form.html', # added default here 'admin/select_site_form.html' ], context)
python
def render_select_site_form(self, request, context, form_url=''): """ Render the site choice form. """ app_label = self.opts.app_label context.update({ 'has_change_permission': self.has_change_permission(request), 'form_url': mark_safe(form_url), 'opts': self.opts, 'add': True, 'save_on_top': self.save_on_top, }) return render_to_response(self.select_site_form_template or [ 'admin/%s/%s/select_site_form.html' % (app_label, self.opts.object_name.lower()), 'admin/%s/select_site_form.html' % app_label, 'admin/usersettings/select_site_form.html', # added default here 'admin/select_site_form.html' ], context)
[ "def", "render_select_site_form", "(", "self", ",", "request", ",", "context", ",", "form_url", "=", "''", ")", ":", "app_label", "=", "self", ".", "opts", ".", "app_label", "context", ".", "update", "(", "{", "'has_change_permission'", ":", "self", ".", "...
Render the site choice form.
[ "Render", "the", "site", "choice", "form", "." ]
cbc2f4b2e01d5401bec8a3fa39151730cd2dcd2a
https://github.com/mishbahr/django-usersettings2/blob/cbc2f4b2e01d5401bec8a3fa39151730cd2dcd2a/usersettings/admin.py#L128-L146
train
48,968
ReadabilityHoldings/python-readability-api
readability/auth.py
xauth
def xauth(base_url_template=DEFAULT_READER_URL_TEMPLATE, **xargs): """ Returns an OAuth token tuple that can be used with clients.ReaderClient. :param base_url_template: Template for generating Readability API urls. :param consumer_key: Readability consumer key, otherwise read from READABILITY_CONSUMER_KEY. :param consumer_secret: Readability consumer secret, otherwise read from READABILITY_CONSUMER_SECRET. :param username: A username, otherwise read from READABILITY_USERNAME. :param password: A password, otherwise read from READABILITY_PASSWORD. """ consumer_key = xargs.get('consumer_key') or required_from_env('READABILITY_CONSUMER_KEY') consumer_secret = xargs.get('consumer_secret') or required_from_env('READABILITY_CONSUMER_SECRET') username = xargs.get('username') or required_from_env('READABILITY_USERNAME') password = xargs.get('password') or required_from_env('READABILITY_PASSWORD') client = Client(consumer_key, client_secret=consumer_secret, signature_type='BODY') url = base_url_template.format(ACCESS_TOKEN_URL) headers = {'Content-Type': 'application/x-www-form-urlencoded'} params = { 'x_auth_username': username, 'x_auth_password': password, 'x_auth_mode': 'client_auth' } uri, headers, body = client.sign(url, http_method='POST', body=urlencode(params), headers=headers) response = requests.post(uri, data=body) logger.debug('POST to %s.', uri) token = parse_qs(response.content) try: # The indexes below are a little weird. parse_qs above gives us # back a dict where each value is a list. We want the first value # in those lists. token = (token[b'oauth_token'][0].decode(), token[b'oauth_token_secret'][0].decode()) except KeyError: raise ValueError('Invalid Credentials.') return token
python
def xauth(base_url_template=DEFAULT_READER_URL_TEMPLATE, **xargs): """ Returns an OAuth token tuple that can be used with clients.ReaderClient. :param base_url_template: Template for generating Readability API urls. :param consumer_key: Readability consumer key, otherwise read from READABILITY_CONSUMER_KEY. :param consumer_secret: Readability consumer secret, otherwise read from READABILITY_CONSUMER_SECRET. :param username: A username, otherwise read from READABILITY_USERNAME. :param password: A password, otherwise read from READABILITY_PASSWORD. """ consumer_key = xargs.get('consumer_key') or required_from_env('READABILITY_CONSUMER_KEY') consumer_secret = xargs.get('consumer_secret') or required_from_env('READABILITY_CONSUMER_SECRET') username = xargs.get('username') or required_from_env('READABILITY_USERNAME') password = xargs.get('password') or required_from_env('READABILITY_PASSWORD') client = Client(consumer_key, client_secret=consumer_secret, signature_type='BODY') url = base_url_template.format(ACCESS_TOKEN_URL) headers = {'Content-Type': 'application/x-www-form-urlencoded'} params = { 'x_auth_username': username, 'x_auth_password': password, 'x_auth_mode': 'client_auth' } uri, headers, body = client.sign(url, http_method='POST', body=urlencode(params), headers=headers) response = requests.post(uri, data=body) logger.debug('POST to %s.', uri) token = parse_qs(response.content) try: # The indexes below are a little weird. parse_qs above gives us # back a dict where each value is a list. We want the first value # in those lists. token = (token[b'oauth_token'][0].decode(), token[b'oauth_token_secret'][0].decode()) except KeyError: raise ValueError('Invalid Credentials.') return token
[ "def", "xauth", "(", "base_url_template", "=", "DEFAULT_READER_URL_TEMPLATE", ",", "*", "*", "xargs", ")", ":", "consumer_key", "=", "xargs", ".", "get", "(", "'consumer_key'", ")", "or", "required_from_env", "(", "'READABILITY_CONSUMER_KEY'", ")", "consumer_secret"...
Returns an OAuth token tuple that can be used with clients.ReaderClient. :param base_url_template: Template for generating Readability API urls. :param consumer_key: Readability consumer key, otherwise read from READABILITY_CONSUMER_KEY. :param consumer_secret: Readability consumer secret, otherwise read from READABILITY_CONSUMER_SECRET. :param username: A username, otherwise read from READABILITY_USERNAME. :param password: A password, otherwise read from READABILITY_PASSWORD.
[ "Returns", "an", "OAuth", "token", "tuple", "that", "can", "be", "used", "with", "clients", ".", "ReaderClient", "." ]
4b746166877d5a8dc29222aedccb18c2506a5385
https://github.com/ReadabilityHoldings/python-readability-api/blob/4b746166877d5a8dc29222aedccb18c2506a5385/readability/auth.py#L37-L79
train
48,969
jeremymcrae/denovonear
denovonear/log_transform_rates.py
log_transform
def log_transform(rates): """ log transform a numeric value, unless it is zero, or negative """ transformed = [] for key in ['missense', 'nonsense', 'splice_lof', 'splice_region', 'synonymous']: try: value = math.log10(rates[key]) except ValueError: value = "NA" except KeyError: continue transformed.append(value) return '\t'.join(map(str, transformed))
python
def log_transform(rates): """ log transform a numeric value, unless it is zero, or negative """ transformed = [] for key in ['missense', 'nonsense', 'splice_lof', 'splice_region', 'synonymous']: try: value = math.log10(rates[key]) except ValueError: value = "NA" except KeyError: continue transformed.append(value) return '\t'.join(map(str, transformed))
[ "def", "log_transform", "(", "rates", ")", ":", "transformed", "=", "[", "]", "for", "key", "in", "[", "'missense'", ",", "'nonsense'", ",", "'splice_lof'", ",", "'splice_region'", ",", "'synonymous'", "]", ":", "try", ":", "value", "=", "math", ".", "lo...
log transform a numeric value, unless it is zero, or negative
[ "log", "transform", "a", "numeric", "value", "unless", "it", "is", "zero", "or", "negative" ]
feaab0fc77e89d70b31e8092899e4f0e68bac9fe
https://github.com/jeremymcrae/denovonear/blob/feaab0fc77e89d70b31e8092899e4f0e68bac9fe/denovonear/log_transform_rates.py#L4-L21
train
48,970
mishbahr/django-usersettings2
usersettings/shortcuts.py
get_usersettings_model
def get_usersettings_model(): """ Returns the ``UserSettings`` model that is active in this project. """ try: from django.apps import apps get_model = apps.get_model except ImportError: from django.db.models.loading import get_model try: app_label, model_name = settings.USERSETTINGS_MODEL.split('.') except ValueError: raise ImproperlyConfigured('USERSETTINGS_MODEL must be of the ' 'form "app_label.model_name"') usersettings_model = get_model(app_label, model_name) if usersettings_model is None: raise ImproperlyConfigured('USERSETTINGS_MODEL refers to model "%s" that has ' 'not been installed' % settings.USERSETTINGS_MODEL) return usersettings_model
python
def get_usersettings_model(): """ Returns the ``UserSettings`` model that is active in this project. """ try: from django.apps import apps get_model = apps.get_model except ImportError: from django.db.models.loading import get_model try: app_label, model_name = settings.USERSETTINGS_MODEL.split('.') except ValueError: raise ImproperlyConfigured('USERSETTINGS_MODEL must be of the ' 'form "app_label.model_name"') usersettings_model = get_model(app_label, model_name) if usersettings_model is None: raise ImproperlyConfigured('USERSETTINGS_MODEL refers to model "%s" that has ' 'not been installed' % settings.USERSETTINGS_MODEL) return usersettings_model
[ "def", "get_usersettings_model", "(", ")", ":", "try", ":", "from", "django", ".", "apps", "import", "apps", "get_model", "=", "apps", ".", "get_model", "except", "ImportError", ":", "from", "django", ".", "db", ".", "models", ".", "loading", "import", "ge...
Returns the ``UserSettings`` model that is active in this project.
[ "Returns", "the", "UserSettings", "model", "that", "is", "active", "in", "this", "project", "." ]
cbc2f4b2e01d5401bec8a3fa39151730cd2dcd2a
https://github.com/mishbahr/django-usersettings2/blob/cbc2f4b2e01d5401bec8a3fa39151730cd2dcd2a/usersettings/shortcuts.py#L5-L24
train
48,971
mishbahr/django-usersettings2
usersettings/shortcuts.py
get_current_usersettings
def get_current_usersettings(): """ Returns the current ``UserSettings`` based on the SITE_ID in the project's settings """ USERSETTINGS_MODEL = get_usersettings_model() try: current_usersettings = USERSETTINGS_MODEL.objects.get_current() except USERSETTINGS_MODEL.DoesNotExist: current_usersettings = USERSETTINGS_MODEL.get_default() return current_usersettings
python
def get_current_usersettings(): """ Returns the current ``UserSettings`` based on the SITE_ID in the project's settings """ USERSETTINGS_MODEL = get_usersettings_model() try: current_usersettings = USERSETTINGS_MODEL.objects.get_current() except USERSETTINGS_MODEL.DoesNotExist: current_usersettings = USERSETTINGS_MODEL.get_default() return current_usersettings
[ "def", "get_current_usersettings", "(", ")", ":", "USERSETTINGS_MODEL", "=", "get_usersettings_model", "(", ")", "try", ":", "current_usersettings", "=", "USERSETTINGS_MODEL", ".", "objects", ".", "get_current", "(", ")", "except", "USERSETTINGS_MODEL", ".", "DoesNotE...
Returns the current ``UserSettings`` based on the SITE_ID in the project's settings
[ "Returns", "the", "current", "UserSettings", "based", "on", "the", "SITE_ID", "in", "the", "project", "s", "settings" ]
cbc2f4b2e01d5401bec8a3fa39151730cd2dcd2a
https://github.com/mishbahr/django-usersettings2/blob/cbc2f4b2e01d5401bec8a3fa39151730cd2dcd2a/usersettings/shortcuts.py#L27-L37
train
48,972
jeremymcrae/denovonear
scripts/run_batch.py
get_options
def get_options(): """ get the command line options """ parser = argparse.ArgumentParser(description="Script to batch process de" "novo clustering.") parser.add_argument("--in", dest="input", required=True, help="Path to" "file listing known mutations in genes. See example file in data folder" "for format.") parser.add_argument("--temp-dir", required=True, help="path to hold intermediate files") parser.add_argument("--out", required=True, help="Path to output file.") args = parser.parse_args() return args
python
def get_options(): """ get the command line options """ parser = argparse.ArgumentParser(description="Script to batch process de" "novo clustering.") parser.add_argument("--in", dest="input", required=True, help="Path to" "file listing known mutations in genes. See example file in data folder" "for format.") parser.add_argument("--temp-dir", required=True, help="path to hold intermediate files") parser.add_argument("--out", required=True, help="Path to output file.") args = parser.parse_args() return args
[ "def", "get_options", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "\"Script to batch process de\"", "\"novo clustering.\"", ")", "parser", ".", "add_argument", "(", "\"--in\"", ",", "dest", "=", "\"input\"", ",", "requ...
get the command line options
[ "get", "the", "command", "line", "options" ]
feaab0fc77e89d70b31e8092899e4f0e68bac9fe
https://github.com/jeremymcrae/denovonear/blob/feaab0fc77e89d70b31e8092899e4f0e68bac9fe/scripts/run_batch.py#L11-L25
train
48,973
jeremymcrae/denovonear
scripts/run_batch.py
count_missense_per_gene
def count_missense_per_gene(lines): """ count the number of missense variants in each gene. """ counts = {} for x in lines: x = x.split("\t") gene = x[0] consequence = x[3] if gene not in counts: counts[gene] = 0 if consequence != "missense_variant": continue counts[gene] += 1 return counts
python
def count_missense_per_gene(lines): """ count the number of missense variants in each gene. """ counts = {} for x in lines: x = x.split("\t") gene = x[0] consequence = x[3] if gene not in counts: counts[gene] = 0 if consequence != "missense_variant": continue counts[gene] += 1 return counts
[ "def", "count_missense_per_gene", "(", "lines", ")", ":", "counts", "=", "{", "}", "for", "x", "in", "lines", ":", "x", "=", "x", ".", "split", "(", "\"\\t\"", ")", "gene", "=", "x", "[", "0", "]", "consequence", "=", "x", "[", "3", "]", "if", ...
count the number of missense variants in each gene.
[ "count", "the", "number", "of", "missense", "variants", "in", "each", "gene", "." ]
feaab0fc77e89d70b31e8092899e4f0e68bac9fe
https://github.com/jeremymcrae/denovonear/blob/feaab0fc77e89d70b31e8092899e4f0e68bac9fe/scripts/run_batch.py#L27-L45
train
48,974
jeremymcrae/denovonear
scripts/run_batch.py
split_denovos
def split_denovos(denovo_path, temp_dir): """ split de novos from an input file into files, one for each gene """ # open the de novos, drop the header line, then sort them (which will be by # HGNC symbol, as the first element of each line) with open(denovo_path, "r") as handle: lines = handle.readlines() header = lines.pop(0) basename = os.path.basename(denovo_path) # only include genes with 2+ missense SNVs counts = count_missense_per_gene(lines) counts = dict((k, v) for k, v in counts.items() if v > 1 ) genes = set([]) for line in sorted(lines): gene = line.split("\t")[0] # open a new output file whenever we hit a different gene if gene not in genes and gene in counts: genes.add(gene) path = os.path.join(temp_dir, "tmp.{}.txt".format(len(genes))) output = open(path, "w") output.write(header) if gene in counts: output.write(line) return len(genes)
python
def split_denovos(denovo_path, temp_dir): """ split de novos from an input file into files, one for each gene """ # open the de novos, drop the header line, then sort them (which will be by # HGNC symbol, as the first element of each line) with open(denovo_path, "r") as handle: lines = handle.readlines() header = lines.pop(0) basename = os.path.basename(denovo_path) # only include genes with 2+ missense SNVs counts = count_missense_per_gene(lines) counts = dict((k, v) for k, v in counts.items() if v > 1 ) genes = set([]) for line in sorted(lines): gene = line.split("\t")[0] # open a new output file whenever we hit a different gene if gene not in genes and gene in counts: genes.add(gene) path = os.path.join(temp_dir, "tmp.{}.txt".format(len(genes))) output = open(path, "w") output.write(header) if gene in counts: output.write(line) return len(genes)
[ "def", "split_denovos", "(", "denovo_path", ",", "temp_dir", ")", ":", "# open the de novos, drop the header line, then sort them (which will be by", "# HGNC symbol, as the first element of each line)", "with", "open", "(", "denovo_path", ",", "\"r\"", ")", "as", "handle", ":",...
split de novos from an input file into files, one for each gene
[ "split", "de", "novos", "from", "an", "input", "file", "into", "files", "one", "for", "each", "gene" ]
feaab0fc77e89d70b31e8092899e4f0e68bac9fe
https://github.com/jeremymcrae/denovonear/blob/feaab0fc77e89d70b31e8092899e4f0e68bac9fe/scripts/run_batch.py#L47-L77
train
48,975
jeremymcrae/denovonear
scripts/run_batch.py
get_random_string
def get_random_string(): """ make a random string, which we can use for bsub job IDs, so that different jobs do not have the same job IDs. """ # set up a random string to associate with the run hash_string = "%8x" % random.getrandbits(32) hash_string = hash_string.strip() # done't allow the random strings to be equivalent to a number, since # the LSF cluster interprets those differently from letter-containing # strings while is_number(hash_string): hash_string = "%8x" % random.getrandbits(32) hash_string = hash_string.strip() return hash_string
python
def get_random_string(): """ make a random string, which we can use for bsub job IDs, so that different jobs do not have the same job IDs. """ # set up a random string to associate with the run hash_string = "%8x" % random.getrandbits(32) hash_string = hash_string.strip() # done't allow the random strings to be equivalent to a number, since # the LSF cluster interprets those differently from letter-containing # strings while is_number(hash_string): hash_string = "%8x" % random.getrandbits(32) hash_string = hash_string.strip() return hash_string
[ "def", "get_random_string", "(", ")", ":", "# set up a random string to associate with the run", "hash_string", "=", "\"%8x\"", "%", "random", ".", "getrandbits", "(", "32", ")", "hash_string", "=", "hash_string", ".", "strip", "(", ")", "# done't allow the random strin...
make a random string, which we can use for bsub job IDs, so that different jobs do not have the same job IDs.
[ "make", "a", "random", "string", "which", "we", "can", "use", "for", "bsub", "job", "IDs", "so", "that", "different", "jobs", "do", "not", "have", "the", "same", "job", "IDs", "." ]
feaab0fc77e89d70b31e8092899e4f0e68bac9fe
https://github.com/jeremymcrae/denovonear/blob/feaab0fc77e89d70b31e8092899e4f0e68bac9fe/scripts/run_batch.py#L96-L112
train
48,976
jeremymcrae/denovonear
scripts/run_batch.py
batch_process
def batch_process(de_novo_path, temp_dir, output_path): """ sets up a lsf job array """ temp_dir = tempfile.mkdtemp(dir=temp_dir) count = split_denovos(de_novo_path, temp_dir) # set up run parameters job_name = "denovonear" job_id = "{0}[1-{1}]%20".format(job_name, count) basename = os.path.basename(de_novo_path) infile = os.path.join(temp_dir, "tmp.\$LSB_JOBINDEX\.txt") outfile = os.path.join(temp_dir, "tmp.\$LSB_JOBINDEX\.output") command = ["denovonear", "cluster", "--in", infile, "--out", outfile] submit_bsub_job(command, job_id, memory=3500, requeue_code=134, logfile="clustering.bjob") time.sleep(2) # merge the array output after the array finishes merge_id = "{}_merge".format(job_name) command = ["head", "-n", "1", os.path.join(temp_dir, "tmp.1.output"), ">", output_path, \ "; tail", "-q", "-n", "+2", os.path.join(temp_dir, "tmp.*.output"), "|", "sort", ">>", output_path] submit_bsub_job(command, merge_id, memory=100, dependent_id=job_id, logfile="clustering.bjob") time.sleep(2) # submit a cleanup job to the cluster submit_bsub_job(["rm", "-r", temp_dir], job_id="{}_cleanup".format(job_name), \ memory=100, dependent_id=merge_id, logfile="clustering.bjob")
python
def batch_process(de_novo_path, temp_dir, output_path): """ sets up a lsf job array """ temp_dir = tempfile.mkdtemp(dir=temp_dir) count = split_denovos(de_novo_path, temp_dir) # set up run parameters job_name = "denovonear" job_id = "{0}[1-{1}]%20".format(job_name, count) basename = os.path.basename(de_novo_path) infile = os.path.join(temp_dir, "tmp.\$LSB_JOBINDEX\.txt") outfile = os.path.join(temp_dir, "tmp.\$LSB_JOBINDEX\.output") command = ["denovonear", "cluster", "--in", infile, "--out", outfile] submit_bsub_job(command, job_id, memory=3500, requeue_code=134, logfile="clustering.bjob") time.sleep(2) # merge the array output after the array finishes merge_id = "{}_merge".format(job_name) command = ["head", "-n", "1", os.path.join(temp_dir, "tmp.1.output"), ">", output_path, \ "; tail", "-q", "-n", "+2", os.path.join(temp_dir, "tmp.*.output"), "|", "sort", ">>", output_path] submit_bsub_job(command, merge_id, memory=100, dependent_id=job_id, logfile="clustering.bjob") time.sleep(2) # submit a cleanup job to the cluster submit_bsub_job(["rm", "-r", temp_dir], job_id="{}_cleanup".format(job_name), \ memory=100, dependent_id=merge_id, logfile="clustering.bjob")
[ "def", "batch_process", "(", "de_novo_path", ",", "temp_dir", ",", "output_path", ")", ":", "temp_dir", "=", "tempfile", ".", "mkdtemp", "(", "dir", "=", "temp_dir", ")", "count", "=", "split_denovos", "(", "de_novo_path", ",", "temp_dir", ")", "# set up run p...
sets up a lsf job array
[ "sets", "up", "a", "lsf", "job", "array" ]
feaab0fc77e89d70b31e8092899e4f0e68bac9fe
https://github.com/jeremymcrae/denovonear/blob/feaab0fc77e89d70b31e8092899e4f0e68bac9fe/scripts/run_batch.py#L158-L188
train
48,977
unfoldingWord-dev/python-gogs-client
gogs_client/interface.py
GogsApi.authenticated_user
def authenticated_user(self, auth): """ Returns the user authenticated by ``auth`` :param auth.Authentication auth: authentication for user to retrieve :return: user authenticated by the provided authentication :rtype: GogsUser :raises NetworkFailure: if there is an error communicating with the server :raises ApiFailure: if the request cannot be serviced """ response = self.get("/user", auth=auth) return GogsUser.from_json(response.json())
python
def authenticated_user(self, auth): """ Returns the user authenticated by ``auth`` :param auth.Authentication auth: authentication for user to retrieve :return: user authenticated by the provided authentication :rtype: GogsUser :raises NetworkFailure: if there is an error communicating with the server :raises ApiFailure: if the request cannot be serviced """ response = self.get("/user", auth=auth) return GogsUser.from_json(response.json())
[ "def", "authenticated_user", "(", "self", ",", "auth", ")", ":", "response", "=", "self", ".", "get", "(", "\"/user\"", ",", "auth", "=", "auth", ")", "return", "GogsUser", ".", "from_json", "(", "response", ".", "json", "(", ")", ")" ]
Returns the user authenticated by ``auth`` :param auth.Authentication auth: authentication for user to retrieve :return: user authenticated by the provided authentication :rtype: GogsUser :raises NetworkFailure: if there is an error communicating with the server :raises ApiFailure: if the request cannot be serviced
[ "Returns", "the", "user", "authenticated", "by", "auth" ]
b7f27f4995abf914c0db8a424760f5b27331939d
https://github.com/unfoldingWord-dev/python-gogs-client/blob/b7f27f4995abf914c0db8a424760f5b27331939d/gogs_client/interface.py#L33-L45
train
48,978
unfoldingWord-dev/python-gogs-client
gogs_client/interface.py
GogsApi.get_tokens
def get_tokens(self, auth, username=None): """ Returns the tokens owned by the specified user. If no user is specified, uses the user authenticated by ``auth``. :param auth.Authentication auth: authentication for user to retrieve. Must be a username-password authentication, due to a restriction of the Gogs API :param str username: username of owner of tokens :return: list of tokens :rtype: List[Token] :raises NetworkFailure: if there is an error communicating with the server :raises ApiFailure: if the request cannot be serviced """ if username is None: username = self.authenticated_user(auth).username response = self.get("/users/{u}/tokens".format(u=username), auth=auth) return [Token.from_json(o) for o in response.json()]
python
def get_tokens(self, auth, username=None): """ Returns the tokens owned by the specified user. If no user is specified, uses the user authenticated by ``auth``. :param auth.Authentication auth: authentication for user to retrieve. Must be a username-password authentication, due to a restriction of the Gogs API :param str username: username of owner of tokens :return: list of tokens :rtype: List[Token] :raises NetworkFailure: if there is an error communicating with the server :raises ApiFailure: if the request cannot be serviced """ if username is None: username = self.authenticated_user(auth).username response = self.get("/users/{u}/tokens".format(u=username), auth=auth) return [Token.from_json(o) for o in response.json()]
[ "def", "get_tokens", "(", "self", ",", "auth", ",", "username", "=", "None", ")", ":", "if", "username", "is", "None", ":", "username", "=", "self", ".", "authenticated_user", "(", "auth", ")", ".", "username", "response", "=", "self", ".", "get", "(",...
Returns the tokens owned by the specified user. If no user is specified, uses the user authenticated by ``auth``. :param auth.Authentication auth: authentication for user to retrieve. Must be a username-password authentication, due to a restriction of the Gogs API :param str username: username of owner of tokens :return: list of tokens :rtype: List[Token] :raises NetworkFailure: if there is an error communicating with the server :raises ApiFailure: if the request cannot be serviced
[ "Returns", "the", "tokens", "owned", "by", "the", "specified", "user", ".", "If", "no", "user", "is", "specified", "uses", "the", "user", "authenticated", "by", "auth", "." ]
b7f27f4995abf914c0db8a424760f5b27331939d
https://github.com/unfoldingWord-dev/python-gogs-client/blob/b7f27f4995abf914c0db8a424760f5b27331939d/gogs_client/interface.py#L47-L65
train
48,979
unfoldingWord-dev/python-gogs-client
gogs_client/interface.py
GogsApi.create_token
def create_token(self, auth, name, username=None): """ Creates a new token with the specified name for the specified user. If no user is specified, uses user authenticated by ``auth``. :param auth.Authentication auth: authentication for user to retrieve. Must be a username-password authentication, due to a restriction of the Gogs API :param str name: name of new token :param str username: username of owner of new token :return: new token representation :rtype: Token :raises NetworkFailure: if there is an error communicating with the server :raises ApiFailure: if the request cannot be serviced """ if username is None: username = self.authenticated_user(auth).username data = {"name": name} response = self.post("/users/{u}/tokens".format(u=username), auth=auth, data=data) return Token.from_json(response.json())
python
def create_token(self, auth, name, username=None): """ Creates a new token with the specified name for the specified user. If no user is specified, uses user authenticated by ``auth``. :param auth.Authentication auth: authentication for user to retrieve. Must be a username-password authentication, due to a restriction of the Gogs API :param str name: name of new token :param str username: username of owner of new token :return: new token representation :rtype: Token :raises NetworkFailure: if there is an error communicating with the server :raises ApiFailure: if the request cannot be serviced """ if username is None: username = self.authenticated_user(auth).username data = {"name": name} response = self.post("/users/{u}/tokens".format(u=username), auth=auth, data=data) return Token.from_json(response.json())
[ "def", "create_token", "(", "self", ",", "auth", ",", "name", ",", "username", "=", "None", ")", ":", "if", "username", "is", "None", ":", "username", "=", "self", ".", "authenticated_user", "(", "auth", ")", ".", "username", "data", "=", "{", "\"name\...
Creates a new token with the specified name for the specified user. If no user is specified, uses user authenticated by ``auth``. :param auth.Authentication auth: authentication for user to retrieve. Must be a username-password authentication, due to a restriction of the Gogs API :param str name: name of new token :param str username: username of owner of new token :return: new token representation :rtype: Token :raises NetworkFailure: if there is an error communicating with the server :raises ApiFailure: if the request cannot be serviced
[ "Creates", "a", "new", "token", "with", "the", "specified", "name", "for", "the", "specified", "user", ".", "If", "no", "user", "is", "specified", "uses", "user", "authenticated", "by", "auth", "." ]
b7f27f4995abf914c0db8a424760f5b27331939d
https://github.com/unfoldingWord-dev/python-gogs-client/blob/b7f27f4995abf914c0db8a424760f5b27331939d/gogs_client/interface.py#L67-L87
train
48,980
unfoldingWord-dev/python-gogs-client
gogs_client/interface.py
GogsApi.ensure_token
def ensure_token(self, auth, name, username=None): """ Ensures the existence of a token with the specified name for the specified user. Creates a new token if none exists. If no user is specified, uses user authenticated by ``auth``. :param auth.Authentication auth: authentication for user to retrieve. Must be a username-password authentication, due to a restriction of the Gogs API :param str name: name of new token :param str username: username of owner of new token :return: token representation :rtype: Token :raises NetworkFailure: if there is an error communicating with the server :raises ApiFailure: if the request cannot be serviced """ if username is None: username = self.authenticated_user(auth).username tokens = [token for token in self.get_tokens(auth, username) if token.name == name] if len(tokens) > 0: return tokens[0] return self.create_token(auth, name, username)
python
def ensure_token(self, auth, name, username=None): """ Ensures the existence of a token with the specified name for the specified user. Creates a new token if none exists. If no user is specified, uses user authenticated by ``auth``. :param auth.Authentication auth: authentication for user to retrieve. Must be a username-password authentication, due to a restriction of the Gogs API :param str name: name of new token :param str username: username of owner of new token :return: token representation :rtype: Token :raises NetworkFailure: if there is an error communicating with the server :raises ApiFailure: if the request cannot be serviced """ if username is None: username = self.authenticated_user(auth).username tokens = [token for token in self.get_tokens(auth, username) if token.name == name] if len(tokens) > 0: return tokens[0] return self.create_token(auth, name, username)
[ "def", "ensure_token", "(", "self", ",", "auth", ",", "name", ",", "username", "=", "None", ")", ":", "if", "username", "is", "None", ":", "username", "=", "self", ".", "authenticated_user", "(", "auth", ")", ".", "username", "tokens", "=", "[", "token...
Ensures the existence of a token with the specified name for the specified user. Creates a new token if none exists. If no user is specified, uses user authenticated by ``auth``. :param auth.Authentication auth: authentication for user to retrieve. Must be a username-password authentication, due to a restriction of the Gogs API :param str name: name of new token :param str username: username of owner of new token :return: token representation :rtype: Token :raises NetworkFailure: if there is an error communicating with the server :raises ApiFailure: if the request cannot be serviced
[ "Ensures", "the", "existence", "of", "a", "token", "with", "the", "specified", "name", "for", "the", "specified", "user", ".", "Creates", "a", "new", "token", "if", "none", "exists", ".", "If", "no", "user", "is", "specified", "uses", "user", "authenticate...
b7f27f4995abf914c0db8a424760f5b27331939d
https://github.com/unfoldingWord-dev/python-gogs-client/blob/b7f27f4995abf914c0db8a424760f5b27331939d/gogs_client/interface.py#L89-L111
train
48,981
unfoldingWord-dev/python-gogs-client
gogs_client/interface.py
GogsApi.create_repo
def create_repo(self, auth, name, description=None, private=False, auto_init=False, gitignore_templates=None, license_template=None, readme_template=None, organization=None): """ Creates a new repository, and returns the created repository. :param auth.Authentication auth: authentication object :param str name: name of the repository to create :param str description: description of the repository to create :param bool private: whether the create repository should be private :param bool auto_init: whether the created repository should be auto-initialized with an initial commit :param list[str] gitignore_templates: collection of ``.gitignore`` templates to apply :param str license_template: license template to apply :param str readme_template: README template to apply :param str organization: organization under which repository is created :return: a representation of the created repository :rtype: GogsRepo :raises NetworkFailure: if there is an error communicating with the server :raises ApiFailure: if the request cannot be serviced """ gitignores = None if gitignore_templates is None \ else ",".join(gitignore_templates) data = { "name": name, "description": description, "private": private, "auto_init": auto_init, "gitignores": gitignores, "license": license_template, "readme": readme_template } data = {k: v for (k, v) in data.items() if v is not None} url = "/org/{0}/repos".format(organization) if organization else "/user/repos" response = self.post(url, auth=auth, data=data) return GogsRepo.from_json(response.json())
python
def create_repo(self, auth, name, description=None, private=False, auto_init=False, gitignore_templates=None, license_template=None, readme_template=None, organization=None): """ Creates a new repository, and returns the created repository. :param auth.Authentication auth: authentication object :param str name: name of the repository to create :param str description: description of the repository to create :param bool private: whether the create repository should be private :param bool auto_init: whether the created repository should be auto-initialized with an initial commit :param list[str] gitignore_templates: collection of ``.gitignore`` templates to apply :param str license_template: license template to apply :param str readme_template: README template to apply :param str organization: organization under which repository is created :return: a representation of the created repository :rtype: GogsRepo :raises NetworkFailure: if there is an error communicating with the server :raises ApiFailure: if the request cannot be serviced """ gitignores = None if gitignore_templates is None \ else ",".join(gitignore_templates) data = { "name": name, "description": description, "private": private, "auto_init": auto_init, "gitignores": gitignores, "license": license_template, "readme": readme_template } data = {k: v for (k, v) in data.items() if v is not None} url = "/org/{0}/repos".format(organization) if organization else "/user/repos" response = self.post(url, auth=auth, data=data) return GogsRepo.from_json(response.json())
[ "def", "create_repo", "(", "self", ",", "auth", ",", "name", ",", "description", "=", "None", ",", "private", "=", "False", ",", "auto_init", "=", "False", ",", "gitignore_templates", "=", "None", ",", "license_template", "=", "None", ",", "readme_template",...
Creates a new repository, and returns the created repository. :param auth.Authentication auth: authentication object :param str name: name of the repository to create :param str description: description of the repository to create :param bool private: whether the create repository should be private :param bool auto_init: whether the created repository should be auto-initialized with an initial commit :param list[str] gitignore_templates: collection of ``.gitignore`` templates to apply :param str license_template: license template to apply :param str readme_template: README template to apply :param str organization: organization under which repository is created :return: a representation of the created repository :rtype: GogsRepo :raises NetworkFailure: if there is an error communicating with the server :raises ApiFailure: if the request cannot be serviced
[ "Creates", "a", "new", "repository", "and", "returns", "the", "created", "repository", "." ]
b7f27f4995abf914c0db8a424760f5b27331939d
https://github.com/unfoldingWord-dev/python-gogs-client/blob/b7f27f4995abf914c0db8a424760f5b27331939d/gogs_client/interface.py#L113-L147
train
48,982
unfoldingWord-dev/python-gogs-client
gogs_client/interface.py
GogsApi.repo_exists
def repo_exists(self, auth, username, repo_name): """ Returns whether a repository with name ``repo_name`` owned by the user with username ``username`` exists. :param auth.Authentication auth: authentication object :param str username: username of owner of repository :param str repo_name: name of repository :return: whether the repository exists :rtype: bool :raises NetworkFailure: if there is an error communicating with the server :raises ApiFailure: if the request cannot be serviced """ path = "/repos/{u}/{r}".format(u=username, r=repo_name) return self._get(path, auth=auth).ok
python
def repo_exists(self, auth, username, repo_name): """ Returns whether a repository with name ``repo_name`` owned by the user with username ``username`` exists. :param auth.Authentication auth: authentication object :param str username: username of owner of repository :param str repo_name: name of repository :return: whether the repository exists :rtype: bool :raises NetworkFailure: if there is an error communicating with the server :raises ApiFailure: if the request cannot be serviced """ path = "/repos/{u}/{r}".format(u=username, r=repo_name) return self._get(path, auth=auth).ok
[ "def", "repo_exists", "(", "self", ",", "auth", ",", "username", ",", "repo_name", ")", ":", "path", "=", "\"/repos/{u}/{r}\"", ".", "format", "(", "u", "=", "username", ",", "r", "=", "repo_name", ")", "return", "self", ".", "_get", "(", "path", ",", ...
Returns whether a repository with name ``repo_name`` owned by the user with username ``username`` exists. :param auth.Authentication auth: authentication object :param str username: username of owner of repository :param str repo_name: name of repository :return: whether the repository exists :rtype: bool :raises NetworkFailure: if there is an error communicating with the server :raises ApiFailure: if the request cannot be serviced
[ "Returns", "whether", "a", "repository", "with", "name", "repo_name", "owned", "by", "the", "user", "with", "username", "username", "exists", "." ]
b7f27f4995abf914c0db8a424760f5b27331939d
https://github.com/unfoldingWord-dev/python-gogs-client/blob/b7f27f4995abf914c0db8a424760f5b27331939d/gogs_client/interface.py#L149-L162
train
48,983
unfoldingWord-dev/python-gogs-client
gogs_client/interface.py
GogsApi.get_repo
def get_repo(self, auth, username, repo_name): """ Returns a the repository with name ``repo_name`` owned by the user with username ``username``. :param auth.Authentication auth: authentication object :param str username: username of owner of repository :param str repo_name: name of repository :return: a representation of the retrieved repository :rtype: GogsRepo :raises NetworkFailure: if there is an error communicating with the server :raises ApiFailure: if the request cannot be serviced """ path = "/repos/{u}/{r}".format(u=username, r=repo_name) response = self.get(path, auth=auth) return GogsRepo.from_json(response.json())
python
def get_repo(self, auth, username, repo_name): """ Returns a the repository with name ``repo_name`` owned by the user with username ``username``. :param auth.Authentication auth: authentication object :param str username: username of owner of repository :param str repo_name: name of repository :return: a representation of the retrieved repository :rtype: GogsRepo :raises NetworkFailure: if there is an error communicating with the server :raises ApiFailure: if the request cannot be serviced """ path = "/repos/{u}/{r}".format(u=username, r=repo_name) response = self.get(path, auth=auth) return GogsRepo.from_json(response.json())
[ "def", "get_repo", "(", "self", ",", "auth", ",", "username", ",", "repo_name", ")", ":", "path", "=", "\"/repos/{u}/{r}\"", ".", "format", "(", "u", "=", "username", ",", "r", "=", "repo_name", ")", "response", "=", "self", ".", "get", "(", "path", ...
Returns a the repository with name ``repo_name`` owned by the user with username ``username``. :param auth.Authentication auth: authentication object :param str username: username of owner of repository :param str repo_name: name of repository :return: a representation of the retrieved repository :rtype: GogsRepo :raises NetworkFailure: if there is an error communicating with the server :raises ApiFailure: if the request cannot be serviced
[ "Returns", "a", "the", "repository", "with", "name", "repo_name", "owned", "by", "the", "user", "with", "username", "username", "." ]
b7f27f4995abf914c0db8a424760f5b27331939d
https://github.com/unfoldingWord-dev/python-gogs-client/blob/b7f27f4995abf914c0db8a424760f5b27331939d/gogs_client/interface.py#L164-L179
train
48,984
unfoldingWord-dev/python-gogs-client
gogs_client/interface.py
GogsApi.get_user_repos
def get_user_repos(self, auth, username): """ Returns the repositories owned by the user with username ``username``. :param auth.Authentication auth: authentication object :param str username: username of owner of repository :return: a list of repositories :rtype: List[GogsRepo] :raises NetworkFailure: if there is an error communicating with the server :raises ApiFailure: if the request cannot be serviced """ path = "/users/{u}/repos".format(u=username) response = self.get(path, auth=auth) return [GogsRepo.from_json(repo_json) for repo_json in response.json()]
python
def get_user_repos(self, auth, username): """ Returns the repositories owned by the user with username ``username``. :param auth.Authentication auth: authentication object :param str username: username of owner of repository :return: a list of repositories :rtype: List[GogsRepo] :raises NetworkFailure: if there is an error communicating with the server :raises ApiFailure: if the request cannot be serviced """ path = "/users/{u}/repos".format(u=username) response = self.get(path, auth=auth) return [GogsRepo.from_json(repo_json) for repo_json in response.json()]
[ "def", "get_user_repos", "(", "self", ",", "auth", ",", "username", ")", ":", "path", "=", "\"/users/{u}/repos\"", ".", "format", "(", "u", "=", "username", ")", "response", "=", "self", ".", "get", "(", "path", ",", "auth", "=", "auth", ")", "return",...
Returns the repositories owned by the user with username ``username``. :param auth.Authentication auth: authentication object :param str username: username of owner of repository :return: a list of repositories :rtype: List[GogsRepo] :raises NetworkFailure: if there is an error communicating with the server :raises ApiFailure: if the request cannot be serviced
[ "Returns", "the", "repositories", "owned", "by", "the", "user", "with", "username", "username", "." ]
b7f27f4995abf914c0db8a424760f5b27331939d
https://github.com/unfoldingWord-dev/python-gogs-client/blob/b7f27f4995abf914c0db8a424760f5b27331939d/gogs_client/interface.py#L181-L195
train
48,985
unfoldingWord-dev/python-gogs-client
gogs_client/interface.py
GogsApi.get_branch
def get_branch(self, auth, username, repo_name, branch_name): """ Returns the branch with name ``branch_name`` in the repository with name ``repo_name`` owned by the user with username ``username``. :param auth.Authentication auth: authentication object :param str username: username of owner of repository containing the branch :param str repo_name: name of the repository with the branch :param str branch_name: name of the branch to return :return: a branch :rtype: GogsBranch :raises NetworkFailure: if there is an error communicating with the server :raises ApiFailure: if the request cannot be serviced """ path = "/repos/{u}/{r}/branches/{b}".format(u=username, r=repo_name, b=branch_name) response = self.get(path, auth=auth) return GogsBranch.from_json(response.json())
python
def get_branch(self, auth, username, repo_name, branch_name): """ Returns the branch with name ``branch_name`` in the repository with name ``repo_name`` owned by the user with username ``username``. :param auth.Authentication auth: authentication object :param str username: username of owner of repository containing the branch :param str repo_name: name of the repository with the branch :param str branch_name: name of the branch to return :return: a branch :rtype: GogsBranch :raises NetworkFailure: if there is an error communicating with the server :raises ApiFailure: if the request cannot be serviced """ path = "/repos/{u}/{r}/branches/{b}".format(u=username, r=repo_name, b=branch_name) response = self.get(path, auth=auth) return GogsBranch.from_json(response.json())
[ "def", "get_branch", "(", "self", ",", "auth", ",", "username", ",", "repo_name", ",", "branch_name", ")", ":", "path", "=", "\"/repos/{u}/{r}/branches/{b}\"", ".", "format", "(", "u", "=", "username", ",", "r", "=", "repo_name", ",", "b", "=", "branch_nam...
Returns the branch with name ``branch_name`` in the repository with name ``repo_name`` owned by the user with username ``username``. :param auth.Authentication auth: authentication object :param str username: username of owner of repository containing the branch :param str repo_name: name of the repository with the branch :param str branch_name: name of the branch to return :return: a branch :rtype: GogsBranch :raises NetworkFailure: if there is an error communicating with the server :raises ApiFailure: if the request cannot be serviced
[ "Returns", "the", "branch", "with", "name", "branch_name", "in", "the", "repository", "with", "name", "repo_name", "owned", "by", "the", "user", "with", "username", "username", "." ]
b7f27f4995abf914c0db8a424760f5b27331939d
https://github.com/unfoldingWord-dev/python-gogs-client/blob/b7f27f4995abf914c0db8a424760f5b27331939d/gogs_client/interface.py#L197-L213
train
48,986
unfoldingWord-dev/python-gogs-client
gogs_client/interface.py
GogsApi.get_branches
def get_branches(self, auth, username, repo_name): """ Returns the branches in the repository with name ``repo_name`` owned by the user with username ``username``. :param auth.Authentication auth: authentication object :param str username: username of owner of repository containing the branch :param str repo_name: name of the repository with the branch :return: a list of branches :rtype: List[GogsBranch] :raises NetworkFailure: if there is an error communicating with the server :raises ApiFailure: if the request cannot be serviced """ path = "/repos/{u}/{r}/branches".format(u=username, r=repo_name) response = self.get(path, auth=auth) return [GogsBranch.from_json(branch_json) for branch_json in response.json()]
python
def get_branches(self, auth, username, repo_name): """ Returns the branches in the repository with name ``repo_name`` owned by the user with username ``username``. :param auth.Authentication auth: authentication object :param str username: username of owner of repository containing the branch :param str repo_name: name of the repository with the branch :return: a list of branches :rtype: List[GogsBranch] :raises NetworkFailure: if there is an error communicating with the server :raises ApiFailure: if the request cannot be serviced """ path = "/repos/{u}/{r}/branches".format(u=username, r=repo_name) response = self.get(path, auth=auth) return [GogsBranch.from_json(branch_json) for branch_json in response.json()]
[ "def", "get_branches", "(", "self", ",", "auth", ",", "username", ",", "repo_name", ")", ":", "path", "=", "\"/repos/{u}/{r}/branches\"", ".", "format", "(", "u", "=", "username", ",", "r", "=", "repo_name", ")", "response", "=", "self", ".", "get", "(",...
Returns the branches in the repository with name ``repo_name`` owned by the user with username ``username``. :param auth.Authentication auth: authentication object :param str username: username of owner of repository containing the branch :param str repo_name: name of the repository with the branch :return: a list of branches :rtype: List[GogsBranch] :raises NetworkFailure: if there is an error communicating with the server :raises ApiFailure: if the request cannot be serviced
[ "Returns", "the", "branches", "in", "the", "repository", "with", "name", "repo_name", "owned", "by", "the", "user", "with", "username", "username", "." ]
b7f27f4995abf914c0db8a424760f5b27331939d
https://github.com/unfoldingWord-dev/python-gogs-client/blob/b7f27f4995abf914c0db8a424760f5b27331939d/gogs_client/interface.py#L215-L230
train
48,987
unfoldingWord-dev/python-gogs-client
gogs_client/interface.py
GogsApi.delete_repo
def delete_repo(self, auth, username, repo_name): """ Deletes the repository with name ``repo_name`` owned by the user with username ``username``. :param auth.Authentication auth: authentication object :param str username: username of owner of repository to delete :param str repo_name: name of repository to delete :raises NetworkFailure: if there is an error communicating with the server :raises ApiFailure: if the request cannot be serviced """ path = "/repos/{u}/{r}".format(u=username, r=repo_name) self.delete(path, auth=auth)
python
def delete_repo(self, auth, username, repo_name): """ Deletes the repository with name ``repo_name`` owned by the user with username ``username``. :param auth.Authentication auth: authentication object :param str username: username of owner of repository to delete :param str repo_name: name of repository to delete :raises NetworkFailure: if there is an error communicating with the server :raises ApiFailure: if the request cannot be serviced """ path = "/repos/{u}/{r}".format(u=username, r=repo_name) self.delete(path, auth=auth)
[ "def", "delete_repo", "(", "self", ",", "auth", ",", "username", ",", "repo_name", ")", ":", "path", "=", "\"/repos/{u}/{r}\"", ".", "format", "(", "u", "=", "username", ",", "r", "=", "repo_name", ")", "self", ".", "delete", "(", "path", ",", "auth", ...
Deletes the repository with name ``repo_name`` owned by the user with username ``username``. :param auth.Authentication auth: authentication object :param str username: username of owner of repository to delete :param str repo_name: name of repository to delete :raises NetworkFailure: if there is an error communicating with the server :raises ApiFailure: if the request cannot be serviced
[ "Deletes", "the", "repository", "with", "name", "repo_name", "owned", "by", "the", "user", "with", "username", "username", "." ]
b7f27f4995abf914c0db8a424760f5b27331939d
https://github.com/unfoldingWord-dev/python-gogs-client/blob/b7f27f4995abf914c0db8a424760f5b27331939d/gogs_client/interface.py#L232-L243
train
48,988
unfoldingWord-dev/python-gogs-client
gogs_client/interface.py
GogsApi.migrate_repo
def migrate_repo(self, auth, clone_addr, uid, repo_name, auth_username=None, auth_password=None, mirror=False, private=False, description=None): """ Migrate a repository from another Git hosting source for the authenticated user. :param auth.Authentication auth: authentication object :param str clone_addr: Remote Git address (HTTP/HTTPS URL or local path) :param int uid: user ID of repository owner :param str repo_name: Repository name :param bool mirror: Repository will be a mirror. Default is false :param bool private: Repository will be private. Default is false :param str description: Repository description :return: a representation of the migrated repository :rtype: GogsRepo :raises NetworkFailure: if there is an error communicating with the server :raises ApiFailure: if the request cannot be serviced """ # "auth_username": auth_username, # "auth_password": auth_password, data = { "clone_addr": clone_addr, "uid": uid, "repo_name": repo_name, "mirror": mirror, "private": private, "description": description, } data = {k: v for (k, v) in data.items() if v is not None} url = "/repos/migrate" response = self.post(url, auth=auth, data=data) return GogsRepo.from_json(response.json())
python
def migrate_repo(self, auth, clone_addr, uid, repo_name, auth_username=None, auth_password=None, mirror=False, private=False, description=None): """ Migrate a repository from another Git hosting source for the authenticated user. :param auth.Authentication auth: authentication object :param str clone_addr: Remote Git address (HTTP/HTTPS URL or local path) :param int uid: user ID of repository owner :param str repo_name: Repository name :param bool mirror: Repository will be a mirror. Default is false :param bool private: Repository will be private. Default is false :param str description: Repository description :return: a representation of the migrated repository :rtype: GogsRepo :raises NetworkFailure: if there is an error communicating with the server :raises ApiFailure: if the request cannot be serviced """ # "auth_username": auth_username, # "auth_password": auth_password, data = { "clone_addr": clone_addr, "uid": uid, "repo_name": repo_name, "mirror": mirror, "private": private, "description": description, } data = {k: v for (k, v) in data.items() if v is not None} url = "/repos/migrate" response = self.post(url, auth=auth, data=data) return GogsRepo.from_json(response.json())
[ "def", "migrate_repo", "(", "self", ",", "auth", ",", "clone_addr", ",", "uid", ",", "repo_name", ",", "auth_username", "=", "None", ",", "auth_password", "=", "None", ",", "mirror", "=", "False", ",", "private", "=", "False", ",", "description", "=", "N...
Migrate a repository from another Git hosting source for the authenticated user. :param auth.Authentication auth: authentication object :param str clone_addr: Remote Git address (HTTP/HTTPS URL or local path) :param int uid: user ID of repository owner :param str repo_name: Repository name :param bool mirror: Repository will be a mirror. Default is false :param bool private: Repository will be private. Default is false :param str description: Repository description :return: a representation of the migrated repository :rtype: GogsRepo :raises NetworkFailure: if there is an error communicating with the server :raises ApiFailure: if the request cannot be serviced
[ "Migrate", "a", "repository", "from", "another", "Git", "hosting", "source", "for", "the", "authenticated", "user", "." ]
b7f27f4995abf914c0db8a424760f5b27331939d
https://github.com/unfoldingWord-dev/python-gogs-client/blob/b7f27f4995abf914c0db8a424760f5b27331939d/gogs_client/interface.py#L245-L277
train
48,989
unfoldingWord-dev/python-gogs-client
gogs_client/interface.py
GogsApi.create_user
def create_user(self, auth, login_name, username, email, password, send_notify=False): """ Creates a new user, and returns the created user. :param auth.Authentication auth: authentication object, must be admin-level :param str login_name: login name for created user :param str username: username for created user :param str email: email address for created user :param str password: password for created user :param bool send_notify: whether a notification email should be sent upon creation :return: a representation of the created user :rtype: GogsUser :raises NetworkFailure: if there is an error communicating with the server :raises ApiFailure: if the request cannot be serviced """ # Since the source_id parameter was not well-documented at the time this method was # written, force the default value data = { "login_name": login_name, "username": username, "email": email, "password": password, "send_notify": send_notify } response = self.post("/admin/users", auth=auth, data=data) return GogsUser.from_json(response.json())
python
def create_user(self, auth, login_name, username, email, password, send_notify=False): """ Creates a new user, and returns the created user. :param auth.Authentication auth: authentication object, must be admin-level :param str login_name: login name for created user :param str username: username for created user :param str email: email address for created user :param str password: password for created user :param bool send_notify: whether a notification email should be sent upon creation :return: a representation of the created user :rtype: GogsUser :raises NetworkFailure: if there is an error communicating with the server :raises ApiFailure: if the request cannot be serviced """ # Since the source_id parameter was not well-documented at the time this method was # written, force the default value data = { "login_name": login_name, "username": username, "email": email, "password": password, "send_notify": send_notify } response = self.post("/admin/users", auth=auth, data=data) return GogsUser.from_json(response.json())
[ "def", "create_user", "(", "self", ",", "auth", ",", "login_name", ",", "username", ",", "email", ",", "password", ",", "send_notify", "=", "False", ")", ":", "# Since the source_id parameter was not well-documented at the time this method was", "# written, force the defaul...
Creates a new user, and returns the created user. :param auth.Authentication auth: authentication object, must be admin-level :param str login_name: login name for created user :param str username: username for created user :param str email: email address for created user :param str password: password for created user :param bool send_notify: whether a notification email should be sent upon creation :return: a representation of the created user :rtype: GogsUser :raises NetworkFailure: if there is an error communicating with the server :raises ApiFailure: if the request cannot be serviced
[ "Creates", "a", "new", "user", "and", "returns", "the", "created", "user", "." ]
b7f27f4995abf914c0db8a424760f5b27331939d
https://github.com/unfoldingWord-dev/python-gogs-client/blob/b7f27f4995abf914c0db8a424760f5b27331939d/gogs_client/interface.py#L279-L304
train
48,990
unfoldingWord-dev/python-gogs-client
gogs_client/interface.py
GogsApi.user_exists
def user_exists(self, username): """ Returns whether a user with username ``username`` exists. :param str username: username of user :return: whether a user with the specified username exists :rtype: bool :raises NetworkFailure: if there is an error communicating with the server :return: """ path = "/users/{}".format(username) return self._get(path).ok
python
def user_exists(self, username): """ Returns whether a user with username ``username`` exists. :param str username: username of user :return: whether a user with the specified username exists :rtype: bool :raises NetworkFailure: if there is an error communicating with the server :return: """ path = "/users/{}".format(username) return self._get(path).ok
[ "def", "user_exists", "(", "self", ",", "username", ")", ":", "path", "=", "\"/users/{}\"", ".", "format", "(", "username", ")", "return", "self", ".", "_get", "(", "path", ")", ".", "ok" ]
Returns whether a user with username ``username`` exists. :param str username: username of user :return: whether a user with the specified username exists :rtype: bool :raises NetworkFailure: if there is an error communicating with the server :return:
[ "Returns", "whether", "a", "user", "with", "username", "username", "exists", "." ]
b7f27f4995abf914c0db8a424760f5b27331939d
https://github.com/unfoldingWord-dev/python-gogs-client/blob/b7f27f4995abf914c0db8a424760f5b27331939d/gogs_client/interface.py#L306-L317
train
48,991
unfoldingWord-dev/python-gogs-client
gogs_client/interface.py
GogsApi.search_users
def search_users(self, username_keyword, limit=10): """ Searches for users whose username matches ``username_keyword``, and returns a list of matched users. :param str username_keyword: keyword to search with :param int limit: maximum number of returned users :return: a list of matched users :rtype: List[GogsUser] :raises NetworkFailure: if there is an error communicating with the server :raises ApiFailure: if the request cannot be serviced """ params = {"q": username_keyword, "limit": limit} response = self.get("/users/search", params=params) return [GogsUser.from_json(user_json) for user_json in response.json()["data"]]
python
def search_users(self, username_keyword, limit=10): """ Searches for users whose username matches ``username_keyword``, and returns a list of matched users. :param str username_keyword: keyword to search with :param int limit: maximum number of returned users :return: a list of matched users :rtype: List[GogsUser] :raises NetworkFailure: if there is an error communicating with the server :raises ApiFailure: if the request cannot be serviced """ params = {"q": username_keyword, "limit": limit} response = self.get("/users/search", params=params) return [GogsUser.from_json(user_json) for user_json in response.json()["data"]]
[ "def", "search_users", "(", "self", ",", "username_keyword", ",", "limit", "=", "10", ")", ":", "params", "=", "{", "\"q\"", ":", "username_keyword", ",", "\"limit\"", ":", "limit", "}", "response", "=", "self", ".", "get", "(", "\"/users/search\"", ",", ...
Searches for users whose username matches ``username_keyword``, and returns a list of matched users. :param str username_keyword: keyword to search with :param int limit: maximum number of returned users :return: a list of matched users :rtype: List[GogsUser] :raises NetworkFailure: if there is an error communicating with the server :raises ApiFailure: if the request cannot be serviced
[ "Searches", "for", "users", "whose", "username", "matches", "username_keyword", "and", "returns", "a", "list", "of", "matched", "users", "." ]
b7f27f4995abf914c0db8a424760f5b27331939d
https://github.com/unfoldingWord-dev/python-gogs-client/blob/b7f27f4995abf914c0db8a424760f5b27331939d/gogs_client/interface.py#L319-L333
train
48,992
unfoldingWord-dev/python-gogs-client
gogs_client/interface.py
GogsApi.get_user
def get_user(self, auth, username): """ Returns a representing the user with username ``username``. :param auth.Authentication auth: authentication object, can be ``None`` :param str username: username of user to get :return: the retrieved user :rtype: GogsUser :raises NetworkFailure: if there is an error communicating with the server :raises ApiFailure: if the request cannot be serviced """ path = "/users/{}".format(username) response = self.get(path, auth=auth) return GogsUser.from_json(response.json())
python
def get_user(self, auth, username): """ Returns a representing the user with username ``username``. :param auth.Authentication auth: authentication object, can be ``None`` :param str username: username of user to get :return: the retrieved user :rtype: GogsUser :raises NetworkFailure: if there is an error communicating with the server :raises ApiFailure: if the request cannot be serviced """ path = "/users/{}".format(username) response = self.get(path, auth=auth) return GogsUser.from_json(response.json())
[ "def", "get_user", "(", "self", ",", "auth", ",", "username", ")", ":", "path", "=", "\"/users/{}\"", ".", "format", "(", "username", ")", "response", "=", "self", ".", "get", "(", "path", ",", "auth", "=", "auth", ")", "return", "GogsUser", ".", "fr...
Returns a representing the user with username ``username``. :param auth.Authentication auth: authentication object, can be ``None`` :param str username: username of user to get :return: the retrieved user :rtype: GogsUser :raises NetworkFailure: if there is an error communicating with the server :raises ApiFailure: if the request cannot be serviced
[ "Returns", "a", "representing", "the", "user", "with", "username", "username", "." ]
b7f27f4995abf914c0db8a424760f5b27331939d
https://github.com/unfoldingWord-dev/python-gogs-client/blob/b7f27f4995abf914c0db8a424760f5b27331939d/gogs_client/interface.py#L335-L348
train
48,993
unfoldingWord-dev/python-gogs-client
gogs_client/interface.py
GogsApi.update_user
def update_user(self, auth, username, update): """ Updates the user with username ``username`` according to ``update``. :param auth.Authentication auth: authentication object, must be admin-level :param str username: username of user to update :param GogsUserUpdate update: a ``GogsUserUpdate`` object describing the requested update :return: the updated user :rtype: GogsUser :raises NetworkFailure: if there is an error communicating with the server :raises ApiFailure: if the request cannot be serviced """ path = "/admin/users/{}".format(username) response = self.patch(path, auth=auth, data=update.as_dict()) return GogsUser.from_json(response.json())
python
def update_user(self, auth, username, update): """ Updates the user with username ``username`` according to ``update``. :param auth.Authentication auth: authentication object, must be admin-level :param str username: username of user to update :param GogsUserUpdate update: a ``GogsUserUpdate`` object describing the requested update :return: the updated user :rtype: GogsUser :raises NetworkFailure: if there is an error communicating with the server :raises ApiFailure: if the request cannot be serviced """ path = "/admin/users/{}".format(username) response = self.patch(path, auth=auth, data=update.as_dict()) return GogsUser.from_json(response.json())
[ "def", "update_user", "(", "self", ",", "auth", ",", "username", ",", "update", ")", ":", "path", "=", "\"/admin/users/{}\"", ".", "format", "(", "username", ")", "response", "=", "self", ".", "patch", "(", "path", ",", "auth", "=", "auth", ",", "data"...
Updates the user with username ``username`` according to ``update``. :param auth.Authentication auth: authentication object, must be admin-level :param str username: username of user to update :param GogsUserUpdate update: a ``GogsUserUpdate`` object describing the requested update :return: the updated user :rtype: GogsUser :raises NetworkFailure: if there is an error communicating with the server :raises ApiFailure: if the request cannot be serviced
[ "Updates", "the", "user", "with", "username", "username", "according", "to", "update", "." ]
b7f27f4995abf914c0db8a424760f5b27331939d
https://github.com/unfoldingWord-dev/python-gogs-client/blob/b7f27f4995abf914c0db8a424760f5b27331939d/gogs_client/interface.py#L350-L364
train
48,994
unfoldingWord-dev/python-gogs-client
gogs_client/interface.py
GogsApi.delete_user
def delete_user(self, auth, username): """ Deletes the user with username ``username``. Should only be called if the to-be-deleted user has no repositories. :param auth.Authentication auth: authentication object, must be admin-level :param str username: username of user to delete """ path = "/admin/users/{}".format(username) self.delete(path, auth=auth)
python
def delete_user(self, auth, username): """ Deletes the user with username ``username``. Should only be called if the to-be-deleted user has no repositories. :param auth.Authentication auth: authentication object, must be admin-level :param str username: username of user to delete """ path = "/admin/users/{}".format(username) self.delete(path, auth=auth)
[ "def", "delete_user", "(", "self", ",", "auth", ",", "username", ")", ":", "path", "=", "\"/admin/users/{}\"", ".", "format", "(", "username", ")", "self", ".", "delete", "(", "path", ",", "auth", "=", "auth", ")" ]
Deletes the user with username ``username``. Should only be called if the to-be-deleted user has no repositories. :param auth.Authentication auth: authentication object, must be admin-level :param str username: username of user to delete
[ "Deletes", "the", "user", "with", "username", "username", ".", "Should", "only", "be", "called", "if", "the", "to", "-", "be", "-", "deleted", "user", "has", "no", "repositories", "." ]
b7f27f4995abf914c0db8a424760f5b27331939d
https://github.com/unfoldingWord-dev/python-gogs-client/blob/b7f27f4995abf914c0db8a424760f5b27331939d/gogs_client/interface.py#L366-L375
train
48,995
unfoldingWord-dev/python-gogs-client
gogs_client/interface.py
GogsApi.get_repo_hooks
def get_repo_hooks(self, auth, username, repo_name): """ Returns all hooks of repository with name ``repo_name`` owned by the user with username ``username``. :param auth.Authentication auth: authentication object :param str username: username of owner of repository :param str repo_name: name of repository :return: a list of hooks for the specified repository :rtype: List[GogsRepo.Hooks] :raises NetworkFailure: if there is an error communicating with the server :raises ApiFailure: if the request cannot be serviced """ path = "/repos/{u}/{r}/hooks".format(u=username, r=repo_name) response = self.get(path, auth=auth) return [GogsRepo.Hook.from_json(hook) for hook in response.json()]
python
def get_repo_hooks(self, auth, username, repo_name): """ Returns all hooks of repository with name ``repo_name`` owned by the user with username ``username``. :param auth.Authentication auth: authentication object :param str username: username of owner of repository :param str repo_name: name of repository :return: a list of hooks for the specified repository :rtype: List[GogsRepo.Hooks] :raises NetworkFailure: if there is an error communicating with the server :raises ApiFailure: if the request cannot be serviced """ path = "/repos/{u}/{r}/hooks".format(u=username, r=repo_name) response = self.get(path, auth=auth) return [GogsRepo.Hook.from_json(hook) for hook in response.json()]
[ "def", "get_repo_hooks", "(", "self", ",", "auth", ",", "username", ",", "repo_name", ")", ":", "path", "=", "\"/repos/{u}/{r}/hooks\"", ".", "format", "(", "u", "=", "username", ",", "r", "=", "repo_name", ")", "response", "=", "self", ".", "get", "(", ...
Returns all hooks of repository with name ``repo_name`` owned by the user with username ``username``. :param auth.Authentication auth: authentication object :param str username: username of owner of repository :param str repo_name: name of repository :return: a list of hooks for the specified repository :rtype: List[GogsRepo.Hooks] :raises NetworkFailure: if there is an error communicating with the server :raises ApiFailure: if the request cannot be serviced
[ "Returns", "all", "hooks", "of", "repository", "with", "name", "repo_name", "owned", "by", "the", "user", "with", "username", "username", "." ]
b7f27f4995abf914c0db8a424760f5b27331939d
https://github.com/unfoldingWord-dev/python-gogs-client/blob/b7f27f4995abf914c0db8a424760f5b27331939d/gogs_client/interface.py#L377-L392
train
48,996
unfoldingWord-dev/python-gogs-client
gogs_client/interface.py
GogsApi.create_hook
def create_hook(self, auth, repo_name, hook_type, config, events=None, organization=None, active=False): """ Creates a new hook, and returns the created hook. :param auth.Authentication auth: authentication object, must be admin-level :param str repo_name: the name of the repo for which we create the hook :param str hook_type: The type of webhook, either "gogs" or "slack" :param dict config: Settings for this hook (possible keys are ``"url"``, ``"content_type"``, ``"secret"``) :param list events: Determines what events the hook is triggered for. Default: ["push"] :param str organization: Organization of the repo :param bool active: Determines whether the hook is actually triggered on pushes. Default is false :return: a representation of the created hook :rtype: GogsRepo.Hook :raises NetworkFailure: if there is an error communicating with the server :raises ApiFailure: if the request cannot be serviced """ if events is None: events = ["push"] # default value is mutable, so assign inside body data = { "type": hook_type, "config": config, "events": events, "active": active } url = "/repos/{o}/{r}/hooks".format(o=organization, r=repo_name) if organization is not None \ else "/repos/{r}/hooks".format(r=repo_name) response = self.post(url, auth=auth, data=data) return GogsRepo.Hook.from_json(response.json())
python
def create_hook(self, auth, repo_name, hook_type, config, events=None, organization=None, active=False): """ Creates a new hook, and returns the created hook. :param auth.Authentication auth: authentication object, must be admin-level :param str repo_name: the name of the repo for which we create the hook :param str hook_type: The type of webhook, either "gogs" or "slack" :param dict config: Settings for this hook (possible keys are ``"url"``, ``"content_type"``, ``"secret"``) :param list events: Determines what events the hook is triggered for. Default: ["push"] :param str organization: Organization of the repo :param bool active: Determines whether the hook is actually triggered on pushes. Default is false :return: a representation of the created hook :rtype: GogsRepo.Hook :raises NetworkFailure: if there is an error communicating with the server :raises ApiFailure: if the request cannot be serviced """ if events is None: events = ["push"] # default value is mutable, so assign inside body data = { "type": hook_type, "config": config, "events": events, "active": active } url = "/repos/{o}/{r}/hooks".format(o=organization, r=repo_name) if organization is not None \ else "/repos/{r}/hooks".format(r=repo_name) response = self.post(url, auth=auth, data=data) return GogsRepo.Hook.from_json(response.json())
[ "def", "create_hook", "(", "self", ",", "auth", ",", "repo_name", ",", "hook_type", ",", "config", ",", "events", "=", "None", ",", "organization", "=", "None", ",", "active", "=", "False", ")", ":", "if", "events", "is", "None", ":", "events", "=", ...
Creates a new hook, and returns the created hook. :param auth.Authentication auth: authentication object, must be admin-level :param str repo_name: the name of the repo for which we create the hook :param str hook_type: The type of webhook, either "gogs" or "slack" :param dict config: Settings for this hook (possible keys are ``"url"``, ``"content_type"``, ``"secret"``) :param list events: Determines what events the hook is triggered for. Default: ["push"] :param str organization: Organization of the repo :param bool active: Determines whether the hook is actually triggered on pushes. Default is false :return: a representation of the created hook :rtype: GogsRepo.Hook :raises NetworkFailure: if there is an error communicating with the server :raises ApiFailure: if the request cannot be serviced
[ "Creates", "a", "new", "hook", "and", "returns", "the", "created", "hook", "." ]
b7f27f4995abf914c0db8a424760f5b27331939d
https://github.com/unfoldingWord-dev/python-gogs-client/blob/b7f27f4995abf914c0db8a424760f5b27331939d/gogs_client/interface.py#L394-L424
train
48,997
unfoldingWord-dev/python-gogs-client
gogs_client/interface.py
GogsApi.update_hook
def update_hook(self, auth, repo_name, hook_id, update, organization=None): """ Updates hook with id ``hook_id`` according to ``update``. :param auth.Authentication auth: authentication object :param str repo_name: repo of the hook to update :param int hook_id: id of the hook to update :param GogsHookUpdate update: a ``GogsHookUpdate`` object describing the requested update :param str organization: name of associated organization, if applicable :return: the updated hook :rtype: GogsRepo.Hook :raises NetworkFailure: if there is an error communicating with the server :raises ApiFailure: if the request cannot be serviced """ if organization is not None: path = "/repos/{o}/{r}/hooks/{i}".format(o=organization, r=repo_name, i=hook_id) else: path = "/repos/{r}/hooks/{i}".format(r=repo_name, i=hook_id) response = self._patch(path, auth=auth, data=update.as_dict()) return GogsRepo.Hook.from_json(response.json())
python
def update_hook(self, auth, repo_name, hook_id, update, organization=None): """ Updates hook with id ``hook_id`` according to ``update``. :param auth.Authentication auth: authentication object :param str repo_name: repo of the hook to update :param int hook_id: id of the hook to update :param GogsHookUpdate update: a ``GogsHookUpdate`` object describing the requested update :param str organization: name of associated organization, if applicable :return: the updated hook :rtype: GogsRepo.Hook :raises NetworkFailure: if there is an error communicating with the server :raises ApiFailure: if the request cannot be serviced """ if organization is not None: path = "/repos/{o}/{r}/hooks/{i}".format(o=organization, r=repo_name, i=hook_id) else: path = "/repos/{r}/hooks/{i}".format(r=repo_name, i=hook_id) response = self._patch(path, auth=auth, data=update.as_dict()) return GogsRepo.Hook.from_json(response.json())
[ "def", "update_hook", "(", "self", ",", "auth", ",", "repo_name", ",", "hook_id", ",", "update", ",", "organization", "=", "None", ")", ":", "if", "organization", "is", "not", "None", ":", "path", "=", "\"/repos/{o}/{r}/hooks/{i}\"", ".", "format", "(", "o...
Updates hook with id ``hook_id`` according to ``update``. :param auth.Authentication auth: authentication object :param str repo_name: repo of the hook to update :param int hook_id: id of the hook to update :param GogsHookUpdate update: a ``GogsHookUpdate`` object describing the requested update :param str organization: name of associated organization, if applicable :return: the updated hook :rtype: GogsRepo.Hook :raises NetworkFailure: if there is an error communicating with the server :raises ApiFailure: if the request cannot be serviced
[ "Updates", "hook", "with", "id", "hook_id", "according", "to", "update", "." ]
b7f27f4995abf914c0db8a424760f5b27331939d
https://github.com/unfoldingWord-dev/python-gogs-client/blob/b7f27f4995abf914c0db8a424760f5b27331939d/gogs_client/interface.py#L426-L445
train
48,998
unfoldingWord-dev/python-gogs-client
gogs_client/interface.py
GogsApi.delete_hook
def delete_hook(self, auth, username, repo_name, hook_id): """ Deletes the hook with id ``hook_id`` for repo with name ``repo_name`` owned by the user with username ``username``. :param auth.Authentication auth: authentication object :param str username: username of owner of repository :param str repo_name: name of repository of hook to delete :param int hook_id: id of hook to delete :raises NetworkFailure: if there is an error communicating with the server :raises ApiFailure: if the request cannot be serviced """ path = "/repos/{u}/{r}/hooks/{i}".format(u=username, r=repo_name, i=hook_id) self.delete(path, auth=auth)
python
def delete_hook(self, auth, username, repo_name, hook_id): """ Deletes the hook with id ``hook_id`` for repo with name ``repo_name`` owned by the user with username ``username``. :param auth.Authentication auth: authentication object :param str username: username of owner of repository :param str repo_name: name of repository of hook to delete :param int hook_id: id of hook to delete :raises NetworkFailure: if there is an error communicating with the server :raises ApiFailure: if the request cannot be serviced """ path = "/repos/{u}/{r}/hooks/{i}".format(u=username, r=repo_name, i=hook_id) self.delete(path, auth=auth)
[ "def", "delete_hook", "(", "self", ",", "auth", ",", "username", ",", "repo_name", ",", "hook_id", ")", ":", "path", "=", "\"/repos/{u}/{r}/hooks/{i}\"", ".", "format", "(", "u", "=", "username", ",", "r", "=", "repo_name", ",", "i", "=", "hook_id", ")",...
Deletes the hook with id ``hook_id`` for repo with name ``repo_name`` owned by the user with username ``username``. :param auth.Authentication auth: authentication object :param str username: username of owner of repository :param str repo_name: name of repository of hook to delete :param int hook_id: id of hook to delete :raises NetworkFailure: if there is an error communicating with the server :raises ApiFailure: if the request cannot be serviced
[ "Deletes", "the", "hook", "with", "id", "hook_id", "for", "repo", "with", "name", "repo_name", "owned", "by", "the", "user", "with", "username", "username", "." ]
b7f27f4995abf914c0db8a424760f5b27331939d
https://github.com/unfoldingWord-dev/python-gogs-client/blob/b7f27f4995abf914c0db8a424760f5b27331939d/gogs_client/interface.py#L447-L460
train
48,999