id
int32
0
252k
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
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
245,700
b3j0f/utils
b3j0f/utils/property.py
del_properties
def del_properties(elt, keys=None, ctx=None): """Delete elt property. :param elt: properties elt to del. Not None methods. :param keys: property keys to delete from elt. If empty, delete all properties. """ # get the best context if ctx is None: ctx = find_ctx(elt=elt) elt_properties = _ctx_elt_properties(elt=elt, ctx=ctx, create=False) # if elt properties exist if elt_properties is not None: if keys is None: keys = list(elt_properties.keys()) else: keys = ensureiterable(keys, iterable=tuple, exclude=str) for key in keys: if key in elt_properties: del elt_properties[key] # delete property component if empty if not elt_properties: # case of dynamic object if isinstance(getattr(ctx, '__dict__', None), dict): try: if elt in ctx.__dict__[__B3J0F__PROPERTIES__]: del ctx.__dict__[__B3J0F__PROPERTIES__][elt] except TypeError: # if elt is unhashable elt = id(elt) if elt in ctx.__dict__[__B3J0F__PROPERTIES__]: del ctx.__dict__[__B3J0F__PROPERTIES__][elt] # if ctx_properties is empty, delete it if not ctx.__dict__[__B3J0F__PROPERTIES__]: del ctx.__dict__[__B3J0F__PROPERTIES__] # case of static object and hashable else: if isinstance(ctx, Hashable): cache = __STATIC_ELEMENTS_CACHE__ else: # case of static and unhashable object cache = __UNHASHABLE_ELTS_CACHE__ ctx = id(ctx) if not isinstance(elt, Hashable): elt = id(elt) # in case of static object if ctx in cache: del cache[ctx][elt] if not cache[ctx]: del cache[ctx]
python
def del_properties(elt, keys=None, ctx=None): """Delete elt property. :param elt: properties elt to del. Not None methods. :param keys: property keys to delete from elt. If empty, delete all properties. """ # get the best context if ctx is None: ctx = find_ctx(elt=elt) elt_properties = _ctx_elt_properties(elt=elt, ctx=ctx, create=False) # if elt properties exist if elt_properties is not None: if keys is None: keys = list(elt_properties.keys()) else: keys = ensureiterable(keys, iterable=tuple, exclude=str) for key in keys: if key in elt_properties: del elt_properties[key] # delete property component if empty if not elt_properties: # case of dynamic object if isinstance(getattr(ctx, '__dict__', None), dict): try: if elt in ctx.__dict__[__B3J0F__PROPERTIES__]: del ctx.__dict__[__B3J0F__PROPERTIES__][elt] except TypeError: # if elt is unhashable elt = id(elt) if elt in ctx.__dict__[__B3J0F__PROPERTIES__]: del ctx.__dict__[__B3J0F__PROPERTIES__][elt] # if ctx_properties is empty, delete it if not ctx.__dict__[__B3J0F__PROPERTIES__]: del ctx.__dict__[__B3J0F__PROPERTIES__] # case of static object and hashable else: if isinstance(ctx, Hashable): cache = __STATIC_ELEMENTS_CACHE__ else: # case of static and unhashable object cache = __UNHASHABLE_ELTS_CACHE__ ctx = id(ctx) if not isinstance(elt, Hashable): elt = id(elt) # in case of static object if ctx in cache: del cache[ctx][elt] if not cache[ctx]: del cache[ctx]
[ "def", "del_properties", "(", "elt", ",", "keys", "=", "None", ",", "ctx", "=", "None", ")", ":", "# get the best context", "if", "ctx", "is", "None", ":", "ctx", "=", "find_ctx", "(", "elt", "=", "elt", ")", "elt_properties", "=", "_ctx_elt_properties", "(", "elt", "=", "elt", ",", "ctx", "=", "ctx", ",", "create", "=", "False", ")", "# if elt properties exist", "if", "elt_properties", "is", "not", "None", ":", "if", "keys", "is", "None", ":", "keys", "=", "list", "(", "elt_properties", ".", "keys", "(", ")", ")", "else", ":", "keys", "=", "ensureiterable", "(", "keys", ",", "iterable", "=", "tuple", ",", "exclude", "=", "str", ")", "for", "key", "in", "keys", ":", "if", "key", "in", "elt_properties", ":", "del", "elt_properties", "[", "key", "]", "# delete property component if empty", "if", "not", "elt_properties", ":", "# case of dynamic object", "if", "isinstance", "(", "getattr", "(", "ctx", ",", "'__dict__'", ",", "None", ")", ",", "dict", ")", ":", "try", ":", "if", "elt", "in", "ctx", ".", "__dict__", "[", "__B3J0F__PROPERTIES__", "]", ":", "del", "ctx", ".", "__dict__", "[", "__B3J0F__PROPERTIES__", "]", "[", "elt", "]", "except", "TypeError", ":", "# if elt is unhashable", "elt", "=", "id", "(", "elt", ")", "if", "elt", "in", "ctx", ".", "__dict__", "[", "__B3J0F__PROPERTIES__", "]", ":", "del", "ctx", ".", "__dict__", "[", "__B3J0F__PROPERTIES__", "]", "[", "elt", "]", "# if ctx_properties is empty, delete it", "if", "not", "ctx", ".", "__dict__", "[", "__B3J0F__PROPERTIES__", "]", ":", "del", "ctx", ".", "__dict__", "[", "__B3J0F__PROPERTIES__", "]", "# case of static object and hashable", "else", ":", "if", "isinstance", "(", "ctx", ",", "Hashable", ")", ":", "cache", "=", "__STATIC_ELEMENTS_CACHE__", "else", ":", "# case of static and unhashable object", "cache", "=", "__UNHASHABLE_ELTS_CACHE__", "ctx", "=", "id", "(", "ctx", ")", "if", "not", "isinstance", "(", "elt", ",", "Hashable", ")", ":", "elt", "=", "id", "(", "elt", ")", "# in case of static object", "if", "ctx", "in", "cache", ":", "del", "cache", "[", "ctx", "]", "[", "elt", "]", "if", "not", "cache", "[", "ctx", "]", ":", "del", "cache", "[", "ctx", "]" ]
Delete elt property. :param elt: properties elt to del. Not None methods. :param keys: property keys to delete from elt. If empty, delete all properties.
[ "Delete", "elt", "property", "." ]
793871b98e90fd1c7ce9ef0dce839cc18fcbc6ff
https://github.com/b3j0f/utils/blob/793871b98e90fd1c7ce9ef0dce839cc18fcbc6ff/b3j0f/utils/property.py#L579-L635
245,701
b3j0f/utils
b3j0f/utils/property.py
setdefault
def setdefault(elt, key, default, ctx=None): """ Get a local property and create default value if local property does not exist. :param elt: local proprety elt to get/create. Not None methods. :param str key: proprety name. :param default: property value to set if key no in local properties. :return: property value or default if property does not exist. """ result = default # get the best context if ctx is None: ctx = find_ctx(elt=elt) # get elt properties elt_properties = _ctx_elt_properties(elt=elt, ctx=ctx, create=True) # if key exists in elt properties if key in elt_properties: # result is elt_properties[key] result = elt_properties[key] else: # set default property value elt_properties[key] = default return result
python
def setdefault(elt, key, default, ctx=None): """ Get a local property and create default value if local property does not exist. :param elt: local proprety elt to get/create. Not None methods. :param str key: proprety name. :param default: property value to set if key no in local properties. :return: property value or default if property does not exist. """ result = default # get the best context if ctx is None: ctx = find_ctx(elt=elt) # get elt properties elt_properties = _ctx_elt_properties(elt=elt, ctx=ctx, create=True) # if key exists in elt properties if key in elt_properties: # result is elt_properties[key] result = elt_properties[key] else: # set default property value elt_properties[key] = default return result
[ "def", "setdefault", "(", "elt", ",", "key", ",", "default", ",", "ctx", "=", "None", ")", ":", "result", "=", "default", "# get the best context", "if", "ctx", "is", "None", ":", "ctx", "=", "find_ctx", "(", "elt", "=", "elt", ")", "# get elt properties", "elt_properties", "=", "_ctx_elt_properties", "(", "elt", "=", "elt", ",", "ctx", "=", "ctx", ",", "create", "=", "True", ")", "# if key exists in elt properties", "if", "key", "in", "elt_properties", ":", "# result is elt_properties[key]", "result", "=", "elt_properties", "[", "key", "]", "else", ":", "# set default property value", "elt_properties", "[", "key", "]", "=", "default", "return", "result" ]
Get a local property and create default value if local property does not exist. :param elt: local proprety elt to get/create. Not None methods. :param str key: proprety name. :param default: property value to set if key no in local properties. :return: property value or default if property does not exist.
[ "Get", "a", "local", "property", "and", "create", "default", "value", "if", "local", "property", "does", "not", "exist", "." ]
793871b98e90fd1c7ce9ef0dce839cc18fcbc6ff
https://github.com/b3j0f/utils/blob/793871b98e90fd1c7ce9ef0dce839cc18fcbc6ff/b3j0f/utils/property.py#L680-L708
245,702
benjaoming/simple-pypi-statistics
simple_pypi_statistics/api.py
get_jsonparsed_data
def get_jsonparsed_data(url): """Receive the content of ``url``, parse it as JSON and return the object. """ response = urlopen(url) data = response.read().decode('utf-8') return json.loads(data)
python
def get_jsonparsed_data(url): """Receive the content of ``url``, parse it as JSON and return the object. """ response = urlopen(url) data = response.read().decode('utf-8') return json.loads(data)
[ "def", "get_jsonparsed_data", "(", "url", ")", ":", "response", "=", "urlopen", "(", "url", ")", "data", "=", "response", ".", "read", "(", ")", ".", "decode", "(", "'utf-8'", ")", "return", "json", ".", "loads", "(", "data", ")" ]
Receive the content of ``url``, parse it as JSON and return the object.
[ "Receive", "the", "content", "of", "url", "parse", "it", "as", "JSON", "and", "return", "the", "object", "." ]
de93b94877004ae18a5c8e5b96b213aa38fb29a8
https://github.com/benjaoming/simple-pypi-statistics/blob/de93b94877004ae18a5c8e5b96b213aa38fb29a8/simple_pypi_statistics/api.py#L90-L96
245,703
benjaoming/simple-pypi-statistics
simple_pypi_statistics/api.py
get_corrected_stats
def get_corrected_stats(package, use_honeypot=True): """ Fetches statistics for `package` and then corrects them using a special honeypot. """ honeypot, __, __ = get_stats('python-bogus-project-honeypot') if not honeypot: raise RuntimeError("Could not get honeypot data") honeypot = honeypot['releases'] # Add a field used to store diff when choosing the best honey pot release # for some statistic for x in honeypot: x['diff'] = 0 stats, __, version = get_stats(package) if not stats: return # Denote release date diff and choose the honey pot release that's closest # to the one of each release releases = stats['releases'] for release in releases: # Sort by absolute difference honeypot.sort(key=lambda x: abs( (x['upload_time'] - release['upload_time']).total_seconds() )) # Multiple candidates honeypot_filtered = list(filter(lambda x: x['diff'] == honeypot[0]['diff'], honeypot)) average_downloads = sum([x['downloads'] for x in honeypot_filtered]) / len(honeypot_filtered) release['downloads'] = release['downloads'] - average_downloads # Re-calculate totals total_count = sum([x['downloads'] for x in releases]) return stats, total_count, version
python
def get_corrected_stats(package, use_honeypot=True): """ Fetches statistics for `package` and then corrects them using a special honeypot. """ honeypot, __, __ = get_stats('python-bogus-project-honeypot') if not honeypot: raise RuntimeError("Could not get honeypot data") honeypot = honeypot['releases'] # Add a field used to store diff when choosing the best honey pot release # for some statistic for x in honeypot: x['diff'] = 0 stats, __, version = get_stats(package) if not stats: return # Denote release date diff and choose the honey pot release that's closest # to the one of each release releases = stats['releases'] for release in releases: # Sort by absolute difference honeypot.sort(key=lambda x: abs( (x['upload_time'] - release['upload_time']).total_seconds() )) # Multiple candidates honeypot_filtered = list(filter(lambda x: x['diff'] == honeypot[0]['diff'], honeypot)) average_downloads = sum([x['downloads'] for x in honeypot_filtered]) / len(honeypot_filtered) release['downloads'] = release['downloads'] - average_downloads # Re-calculate totals total_count = sum([x['downloads'] for x in releases]) return stats, total_count, version
[ "def", "get_corrected_stats", "(", "package", ",", "use_honeypot", "=", "True", ")", ":", "honeypot", ",", "__", ",", "__", "=", "get_stats", "(", "'python-bogus-project-honeypot'", ")", "if", "not", "honeypot", ":", "raise", "RuntimeError", "(", "\"Could not get honeypot data\"", ")", "honeypot", "=", "honeypot", "[", "'releases'", "]", "# Add a field used to store diff when choosing the best honey pot release", "# for some statistic", "for", "x", "in", "honeypot", ":", "x", "[", "'diff'", "]", "=", "0", "stats", ",", "__", ",", "version", "=", "get_stats", "(", "package", ")", "if", "not", "stats", ":", "return", "# Denote release date diff and choose the honey pot release that's closest", "# to the one of each release", "releases", "=", "stats", "[", "'releases'", "]", "for", "release", "in", "releases", ":", "# Sort by absolute difference", "honeypot", ".", "sort", "(", "key", "=", "lambda", "x", ":", "abs", "(", "(", "x", "[", "'upload_time'", "]", "-", "release", "[", "'upload_time'", "]", ")", ".", "total_seconds", "(", ")", ")", ")", "# Multiple candidates", "honeypot_filtered", "=", "list", "(", "filter", "(", "lambda", "x", ":", "x", "[", "'diff'", "]", "==", "honeypot", "[", "0", "]", "[", "'diff'", "]", ",", "honeypot", ")", ")", "average_downloads", "=", "sum", "(", "[", "x", "[", "'downloads'", "]", "for", "x", "in", "honeypot_filtered", "]", ")", "/", "len", "(", "honeypot_filtered", ")", "release", "[", "'downloads'", "]", "=", "release", "[", "'downloads'", "]", "-", "average_downloads", "# Re-calculate totals", "total_count", "=", "sum", "(", "[", "x", "[", "'downloads'", "]", "for", "x", "in", "releases", "]", ")", "return", "stats", ",", "total_count", ",", "version" ]
Fetches statistics for `package` and then corrects them using a special honeypot.
[ "Fetches", "statistics", "for", "package", "and", "then", "corrects", "them", "using", "a", "special", "honeypot", "." ]
de93b94877004ae18a5c8e5b96b213aa38fb29a8
https://github.com/benjaoming/simple-pypi-statistics/blob/de93b94877004ae18a5c8e5b96b213aa38fb29a8/simple_pypi_statistics/api.py#L191-L233
245,704
foxx/python-helpful
helpful.py
ensure_subclass
def ensure_subclass(value, types): """ Ensure value is a subclass of types >>> class Hello(object): pass >>> ensure_subclass(Hello, Hello) >>> ensure_subclass(object, Hello) Traceback (most recent call last): TypeError: """ ensure_class(value) if not issubclass(value, types): raise TypeError( "expected subclass of {}, not {}".format( types, value))
python
def ensure_subclass(value, types): """ Ensure value is a subclass of types >>> class Hello(object): pass >>> ensure_subclass(Hello, Hello) >>> ensure_subclass(object, Hello) Traceback (most recent call last): TypeError: """ ensure_class(value) if not issubclass(value, types): raise TypeError( "expected subclass of {}, not {}".format( types, value))
[ "def", "ensure_subclass", "(", "value", ",", "types", ")", ":", "ensure_class", "(", "value", ")", "if", "not", "issubclass", "(", "value", ",", "types", ")", ":", "raise", "TypeError", "(", "\"expected subclass of {}, not {}\"", ".", "format", "(", "types", ",", "value", ")", ")" ]
Ensure value is a subclass of types >>> class Hello(object): pass >>> ensure_subclass(Hello, Hello) >>> ensure_subclass(object, Hello) Traceback (most recent call last): TypeError:
[ "Ensure", "value", "is", "a", "subclass", "of", "types" ]
e31ad9bdf45051d8b9a0d1808d214e2293c3bbed
https://github.com/foxx/python-helpful/blob/e31ad9bdf45051d8b9a0d1808d214e2293c3bbed/helpful.py#L157-L171
245,705
foxx/python-helpful
helpful.py
ensure_instance
def ensure_instance(value, types): """ Ensure value is an instance of a certain type >>> ensure_instance(1, [str]) Traceback (most recent call last): TypeError: >>> ensure_instance(1, str) Traceback (most recent call last): TypeError: >>> ensure_instance(1, int) >>> ensure_instance(1, (int, str)) :attr types: Type of list of types """ if not isinstance(value, types): raise TypeError( "expected instance of {}, got {}".format( types, value))
python
def ensure_instance(value, types): """ Ensure value is an instance of a certain type >>> ensure_instance(1, [str]) Traceback (most recent call last): TypeError: >>> ensure_instance(1, str) Traceback (most recent call last): TypeError: >>> ensure_instance(1, int) >>> ensure_instance(1, (int, str)) :attr types: Type of list of types """ if not isinstance(value, types): raise TypeError( "expected instance of {}, got {}".format( types, value))
[ "def", "ensure_instance", "(", "value", ",", "types", ")", ":", "if", "not", "isinstance", "(", "value", ",", "types", ")", ":", "raise", "TypeError", "(", "\"expected instance of {}, got {}\"", ".", "format", "(", "types", ",", "value", ")", ")" ]
Ensure value is an instance of a certain type >>> ensure_instance(1, [str]) Traceback (most recent call last): TypeError: >>> ensure_instance(1, str) Traceback (most recent call last): TypeError: >>> ensure_instance(1, int) >>> ensure_instance(1, (int, str)) :attr types: Type of list of types
[ "Ensure", "value", "is", "an", "instance", "of", "a", "certain", "type" ]
e31ad9bdf45051d8b9a0d1808d214e2293c3bbed
https://github.com/foxx/python-helpful/blob/e31ad9bdf45051d8b9a0d1808d214e2293c3bbed/helpful.py#L173-L193
245,706
foxx/python-helpful
helpful.py
iter_ensure_instance
def iter_ensure_instance(iterable, types): """ Iterate over object and check each item type >>> iter_ensure_instance([1,2,3], [str]) Traceback (most recent call last): TypeError: >>> iter_ensure_instance([1,2,3], int) >>> iter_ensure_instance(1, int) Traceback (most recent call last): TypeError: """ ensure_instance(iterable, Iterable) [ ensure_instance(item, types) for item in iterable ]
python
def iter_ensure_instance(iterable, types): """ Iterate over object and check each item type >>> iter_ensure_instance([1,2,3], [str]) Traceback (most recent call last): TypeError: >>> iter_ensure_instance([1,2,3], int) >>> iter_ensure_instance(1, int) Traceback (most recent call last): TypeError: """ ensure_instance(iterable, Iterable) [ ensure_instance(item, types) for item in iterable ]
[ "def", "iter_ensure_instance", "(", "iterable", ",", "types", ")", ":", "ensure_instance", "(", "iterable", ",", "Iterable", ")", "[", "ensure_instance", "(", "item", ",", "types", ")", "for", "item", "in", "iterable", "]" ]
Iterate over object and check each item type >>> iter_ensure_instance([1,2,3], [str]) Traceback (most recent call last): TypeError: >>> iter_ensure_instance([1,2,3], int) >>> iter_ensure_instance(1, int) Traceback (most recent call last): TypeError:
[ "Iterate", "over", "object", "and", "check", "each", "item", "type" ]
e31ad9bdf45051d8b9a0d1808d214e2293c3bbed
https://github.com/foxx/python-helpful/blob/e31ad9bdf45051d8b9a0d1808d214e2293c3bbed/helpful.py#L196-L209
245,707
foxx/python-helpful
helpful.py
add_bases
def add_bases(cls, *bases): """ Add bases to class >>> class Base(object): pass >>> class A(Base): pass >>> class B(Base): pass >>> issubclass(A, B) False >>> add_bases(A, B) >>> issubclass(A, B) True """ assert inspect.isclass(cls), "Expected class object" for mixin in bases: assert inspect.isclass(mixin), "Expected class object for bases" new_bases = (bases + cls.__bases__) cls.__bases__ = new_bases
python
def add_bases(cls, *bases): """ Add bases to class >>> class Base(object): pass >>> class A(Base): pass >>> class B(Base): pass >>> issubclass(A, B) False >>> add_bases(A, B) >>> issubclass(A, B) True """ assert inspect.isclass(cls), "Expected class object" for mixin in bases: assert inspect.isclass(mixin), "Expected class object for bases" new_bases = (bases + cls.__bases__) cls.__bases__ = new_bases
[ "def", "add_bases", "(", "cls", ",", "*", "bases", ")", ":", "assert", "inspect", ".", "isclass", "(", "cls", ")", ",", "\"Expected class object\"", "for", "mixin", "in", "bases", ":", "assert", "inspect", ".", "isclass", "(", "mixin", ")", ",", "\"Expected class object for bases\"", "new_bases", "=", "(", "bases", "+", "cls", ".", "__bases__", ")", "cls", ".", "__bases__", "=", "new_bases" ]
Add bases to class >>> class Base(object): pass >>> class A(Base): pass >>> class B(Base): pass >>> issubclass(A, B) False >>> add_bases(A, B) >>> issubclass(A, B) True
[ "Add", "bases", "to", "class" ]
e31ad9bdf45051d8b9a0d1808d214e2293c3bbed
https://github.com/foxx/python-helpful/blob/e31ad9bdf45051d8b9a0d1808d214e2293c3bbed/helpful.py#L284-L301
245,708
foxx/python-helpful
helpful.py
sort_dict_by_key
def sort_dict_by_key(obj): """ Sort dict by its keys >>> sort_dict_by_key(dict(c=1, b=2, a=3, d=4)) OrderedDict([('a', 3), ('b', 2), ('c', 1), ('d', 4)]) """ sort_func = lambda x: x[0] return OrderedDict(sorted(obj.items(), key=sort_func))
python
def sort_dict_by_key(obj): """ Sort dict by its keys >>> sort_dict_by_key(dict(c=1, b=2, a=3, d=4)) OrderedDict([('a', 3), ('b', 2), ('c', 1), ('d', 4)]) """ sort_func = lambda x: x[0] return OrderedDict(sorted(obj.items(), key=sort_func))
[ "def", "sort_dict_by_key", "(", "obj", ")", ":", "sort_func", "=", "lambda", "x", ":", "x", "[", "0", "]", "return", "OrderedDict", "(", "sorted", "(", "obj", ".", "items", "(", ")", ",", "key", "=", "sort_func", ")", ")" ]
Sort dict by its keys >>> sort_dict_by_key(dict(c=1, b=2, a=3, d=4)) OrderedDict([('a', 3), ('b', 2), ('c', 1), ('d', 4)])
[ "Sort", "dict", "by", "its", "keys" ]
e31ad9bdf45051d8b9a0d1808d214e2293c3bbed
https://github.com/foxx/python-helpful/blob/e31ad9bdf45051d8b9a0d1808d214e2293c3bbed/helpful.py#L384-L392
245,709
foxx/python-helpful
helpful.py
generate_random_token
def generate_random_token(length=32): """ Generate random secure token >>> len(generate_random_token()) 32 >>> len(generate_random_token(6)) 6 """ chars = (string.ascii_lowercase + string.ascii_uppercase + string.digits) return ''.join(random.choice(chars) for _ in range(length))
python
def generate_random_token(length=32): """ Generate random secure token >>> len(generate_random_token()) 32 >>> len(generate_random_token(6)) 6 """ chars = (string.ascii_lowercase + string.ascii_uppercase + string.digits) return ''.join(random.choice(chars) for _ in range(length))
[ "def", "generate_random_token", "(", "length", "=", "32", ")", ":", "chars", "=", "(", "string", ".", "ascii_lowercase", "+", "string", ".", "ascii_uppercase", "+", "string", ".", "digits", ")", "return", "''", ".", "join", "(", "random", ".", "choice", "(", "chars", ")", "for", "_", "in", "range", "(", "length", ")", ")" ]
Generate random secure token >>> len(generate_random_token()) 32 >>> len(generate_random_token(6)) 6
[ "Generate", "random", "secure", "token" ]
e31ad9bdf45051d8b9a0d1808d214e2293c3bbed
https://github.com/foxx/python-helpful/blob/e31ad9bdf45051d8b9a0d1808d214e2293c3bbed/helpful.py#L395-L405
245,710
foxx/python-helpful
helpful.py
default
def default(*args, **kwargs): """ Return first argument which is "truthy" >>> default(None, None, 1) 1 >>> default(None, None, 123) 123 >>> print(default(None, None)) None """ default = kwargs.get('default', None) for arg in args: if arg: return arg return default
python
def default(*args, **kwargs): """ Return first argument which is "truthy" >>> default(None, None, 1) 1 >>> default(None, None, 123) 123 >>> print(default(None, None)) None """ default = kwargs.get('default', None) for arg in args: if arg: return arg return default
[ "def", "default", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "default", "=", "kwargs", ".", "get", "(", "'default'", ",", "None", ")", "for", "arg", "in", "args", ":", "if", "arg", ":", "return", "arg", "return", "default" ]
Return first argument which is "truthy" >>> default(None, None, 1) 1 >>> default(None, None, 123) 123 >>> print(default(None, None)) None
[ "Return", "first", "argument", "which", "is", "truthy" ]
e31ad9bdf45051d8b9a0d1808d214e2293c3bbed
https://github.com/foxx/python-helpful/blob/e31ad9bdf45051d8b9a0d1808d214e2293c3bbed/helpful.py#L408-L423
245,711
foxx/python-helpful
helpful.py
is_int
def is_int(value): """ Check if value is an int :type value: int, str, bytes, float, Decimal >>> is_int(123), is_int('123'), is_int(Decimal('10')) (True, True, True) >>> is_int(1.1), is_int('1.1'), is_int(Decimal('10.1')) (False, False, False) >>> is_int(object) Traceback (most recent call last): TypeError: """ ensure_instance(value, (int, str, bytes, float, Decimal)) if isinstance(value, int): return True elif isinstance(value, float): return False elif isinstance(value, Decimal): return str(value).isdigit() elif isinstance(value, (str, bytes)): return value.isdigit() raise ValueError()
python
def is_int(value): """ Check if value is an int :type value: int, str, bytes, float, Decimal >>> is_int(123), is_int('123'), is_int(Decimal('10')) (True, True, True) >>> is_int(1.1), is_int('1.1'), is_int(Decimal('10.1')) (False, False, False) >>> is_int(object) Traceback (most recent call last): TypeError: """ ensure_instance(value, (int, str, bytes, float, Decimal)) if isinstance(value, int): return True elif isinstance(value, float): return False elif isinstance(value, Decimal): return str(value).isdigit() elif isinstance(value, (str, bytes)): return value.isdigit() raise ValueError()
[ "def", "is_int", "(", "value", ")", ":", "ensure_instance", "(", "value", ",", "(", "int", ",", "str", ",", "bytes", ",", "float", ",", "Decimal", ")", ")", "if", "isinstance", "(", "value", ",", "int", ")", ":", "return", "True", "elif", "isinstance", "(", "value", ",", "float", ")", ":", "return", "False", "elif", "isinstance", "(", "value", ",", "Decimal", ")", ":", "return", "str", "(", "value", ")", ".", "isdigit", "(", ")", "elif", "isinstance", "(", "value", ",", "(", "str", ",", "bytes", ")", ")", ":", "return", "value", ".", "isdigit", "(", ")", "raise", "ValueError", "(", ")" ]
Check if value is an int :type value: int, str, bytes, float, Decimal >>> is_int(123), is_int('123'), is_int(Decimal('10')) (True, True, True) >>> is_int(1.1), is_int('1.1'), is_int(Decimal('10.1')) (False, False, False) >>> is_int(object) Traceback (most recent call last): TypeError:
[ "Check", "if", "value", "is", "an", "int" ]
e31ad9bdf45051d8b9a0d1808d214e2293c3bbed
https://github.com/foxx/python-helpful/blob/e31ad9bdf45051d8b9a0d1808d214e2293c3bbed/helpful.py#L455-L478
245,712
foxx/python-helpful
helpful.py
coerce_to_bytes
def coerce_to_bytes(x, charset=sys.getdefaultencoding(), errors='strict'): """ Coerce value to bytes >>> a = coerce_to_bytes('hello') >>> assert isinstance(a, bytes) >>> a = coerce_to_bytes(b'hello') >>> assert isinstance(a, bytes) >>> a = coerce_to_bytes(None) >>> assert a is None >>> coerce_to_bytes(object()) Traceback (most recent call last): ... TypeError: Cannot coerce to bytes """ PY2 = sys.version_info[0] == 2 if PY2: # pragma: nocover if x is None: return None if isinstance(x, (bytes, bytearray, buffer)): return bytes(x) if isinstance(x, unicode): return x.encode(charset, errors) raise TypeError('Cannot coerce to bytes') else: # pragma: nocover if x is None: return None if isinstance(x, (bytes, bytearray, memoryview)): return bytes(x) if isinstance(x, str): return x.encode(charset, errors) raise TypeError('Cannot coerce to bytes')
python
def coerce_to_bytes(x, charset=sys.getdefaultencoding(), errors='strict'): """ Coerce value to bytes >>> a = coerce_to_bytes('hello') >>> assert isinstance(a, bytes) >>> a = coerce_to_bytes(b'hello') >>> assert isinstance(a, bytes) >>> a = coerce_to_bytes(None) >>> assert a is None >>> coerce_to_bytes(object()) Traceback (most recent call last): ... TypeError: Cannot coerce to bytes """ PY2 = sys.version_info[0] == 2 if PY2: # pragma: nocover if x is None: return None if isinstance(x, (bytes, bytearray, buffer)): return bytes(x) if isinstance(x, unicode): return x.encode(charset, errors) raise TypeError('Cannot coerce to bytes') else: # pragma: nocover if x is None: return None if isinstance(x, (bytes, bytearray, memoryview)): return bytes(x) if isinstance(x, str): return x.encode(charset, errors) raise TypeError('Cannot coerce to bytes')
[ "def", "coerce_to_bytes", "(", "x", ",", "charset", "=", "sys", ".", "getdefaultencoding", "(", ")", ",", "errors", "=", "'strict'", ")", ":", "PY2", "=", "sys", ".", "version_info", "[", "0", "]", "==", "2", "if", "PY2", ":", "# pragma: nocover", "if", "x", "is", "None", ":", "return", "None", "if", "isinstance", "(", "x", ",", "(", "bytes", ",", "bytearray", ",", "buffer", ")", ")", ":", "return", "bytes", "(", "x", ")", "if", "isinstance", "(", "x", ",", "unicode", ")", ":", "return", "x", ".", "encode", "(", "charset", ",", "errors", ")", "raise", "TypeError", "(", "'Cannot coerce to bytes'", ")", "else", ":", "# pragma: nocover", "if", "x", "is", "None", ":", "return", "None", "if", "isinstance", "(", "x", ",", "(", "bytes", ",", "bytearray", ",", "memoryview", ")", ")", ":", "return", "bytes", "(", "x", ")", "if", "isinstance", "(", "x", ",", "str", ")", ":", "return", "x", ".", "encode", "(", "charset", ",", "errors", ")", "raise", "TypeError", "(", "'Cannot coerce to bytes'", ")" ]
Coerce value to bytes >>> a = coerce_to_bytes('hello') >>> assert isinstance(a, bytes) >>> a = coerce_to_bytes(b'hello') >>> assert isinstance(a, bytes) >>> a = coerce_to_bytes(None) >>> assert a is None >>> coerce_to_bytes(object()) Traceback (most recent call last): ... TypeError: Cannot coerce to bytes
[ "Coerce", "value", "to", "bytes" ]
e31ad9bdf45051d8b9a0d1808d214e2293c3bbed
https://github.com/foxx/python-helpful/blob/e31ad9bdf45051d8b9a0d1808d214e2293c3bbed/helpful.py#L511-L543
245,713
foxx/python-helpful
helpful.py
Tempfile.cleanup
def cleanup(self): """Remove any created temp paths""" for path in self.paths: if isinstance(path, tuple): os.close(path[0]) os.unlink(path[1]) else: shutil.rmtree(path) self.paths = []
python
def cleanup(self): """Remove any created temp paths""" for path in self.paths: if isinstance(path, tuple): os.close(path[0]) os.unlink(path[1]) else: shutil.rmtree(path) self.paths = []
[ "def", "cleanup", "(", "self", ")", ":", "for", "path", "in", "self", ".", "paths", ":", "if", "isinstance", "(", "path", ",", "tuple", ")", ":", "os", ".", "close", "(", "path", "[", "0", "]", ")", "os", ".", "unlink", "(", "path", "[", "1", "]", ")", "else", ":", "shutil", ".", "rmtree", "(", "path", ")", "self", ".", "paths", "=", "[", "]" ]
Remove any created temp paths
[ "Remove", "any", "created", "temp", "paths" ]
e31ad9bdf45051d8b9a0d1808d214e2293c3bbed
https://github.com/foxx/python-helpful/blob/e31ad9bdf45051d8b9a0d1808d214e2293c3bbed/helpful.py#L599-L607
245,714
aganezov/gos
gos/tmp/scaffolding_no_repeats.py
get_vertex_surrounding_multicolor
def get_vertex_surrounding_multicolor(graph, vertex): """ Loops over all edges that are incident to supplied vertex and accumulates all colors, that are present in those edges """ result = Multicolor() for edge in graph.get_edges_by_vertex(vertex): result += edge.multicolor return result
python
def get_vertex_surrounding_multicolor(graph, vertex): """ Loops over all edges that are incident to supplied vertex and accumulates all colors, that are present in those edges """ result = Multicolor() for edge in graph.get_edges_by_vertex(vertex): result += edge.multicolor return result
[ "def", "get_vertex_surrounding_multicolor", "(", "graph", ",", "vertex", ")", ":", "result", "=", "Multicolor", "(", ")", "for", "edge", "in", "graph", ".", "get_edges_by_vertex", "(", "vertex", ")", ":", "result", "+=", "edge", ".", "multicolor", "return", "result" ]
Loops over all edges that are incident to supplied vertex and accumulates all colors, that are present in those edges
[ "Loops", "over", "all", "edges", "that", "are", "incident", "to", "supplied", "vertex", "and", "accumulates", "all", "colors", "that", "are", "present", "in", "those", "edges" ]
fb4d210284f3037c5321250cb95f3901754feb6b
https://github.com/aganezov/gos/blob/fb4d210284f3037c5321250cb95f3901754feb6b/gos/tmp/scaffolding_no_repeats.py#L19-L27
245,715
aganezov/gos
gos/tmp/scaffolding_no_repeats.py
get_irregular_edge_by_vertex
def get_irregular_edge_by_vertex(graph, vertex): """ Loops over all edges that are incident to supplied vertex and return a first irregular edge in "no repeat" scenario such irregular edge can be only one for any given supplied vertex """ for edge in graph.get_edges_by_vertex(vertex): if edge.is_irregular_edge: return edge return None
python
def get_irregular_edge_by_vertex(graph, vertex): """ Loops over all edges that are incident to supplied vertex and return a first irregular edge in "no repeat" scenario such irregular edge can be only one for any given supplied vertex """ for edge in graph.get_edges_by_vertex(vertex): if edge.is_irregular_edge: return edge return None
[ "def", "get_irregular_edge_by_vertex", "(", "graph", ",", "vertex", ")", ":", "for", "edge", "in", "graph", ".", "get_edges_by_vertex", "(", "vertex", ")", ":", "if", "edge", ".", "is_irregular_edge", ":", "return", "edge", "return", "None" ]
Loops over all edges that are incident to supplied vertex and return a first irregular edge in "no repeat" scenario such irregular edge can be only one for any given supplied vertex
[ "Loops", "over", "all", "edges", "that", "are", "incident", "to", "supplied", "vertex", "and", "return", "a", "first", "irregular", "edge", "in", "no", "repeat", "scenario", "such", "irregular", "edge", "can", "be", "only", "one", "for", "any", "given", "supplied", "vertex" ]
fb4d210284f3037c5321250cb95f3901754feb6b
https://github.com/aganezov/gos/blob/fb4d210284f3037c5321250cb95f3901754feb6b/gos/tmp/scaffolding_no_repeats.py#L30-L38
245,716
aganezov/gos
gos/tmp/scaffolding_no_repeats.py
assemble_points
def assemble_points(graph, assemblies, multicolor, verbose=False, verbose_destination=None): """ This function actually does assembling being provided a graph, to play with a list of assembly points and a multicolor, which to assemble """ if verbose: print(">>Assembling for multicolor", [e.name for e in multicolor.multicolors.elements()], file=verbose_destination) for assembly in assemblies: v1, v2, (before, after, ex_data) = assembly iv1 = get_irregular_vertex(get_irregular_edge_by_vertex(graph, vertex=v1)) iv2 = get_irregular_vertex(get_irregular_edge_by_vertex(graph, vertex=v2)) kbreak = KBreak(start_edges=[(v1, iv1), (v2, iv2)], result_edges=[(v1, v2), (iv1, iv2)], multicolor=multicolor) if verbose: print("(", v1.name, ",", iv1.name, ")x(", v2.name, ",", iv2.name, ")", " score=", before - after, sep="", file=verbose_destination) graph.apply_kbreak(kbreak=kbreak, merge=True)
python
def assemble_points(graph, assemblies, multicolor, verbose=False, verbose_destination=None): """ This function actually does assembling being provided a graph, to play with a list of assembly points and a multicolor, which to assemble """ if verbose: print(">>Assembling for multicolor", [e.name for e in multicolor.multicolors.elements()], file=verbose_destination) for assembly in assemblies: v1, v2, (before, after, ex_data) = assembly iv1 = get_irregular_vertex(get_irregular_edge_by_vertex(graph, vertex=v1)) iv2 = get_irregular_vertex(get_irregular_edge_by_vertex(graph, vertex=v2)) kbreak = KBreak(start_edges=[(v1, iv1), (v2, iv2)], result_edges=[(v1, v2), (iv1, iv2)], multicolor=multicolor) if verbose: print("(", v1.name, ",", iv1.name, ")x(", v2.name, ",", iv2.name, ")", " score=", before - after, sep="", file=verbose_destination) graph.apply_kbreak(kbreak=kbreak, merge=True)
[ "def", "assemble_points", "(", "graph", ",", "assemblies", ",", "multicolor", ",", "verbose", "=", "False", ",", "verbose_destination", "=", "None", ")", ":", "if", "verbose", ":", "print", "(", "\">>Assembling for multicolor\"", ",", "[", "e", ".", "name", "for", "e", "in", "multicolor", ".", "multicolors", ".", "elements", "(", ")", "]", ",", "file", "=", "verbose_destination", ")", "for", "assembly", "in", "assemblies", ":", "v1", ",", "v2", ",", "(", "before", ",", "after", ",", "ex_data", ")", "=", "assembly", "iv1", "=", "get_irregular_vertex", "(", "get_irregular_edge_by_vertex", "(", "graph", ",", "vertex", "=", "v1", ")", ")", "iv2", "=", "get_irregular_vertex", "(", "get_irregular_edge_by_vertex", "(", "graph", ",", "vertex", "=", "v2", ")", ")", "kbreak", "=", "KBreak", "(", "start_edges", "=", "[", "(", "v1", ",", "iv1", ")", ",", "(", "v2", ",", "iv2", ")", "]", ",", "result_edges", "=", "[", "(", "v1", ",", "v2", ")", ",", "(", "iv1", ",", "iv2", ")", "]", ",", "multicolor", "=", "multicolor", ")", "if", "verbose", ":", "print", "(", "\"(\"", ",", "v1", ".", "name", ",", "\",\"", ",", "iv1", ".", "name", ",", "\")x(\"", ",", "v2", ".", "name", ",", "\",\"", ",", "iv2", ".", "name", ",", "\")\"", ",", "\" score=\"", ",", "before", "-", "after", ",", "sep", "=", "\"\"", ",", "file", "=", "verbose_destination", ")", "graph", ".", "apply_kbreak", "(", "kbreak", "=", "kbreak", ",", "merge", "=", "True", ")" ]
This function actually does assembling being provided a graph, to play with a list of assembly points and a multicolor, which to assemble
[ "This", "function", "actually", "does", "assembling", "being", "provided", "a", "graph", "to", "play", "with", "a", "list", "of", "assembly", "points", "and", "a", "multicolor", "which", "to", "assemble" ]
fb4d210284f3037c5321250cb95f3901754feb6b
https://github.com/aganezov/gos/blob/fb4d210284f3037c5321250cb95f3901754feb6b/gos/tmp/scaffolding_no_repeats.py#L403-L423
245,717
shad7/tvdbapi_client
tvdbapi_client/exceptions.py
error_map
def error_map(func): """Wrap exceptions raised by requests. .. py:decorator:: error_map """ @six.wraps(func) def wrapper(*args, **kwargs): try: return func(*args, **kwargs) except exceptions.RequestException as err: raise TVDBRequestException( err, response=getattr(err, 'response', None), request=getattr(err, 'request', None)) return wrapper
python
def error_map(func): """Wrap exceptions raised by requests. .. py:decorator:: error_map """ @six.wraps(func) def wrapper(*args, **kwargs): try: return func(*args, **kwargs) except exceptions.RequestException as err: raise TVDBRequestException( err, response=getattr(err, 'response', None), request=getattr(err, 'request', None)) return wrapper
[ "def", "error_map", "(", "func", ")", ":", "@", "six", ".", "wraps", "(", "func", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "return", "func", "(", "*", "args", ",", "*", "*", "kwargs", ")", "except", "exceptions", ".", "RequestException", "as", "err", ":", "raise", "TVDBRequestException", "(", "err", ",", "response", "=", "getattr", "(", "err", ",", "'response'", ",", "None", ")", ",", "request", "=", "getattr", "(", "err", ",", "'request'", ",", "None", ")", ")", "return", "wrapper" ]
Wrap exceptions raised by requests. .. py:decorator:: error_map
[ "Wrap", "exceptions", "raised", "by", "requests", "." ]
edf1771184122f4db42af7fc087407a3e6a4e377
https://github.com/shad7/tvdbapi_client/blob/edf1771184122f4db42af7fc087407a3e6a4e377/tvdbapi_client/exceptions.py#L6-L20
245,718
eeue56/PyChat.js
pychatjs/server/protocol.py
create_message
def create_message(username, message): """ Creates a standard message from a given user with the message Replaces newline with html break """ message = message.replace('\n', '<br/>') return '{{"service":1, "data":{{"message":"{mes}", "username":"{user}"}} }}'.format(mes=message, user=username)
python
def create_message(username, message): """ Creates a standard message from a given user with the message Replaces newline with html break """ message = message.replace('\n', '<br/>') return '{{"service":1, "data":{{"message":"{mes}", "username":"{user}"}} }}'.format(mes=message, user=username)
[ "def", "create_message", "(", "username", ",", "message", ")", ":", "message", "=", "message", ".", "replace", "(", "'\\n'", ",", "'<br/>'", ")", "return", "'{{\"service\":1, \"data\":{{\"message\":\"{mes}\", \"username\":\"{user}\"}} }}'", ".", "format", "(", "mes", "=", "message", ",", "user", "=", "username", ")" ]
Creates a standard message from a given user with the message Replaces newline with html break
[ "Creates", "a", "standard", "message", "from", "a", "given", "user", "with", "the", "message", "Replaces", "newline", "with", "html", "break" ]
45056de6f988350c90a6dbe674459a4affde8abc
https://github.com/eeue56/PyChat.js/blob/45056de6f988350c90a6dbe674459a4affde8abc/pychatjs/server/protocol.py#L17-L21
245,719
FreshXOpenSource/wallaby-frontend-qt
wallaby/frontends/qt/reactor/qt4reactor.py
QtReactor._add
def _add(self, xer, primary, type): """ Private method for adding a descriptor from the event loop. It takes care of adding it if new or modifying it if already added for another state (read -> read/write for example). """ if xer not in primary: primary[xer] = TwistedSocketNotifier(None, self, xer, type)
python
def _add(self, xer, primary, type): """ Private method for adding a descriptor from the event loop. It takes care of adding it if new or modifying it if already added for another state (read -> read/write for example). """ if xer not in primary: primary[xer] = TwistedSocketNotifier(None, self, xer, type)
[ "def", "_add", "(", "self", ",", "xer", ",", "primary", ",", "type", ")", ":", "if", "xer", "not", "in", "primary", ":", "primary", "[", "xer", "]", "=", "TwistedSocketNotifier", "(", "None", ",", "self", ",", "xer", ",", "type", ")" ]
Private method for adding a descriptor from the event loop. It takes care of adding it if new or modifying it if already added for another state (read -> read/write for example).
[ "Private", "method", "for", "adding", "a", "descriptor", "from", "the", "event", "loop", "." ]
eee70d0ec4ce34827f62a1654e28dbff8a8afb1a
https://github.com/FreshXOpenSource/wallaby-frontend-qt/blob/eee70d0ec4ce34827f62a1654e28dbff8a8afb1a/wallaby/frontends/qt/reactor/qt4reactor.py#L146-L154
245,720
FreshXOpenSource/wallaby-frontend-qt
wallaby/frontends/qt/reactor/qt4reactor.py
QtReactor._remove
def _remove(self, xer, primary): """ Private method for removing a descriptor from the event loop. It does the inverse job of _add, and also add a check in case of the fd has gone away. """ if xer in primary: notifier = primary.pop(xer) notifier.shutdown()
python
def _remove(self, xer, primary): """ Private method for removing a descriptor from the event loop. It does the inverse job of _add, and also add a check in case of the fd has gone away. """ if xer in primary: notifier = primary.pop(xer) notifier.shutdown()
[ "def", "_remove", "(", "self", ",", "xer", ",", "primary", ")", ":", "if", "xer", "in", "primary", ":", "notifier", "=", "primary", ".", "pop", "(", "xer", ")", "notifier", ".", "shutdown", "(", ")" ]
Private method for removing a descriptor from the event loop. It does the inverse job of _add, and also add a check in case of the fd has gone away.
[ "Private", "method", "for", "removing", "a", "descriptor", "from", "the", "event", "loop", "." ]
eee70d0ec4ce34827f62a1654e28dbff8a8afb1a
https://github.com/FreshXOpenSource/wallaby-frontend-qt/blob/eee70d0ec4ce34827f62a1654e28dbff8a8afb1a/wallaby/frontends/qt/reactor/qt4reactor.py#L171-L180
245,721
FreshXOpenSource/wallaby-frontend-qt
wallaby/frontends/qt/reactor/qt4reactor.py
QtReactor.removeAll
def removeAll(self): """ Remove all selectables, and return a list of them. """ rv = self._removeAll(self._reads, self._writes) return rv
python
def removeAll(self): """ Remove all selectables, and return a list of them. """ rv = self._removeAll(self._reads, self._writes) return rv
[ "def", "removeAll", "(", "self", ")", ":", "rv", "=", "self", ".", "_removeAll", "(", "self", ".", "_reads", ",", "self", ".", "_writes", ")", "return", "rv" ]
Remove all selectables, and return a list of them.
[ "Remove", "all", "selectables", "and", "return", "a", "list", "of", "them", "." ]
eee70d0ec4ce34827f62a1654e28dbff8a8afb1a
https://github.com/FreshXOpenSource/wallaby-frontend-qt/blob/eee70d0ec4ce34827f62a1654e28dbff8a8afb1a/wallaby/frontends/qt/reactor/qt4reactor.py#L197-L202
245,722
FreshXOpenSource/wallaby-frontend-qt
wallaby/frontends/qt/reactor/qt4reactor.py
QtReactor.doIteration
def doIteration(self, delay=None, fromqt=False): 'This method is called by a Qt timer or by network activity on a file descriptor' if not self.running and self._blockApp: self._blockApp.quit() self._timer.stop() delay = max(delay, 1) if not fromqt: self.qApp.processEvents(QtCore.QEventLoop.AllEvents, delay * 1000) if self.timeout() is None: timeout = 0.1 elif self.timeout() == 0: timeout = 0 else: timeout = self.timeout() self._timer.setInterval(timeout * 1000) self._timer.start()
python
def doIteration(self, delay=None, fromqt=False): 'This method is called by a Qt timer or by network activity on a file descriptor' if not self.running and self._blockApp: self._blockApp.quit() self._timer.stop() delay = max(delay, 1) if not fromqt: self.qApp.processEvents(QtCore.QEventLoop.AllEvents, delay * 1000) if self.timeout() is None: timeout = 0.1 elif self.timeout() == 0: timeout = 0 else: timeout = self.timeout() self._timer.setInterval(timeout * 1000) self._timer.start()
[ "def", "doIteration", "(", "self", ",", "delay", "=", "None", ",", "fromqt", "=", "False", ")", ":", "if", "not", "self", ".", "running", "and", "self", ".", "_blockApp", ":", "self", ".", "_blockApp", ".", "quit", "(", ")", "self", ".", "_timer", ".", "stop", "(", ")", "delay", "=", "max", "(", "delay", ",", "1", ")", "if", "not", "fromqt", ":", "self", ".", "qApp", ".", "processEvents", "(", "QtCore", ".", "QEventLoop", ".", "AllEvents", ",", "delay", "*", "1000", ")", "if", "self", ".", "timeout", "(", ")", "is", "None", ":", "timeout", "=", "0.1", "elif", "self", ".", "timeout", "(", ")", "==", "0", ":", "timeout", "=", "0", "else", ":", "timeout", "=", "self", ".", "timeout", "(", ")", "self", ".", "_timer", ".", "setInterval", "(", "timeout", "*", "1000", ")", "self", ".", "_timer", ".", "start", "(", ")" ]
This method is called by a Qt timer or by network activity on a file descriptor
[ "This", "method", "is", "called", "by", "a", "Qt", "timer", "or", "by", "network", "activity", "on", "a", "file", "descriptor" ]
eee70d0ec4ce34827f62a1654e28dbff8a8afb1a
https://github.com/FreshXOpenSource/wallaby-frontend-qt/blob/eee70d0ec4ce34827f62a1654e28dbff8a8afb1a/wallaby/frontends/qt/reactor/qt4reactor.py#L233-L249
245,723
FreshXOpenSource/wallaby-frontend-qt
wallaby/frontends/qt/reactor/qt4reactor.py
QtEventReactor.addEvent
def addEvent(self, event, fd, action): """ Add a new win32 event to the event loop. """ self._events[event] = (fd, action)
python
def addEvent(self, event, fd, action): """ Add a new win32 event to the event loop. """ self._events[event] = (fd, action)
[ "def", "addEvent", "(", "self", ",", "event", ",", "fd", ",", "action", ")", ":", "self", ".", "_events", "[", "event", "]", "=", "(", "fd", ",", "action", ")" ]
Add a new win32 event to the event loop.
[ "Add", "a", "new", "win32", "event", "to", "the", "event", "loop", "." ]
eee70d0ec4ce34827f62a1654e28dbff8a8afb1a
https://github.com/FreshXOpenSource/wallaby-frontend-qt/blob/eee70d0ec4ce34827f62a1654e28dbff8a8afb1a/wallaby/frontends/qt/reactor/qt4reactor.py#L272-L276
245,724
chrlie/howabout
src/howabout/__init__.py
get_levenshtein
def get_levenshtein(first, second): """\ Get the Levenshtein distance between two strings. :param first: the first string :param second: the second string """ if not first: return len(second) if not second: return len(first) prev_distances = range(0, len(second) + 1) curr_distances = None # Find the minimum edit distance between each substring of 'first' and # the entirety of 'second'. The first column of each distance list is # the distance from the current string to the empty string. for first_idx, first_char in enumerate(first, start=1): # Keep only the previous and current rows of the # lookup table in memory curr_distances = [first_idx] for second_idx, second_char in enumerate(second, start=1): # Take the max of the neighbors compare = [ prev_distances[second_idx - 1], prev_distances[second_idx], curr_distances[second_idx - 1], ] distance = min(*compare) if first_char != second_char: distance += 1 curr_distances.append(distance) prev_distances = curr_distances return curr_distances[-1]
python
def get_levenshtein(first, second): """\ Get the Levenshtein distance between two strings. :param first: the first string :param second: the second string """ if not first: return len(second) if not second: return len(first) prev_distances = range(0, len(second) + 1) curr_distances = None # Find the minimum edit distance between each substring of 'first' and # the entirety of 'second'. The first column of each distance list is # the distance from the current string to the empty string. for first_idx, first_char in enumerate(first, start=1): # Keep only the previous and current rows of the # lookup table in memory curr_distances = [first_idx] for second_idx, second_char in enumerate(second, start=1): # Take the max of the neighbors compare = [ prev_distances[second_idx - 1], prev_distances[second_idx], curr_distances[second_idx - 1], ] distance = min(*compare) if first_char != second_char: distance += 1 curr_distances.append(distance) prev_distances = curr_distances return curr_distances[-1]
[ "def", "get_levenshtein", "(", "first", ",", "second", ")", ":", "if", "not", "first", ":", "return", "len", "(", "second", ")", "if", "not", "second", ":", "return", "len", "(", "first", ")", "prev_distances", "=", "range", "(", "0", ",", "len", "(", "second", ")", "+", "1", ")", "curr_distances", "=", "None", "# Find the minimum edit distance between each substring of 'first' and", "# the entirety of 'second'. The first column of each distance list is", "# the distance from the current string to the empty string.", "for", "first_idx", ",", "first_char", "in", "enumerate", "(", "first", ",", "start", "=", "1", ")", ":", "# Keep only the previous and current rows of the", "# lookup table in memory", "curr_distances", "=", "[", "first_idx", "]", "for", "second_idx", ",", "second_char", "in", "enumerate", "(", "second", ",", "start", "=", "1", ")", ":", "# Take the max of the neighbors", "compare", "=", "[", "prev_distances", "[", "second_idx", "-", "1", "]", ",", "prev_distances", "[", "second_idx", "]", ",", "curr_distances", "[", "second_idx", "-", "1", "]", ",", "]", "distance", "=", "min", "(", "*", "compare", ")", "if", "first_char", "!=", "second_char", ":", "distance", "+=", "1", "curr_distances", ".", "append", "(", "distance", ")", "prev_distances", "=", "curr_distances", "return", "curr_distances", "[", "-", "1", "]" ]
\ Get the Levenshtein distance between two strings. :param first: the first string :param second: the second string
[ "\\", "Get", "the", "Levenshtein", "distance", "between", "two", "strings", "." ]
780cacbdd9156106cc77f643c75191a824b034bb
https://github.com/chrlie/howabout/blob/780cacbdd9156106cc77f643c75191a824b034bb/src/howabout/__init__.py#L6-L47
245,725
chrlie/howabout
src/howabout/__init__.py
Matcher.all_matches
def all_matches(self, target, choices, group=False, include_rank=False): """\ Get all choices listed from best match to worst match. If `group` is `True`, then matches are grouped based on their distance returned from `get_distance(target, choice)` and returned as an iterator. Otherwise, an iterator of all matches is returned. For example :: from howabout import all_matches choices = ['pot', 'cat', 'bat'] for group in all_matches('hat', choices, group=True): print(list(group)) # ['bat', 'cat'] # ['pot'] :param target: a string :param choices: a list or iterable of strings to compare with `target` string :param group: if `True`, group """ dist = self.get_distance # Keep everything here as an iterator in case we're given a lot of # choices matched = ((dist(target, choice), choice) for choice in choices) matched = sorted(matched) if group: for rank, choices in groupby(matched, key=lambda m: m[0]): yield map(lambda m: m[1], choices) else: for rank, choice in matched: yield choice
python
def all_matches(self, target, choices, group=False, include_rank=False): """\ Get all choices listed from best match to worst match. If `group` is `True`, then matches are grouped based on their distance returned from `get_distance(target, choice)` and returned as an iterator. Otherwise, an iterator of all matches is returned. For example :: from howabout import all_matches choices = ['pot', 'cat', 'bat'] for group in all_matches('hat', choices, group=True): print(list(group)) # ['bat', 'cat'] # ['pot'] :param target: a string :param choices: a list or iterable of strings to compare with `target` string :param group: if `True`, group """ dist = self.get_distance # Keep everything here as an iterator in case we're given a lot of # choices matched = ((dist(target, choice), choice) for choice in choices) matched = sorted(matched) if group: for rank, choices in groupby(matched, key=lambda m: m[0]): yield map(lambda m: m[1], choices) else: for rank, choice in matched: yield choice
[ "def", "all_matches", "(", "self", ",", "target", ",", "choices", ",", "group", "=", "False", ",", "include_rank", "=", "False", ")", ":", "dist", "=", "self", ".", "get_distance", "# Keep everything here as an iterator in case we're given a lot of", "# choices", "matched", "=", "(", "(", "dist", "(", "target", ",", "choice", ")", ",", "choice", ")", "for", "choice", "in", "choices", ")", "matched", "=", "sorted", "(", "matched", ")", "if", "group", ":", "for", "rank", ",", "choices", "in", "groupby", "(", "matched", ",", "key", "=", "lambda", "m", ":", "m", "[", "0", "]", ")", ":", "yield", "map", "(", "lambda", "m", ":", "m", "[", "1", "]", ",", "choices", ")", "else", ":", "for", "rank", ",", "choice", "in", "matched", ":", "yield", "choice" ]
\ Get all choices listed from best match to worst match. If `group` is `True`, then matches are grouped based on their distance returned from `get_distance(target, choice)` and returned as an iterator. Otherwise, an iterator of all matches is returned. For example :: from howabout import all_matches choices = ['pot', 'cat', 'bat'] for group in all_matches('hat', choices, group=True): print(list(group)) # ['bat', 'cat'] # ['pot'] :param target: a string :param choices: a list or iterable of strings to compare with `target` string :param group: if `True`, group
[ "\\", "Get", "all", "choices", "listed", "from", "best", "match", "to", "worst", "match", "." ]
780cacbdd9156106cc77f643c75191a824b034bb
https://github.com/chrlie/howabout/blob/780cacbdd9156106cc77f643c75191a824b034bb/src/howabout/__init__.py#L68-L109
245,726
chrlie/howabout
src/howabout/__init__.py
Matcher.best_matches
def best_matches(self, target, choices): """\ Get all the first choices listed from best match to worst match, optionally grouping on equal matches. :param target: :param choices: :param group: """ all = self.all_matches try: matches = next(all(target, choices, group=True)) for match in matches: yield match except StopIteration: pass
python
def best_matches(self, target, choices): """\ Get all the first choices listed from best match to worst match, optionally grouping on equal matches. :param target: :param choices: :param group: """ all = self.all_matches try: matches = next(all(target, choices, group=True)) for match in matches: yield match except StopIteration: pass
[ "def", "best_matches", "(", "self", ",", "target", ",", "choices", ")", ":", "all", "=", "self", ".", "all_matches", "try", ":", "matches", "=", "next", "(", "all", "(", "target", ",", "choices", ",", "group", "=", "True", ")", ")", "for", "match", "in", "matches", ":", "yield", "match", "except", "StopIteration", ":", "pass" ]
\ Get all the first choices listed from best match to worst match, optionally grouping on equal matches. :param target: :param choices: :param group:
[ "\\", "Get", "all", "the", "first", "choices", "listed", "from", "best", "match", "to", "worst", "match", "optionally", "grouping", "on", "equal", "matches", "." ]
780cacbdd9156106cc77f643c75191a824b034bb
https://github.com/chrlie/howabout/blob/780cacbdd9156106cc77f643c75191a824b034bb/src/howabout/__init__.py#L111-L128
245,727
chrlie/howabout
src/howabout/__init__.py
Matcher.best_match
def best_match(self, target, choices): """\ Return the best match. """ all = self.all_matches try: best = next(all(target, choices, group=False)) return best except StopIteration: pass
python
def best_match(self, target, choices): """\ Return the best match. """ all = self.all_matches try: best = next(all(target, choices, group=False)) return best except StopIteration: pass
[ "def", "best_match", "(", "self", ",", "target", ",", "choices", ")", ":", "all", "=", "self", ".", "all_matches", "try", ":", "best", "=", "next", "(", "all", "(", "target", ",", "choices", ",", "group", "=", "False", ")", ")", "return", "best", "except", "StopIteration", ":", "pass" ]
\ Return the best match.
[ "\\", "Return", "the", "best", "match", "." ]
780cacbdd9156106cc77f643c75191a824b034bb
https://github.com/chrlie/howabout/blob/780cacbdd9156106cc77f643c75191a824b034bb/src/howabout/__init__.py#L130-L141
245,728
TheOneHyer/arandomness
build/lib.linux-x86_64-3.6/arandomness/arandom/agenerator.py
agenerator
def agenerator(): """Arandom number generator""" free_mem = psutil.virtual_memory().available mem_24 = 0.24 * free_mem mem_26 = 0.26 * free_mem a = MemEater(int(mem_24)) b = MemEater(int(mem_26)) sleep(5) return free_mem/1000/1000, psutil.virtual_memory().available/1000/1000
python
def agenerator(): """Arandom number generator""" free_mem = psutil.virtual_memory().available mem_24 = 0.24 * free_mem mem_26 = 0.26 * free_mem a = MemEater(int(mem_24)) b = MemEater(int(mem_26)) sleep(5) return free_mem/1000/1000, psutil.virtual_memory().available/1000/1000
[ "def", "agenerator", "(", ")", ":", "free_mem", "=", "psutil", ".", "virtual_memory", "(", ")", ".", "available", "mem_24", "=", "0.24", "*", "free_mem", "mem_26", "=", "0.26", "*", "free_mem", "a", "=", "MemEater", "(", "int", "(", "mem_24", ")", ")", "b", "=", "MemEater", "(", "int", "(", "mem_26", ")", ")", "sleep", "(", "5", ")", "return", "free_mem", "/", "1000", "/", "1000", ",", "psutil", ".", "virtual_memory", "(", ")", ".", "available", "/", "1000", "/", "1000" ]
Arandom number generator
[ "Arandom", "number", "generator" ]
ae9f630e9a1d67b0eb6d61644a49756de8a5268c
https://github.com/TheOneHyer/arandomness/blob/ae9f630e9a1d67b0eb6d61644a49756de8a5268c/build/lib.linux-x86_64-3.6/arandomness/arandom/agenerator.py#L35-L44
245,729
geertj/looping
lib/looping/pyuv.py
PyUVEventLoop._validate_signal
def _validate_signal(self, sig): """Internal helper to validate a signal. Raise ValueError if the signal number is invalid or uncatchable. Raise RuntimeError if there is a problem setting up the handler. """ if not isinstance(sig, int): raise TypeError('sig must be an int, not {!r}'.format(sig)) if signal is None: raise RuntimeError('Signals are not supported') if not (1 <= sig < signal.NSIG): raise ValueError('sig {} out of range(1, {})'.format(sig, signal.NSIG)) if sys.platform == 'win32': raise RuntimeError('Signals are not really supported on Windows')
python
def _validate_signal(self, sig): """Internal helper to validate a signal. Raise ValueError if the signal number is invalid or uncatchable. Raise RuntimeError if there is a problem setting up the handler. """ if not isinstance(sig, int): raise TypeError('sig must be an int, not {!r}'.format(sig)) if signal is None: raise RuntimeError('Signals are not supported') if not (1 <= sig < signal.NSIG): raise ValueError('sig {} out of range(1, {})'.format(sig, signal.NSIG)) if sys.platform == 'win32': raise RuntimeError('Signals are not really supported on Windows')
[ "def", "_validate_signal", "(", "self", ",", "sig", ")", ":", "if", "not", "isinstance", "(", "sig", ",", "int", ")", ":", "raise", "TypeError", "(", "'sig must be an int, not {!r}'", ".", "format", "(", "sig", ")", ")", "if", "signal", "is", "None", ":", "raise", "RuntimeError", "(", "'Signals are not supported'", ")", "if", "not", "(", "1", "<=", "sig", "<", "signal", ".", "NSIG", ")", ":", "raise", "ValueError", "(", "'sig {} out of range(1, {})'", ".", "format", "(", "sig", ",", "signal", ".", "NSIG", ")", ")", "if", "sys", ".", "platform", "==", "'win32'", ":", "raise", "RuntimeError", "(", "'Signals are not really supported on Windows'", ")" ]
Internal helper to validate a signal. Raise ValueError if the signal number is invalid or uncatchable. Raise RuntimeError if there is a problem setting up the handler.
[ "Internal", "helper", "to", "validate", "a", "signal", "." ]
b60303714685aede18b37c0d80f8f55175ad7a65
https://github.com/geertj/looping/blob/b60303714685aede18b37c0d80f8f55175ad7a65/lib/looping/pyuv.py#L358-L371
245,730
rackerlabs/silverberg
silverberg/client.py
CQLClient.describe_version
def describe_version(self): """ Query the Cassandra server for the version. :returns: string -- the version tag """ def _vers(client): return client.describe_version() d = self._connection() d.addCallback(_vers) return d
python
def describe_version(self): """ Query the Cassandra server for the version. :returns: string -- the version tag """ def _vers(client): return client.describe_version() d = self._connection() d.addCallback(_vers) return d
[ "def", "describe_version", "(", "self", ")", ":", "def", "_vers", "(", "client", ")", ":", "return", "client", ".", "describe_version", "(", ")", "d", "=", "self", ".", "_connection", "(", ")", "d", ".", "addCallback", "(", "_vers", ")", "return", "d" ]
Query the Cassandra server for the version. :returns: string -- the version tag
[ "Query", "the", "Cassandra", "server", "for", "the", "version", "." ]
c6fae78923a019f1615e9516ab30fa105c72a542
https://github.com/rackerlabs/silverberg/blob/c6fae78923a019f1615e9516ab30fa105c72a542/silverberg/client.py#L106-L117
245,731
rackerlabs/silverberg
silverberg/client.py
CQLClient.execute
def execute(self, query, args, consistency): """ Execute a CQL query against the server. :param query: The CQL query to execute :type query: str. :param args: The arguments to substitute :type args: dict. :param consistency: The consistency level :type consistency: ConsistencyLevel In order to avoid unpleasant issues of CQL injection (Hey, just because there's no SQL doesn't mean that Little Bobby Tables won't mess things up for you like in XKCD #327) you probably want to use argument substitution instead of concatting strings together to build a query. Thus, like the official CQL driver for non-Twisted python that comes with the Cassandra distro, we do variable substitution. Example:: d = client.execute("UPDATE :table SET 'fff' = :val WHERE " "KEY = :key",{"val":1234, "key": "fff", "table": "blah"}) :returns: A Deferred that fires with either None, an int, or an iterable of `{'column': value, ...}` dictionaries, depending on the CQL query. e.g. a UPDATE would return None, whereas a SELECT would return an int or some rows Example output:: [{"fff": 1222}] """ prep_query = prepare(query, args) def _execute(client): exec_d = client.execute_cql3_query(prep_query, ttypes.Compression.NONE, consistency) if self._disconnect_on_cancel: cancellable_d = Deferred(lambda d: self.disconnect()) exec_d.chainDeferred(cancellable_d) return cancellable_d else: return exec_d def _proc_results(result): if result.type == ttypes.CqlResultType.ROWS: return self._unmarshal_result(result.schema, result.rows, unmarshallers) elif result.type == ttypes.CqlResultType.INT: return result.num else: return None d = self._connection() d.addCallback(_execute) d.addCallback(_proc_results) return d
python
def execute(self, query, args, consistency): """ Execute a CQL query against the server. :param query: The CQL query to execute :type query: str. :param args: The arguments to substitute :type args: dict. :param consistency: The consistency level :type consistency: ConsistencyLevel In order to avoid unpleasant issues of CQL injection (Hey, just because there's no SQL doesn't mean that Little Bobby Tables won't mess things up for you like in XKCD #327) you probably want to use argument substitution instead of concatting strings together to build a query. Thus, like the official CQL driver for non-Twisted python that comes with the Cassandra distro, we do variable substitution. Example:: d = client.execute("UPDATE :table SET 'fff' = :val WHERE " "KEY = :key",{"val":1234, "key": "fff", "table": "blah"}) :returns: A Deferred that fires with either None, an int, or an iterable of `{'column': value, ...}` dictionaries, depending on the CQL query. e.g. a UPDATE would return None, whereas a SELECT would return an int or some rows Example output:: [{"fff": 1222}] """ prep_query = prepare(query, args) def _execute(client): exec_d = client.execute_cql3_query(prep_query, ttypes.Compression.NONE, consistency) if self._disconnect_on_cancel: cancellable_d = Deferred(lambda d: self.disconnect()) exec_d.chainDeferred(cancellable_d) return cancellable_d else: return exec_d def _proc_results(result): if result.type == ttypes.CqlResultType.ROWS: return self._unmarshal_result(result.schema, result.rows, unmarshallers) elif result.type == ttypes.CqlResultType.INT: return result.num else: return None d = self._connection() d.addCallback(_execute) d.addCallback(_proc_results) return d
[ "def", "execute", "(", "self", ",", "query", ",", "args", ",", "consistency", ")", ":", "prep_query", "=", "prepare", "(", "query", ",", "args", ")", "def", "_execute", "(", "client", ")", ":", "exec_d", "=", "client", ".", "execute_cql3_query", "(", "prep_query", ",", "ttypes", ".", "Compression", ".", "NONE", ",", "consistency", ")", "if", "self", ".", "_disconnect_on_cancel", ":", "cancellable_d", "=", "Deferred", "(", "lambda", "d", ":", "self", ".", "disconnect", "(", ")", ")", "exec_d", ".", "chainDeferred", "(", "cancellable_d", ")", "return", "cancellable_d", "else", ":", "return", "exec_d", "def", "_proc_results", "(", "result", ")", ":", "if", "result", ".", "type", "==", "ttypes", ".", "CqlResultType", ".", "ROWS", ":", "return", "self", ".", "_unmarshal_result", "(", "result", ".", "schema", ",", "result", ".", "rows", ",", "unmarshallers", ")", "elif", "result", ".", "type", "==", "ttypes", ".", "CqlResultType", ".", "INT", ":", "return", "result", ".", "num", "else", ":", "return", "None", "d", "=", "self", ".", "_connection", "(", ")", "d", ".", "addCallback", "(", "_execute", ")", "d", ".", "addCallback", "(", "_proc_results", ")", "return", "d" ]
Execute a CQL query against the server. :param query: The CQL query to execute :type query: str. :param args: The arguments to substitute :type args: dict. :param consistency: The consistency level :type consistency: ConsistencyLevel In order to avoid unpleasant issues of CQL injection (Hey, just because there's no SQL doesn't mean that Little Bobby Tables won't mess things up for you like in XKCD #327) you probably want to use argument substitution instead of concatting strings together to build a query. Thus, like the official CQL driver for non-Twisted python that comes with the Cassandra distro, we do variable substitution. Example:: d = client.execute("UPDATE :table SET 'fff' = :val WHERE " "KEY = :key",{"val":1234, "key": "fff", "table": "blah"}) :returns: A Deferred that fires with either None, an int, or an iterable of `{'column': value, ...}` dictionaries, depending on the CQL query. e.g. a UPDATE would return None, whereas a SELECT would return an int or some rows Example output:: [{"fff": 1222}]
[ "Execute", "a", "CQL", "query", "against", "the", "server", "." ]
c6fae78923a019f1615e9516ab30fa105c72a542
https://github.com/rackerlabs/silverberg/blob/c6fae78923a019f1615e9516ab30fa105c72a542/silverberg/client.py#L161-L221
245,732
akissa/sachannelupdate
sachannelupdate/base.py
getfiles
def getfiles(qfiles, dirname, names): """Get rule files in a directory""" for name in names: fullname = os.path.join(dirname, name) if os.path.isfile(fullname) and \ fullname.endswith('.cf') or \ fullname.endswith('.post'): qfiles.put(fullname)
python
def getfiles(qfiles, dirname, names): """Get rule files in a directory""" for name in names: fullname = os.path.join(dirname, name) if os.path.isfile(fullname) and \ fullname.endswith('.cf') or \ fullname.endswith('.post'): qfiles.put(fullname)
[ "def", "getfiles", "(", "qfiles", ",", "dirname", ",", "names", ")", ":", "for", "name", "in", "names", ":", "fullname", "=", "os", ".", "path", ".", "join", "(", "dirname", ",", "name", ")", "if", "os", ".", "path", ".", "isfile", "(", "fullname", ")", "and", "fullname", ".", "endswith", "(", "'.cf'", ")", "or", "fullname", ".", "endswith", "(", "'.post'", ")", ":", "qfiles", ".", "put", "(", "fullname", ")" ]
Get rule files in a directory
[ "Get", "rule", "files", "in", "a", "directory" ]
a1c3c3d86b874f9c92c2407e2608963165d3ae98
https://github.com/akissa/sachannelupdate/blob/a1c3c3d86b874f9c92c2407e2608963165d3ae98/sachannelupdate/base.py#L49-L56
245,733
akissa/sachannelupdate
sachannelupdate/base.py
deploy_file
def deploy_file(source, dest): """Deploy a file""" date = datetime.utcnow().strftime('%Y-%m-%d') shandle = open(source) with open(dest, 'w') as handle: for line in shandle: if line == '# Updated: %date%\n': newline = '# Updated: %s\n' % date else: newline = line handle.write(newline) handle.flush() shandle.close()
python
def deploy_file(source, dest): """Deploy a file""" date = datetime.utcnow().strftime('%Y-%m-%d') shandle = open(source) with open(dest, 'w') as handle: for line in shandle: if line == '# Updated: %date%\n': newline = '# Updated: %s\n' % date else: newline = line handle.write(newline) handle.flush() shandle.close()
[ "def", "deploy_file", "(", "source", ",", "dest", ")", ":", "date", "=", "datetime", ".", "utcnow", "(", ")", ".", "strftime", "(", "'%Y-%m-%d'", ")", "shandle", "=", "open", "(", "source", ")", "with", "open", "(", "dest", ",", "'w'", ")", "as", "handle", ":", "for", "line", "in", "shandle", ":", "if", "line", "==", "'# Updated: %date%\\n'", ":", "newline", "=", "'# Updated: %s\\n'", "%", "date", "else", ":", "newline", "=", "line", "handle", ".", "write", "(", "newline", ")", "handle", ".", "flush", "(", ")", "shandle", ".", "close", "(", ")" ]
Deploy a file
[ "Deploy", "a", "file" ]
a1c3c3d86b874f9c92c2407e2608963165d3ae98
https://github.com/akissa/sachannelupdate/blob/a1c3c3d86b874f9c92c2407e2608963165d3ae98/sachannelupdate/base.py#L59-L71
245,734
akissa/sachannelupdate
sachannelupdate/base.py
get_counter
def get_counter(counterfile): """Get the counter value""" try: version_num = open(counterfile).read() version_num = int(version_num) + 1 except (ValueError, IOError): version_num = 1 create_file(counterfile, "%d" % version_num) except BaseException as msg: raise SaChannelUpdateError(msg) return version_num
python
def get_counter(counterfile): """Get the counter value""" try: version_num = open(counterfile).read() version_num = int(version_num) + 1 except (ValueError, IOError): version_num = 1 create_file(counterfile, "%d" % version_num) except BaseException as msg: raise SaChannelUpdateError(msg) return version_num
[ "def", "get_counter", "(", "counterfile", ")", ":", "try", ":", "version_num", "=", "open", "(", "counterfile", ")", ".", "read", "(", ")", "version_num", "=", "int", "(", "version_num", ")", "+", "1", "except", "(", "ValueError", ",", "IOError", ")", ":", "version_num", "=", "1", "create_file", "(", "counterfile", ",", "\"%d\"", "%", "version_num", ")", "except", "BaseException", "as", "msg", ":", "raise", "SaChannelUpdateError", "(", "msg", ")", "return", "version_num" ]
Get the counter value
[ "Get", "the", "counter", "value" ]
a1c3c3d86b874f9c92c2407e2608963165d3ae98
https://github.com/akissa/sachannelupdate/blob/a1c3c3d86b874f9c92c2407e2608963165d3ae98/sachannelupdate/base.py#L106-L116
245,735
akissa/sachannelupdate
sachannelupdate/base.py
update_dns
def update_dns(config, record, sa_version): "Update the DNS record" try: domain = config.get('domain_name', 'sa.baruwa.com.') dns_key = config.get('domain_key') dns_ip = config.get('domain_ip', '127.0.0.1') keyring = tsigkeyring.from_text({domain: dns_key}) transaction = update.Update( domain, keyring=keyring, keyalgorithm=tsig.HMAC_SHA512) txtrecord = '%s.%s' % (sa_version, domain) transaction.replace(txtrecord, 120, 'txt', record) query.tcp(transaction, dns_ip) return True except DNSException, msg: raise SaChannelUpdateDNSError(msg)
python
def update_dns(config, record, sa_version): "Update the DNS record" try: domain = config.get('domain_name', 'sa.baruwa.com.') dns_key = config.get('domain_key') dns_ip = config.get('domain_ip', '127.0.0.1') keyring = tsigkeyring.from_text({domain: dns_key}) transaction = update.Update( domain, keyring=keyring, keyalgorithm=tsig.HMAC_SHA512) txtrecord = '%s.%s' % (sa_version, domain) transaction.replace(txtrecord, 120, 'txt', record) query.tcp(transaction, dns_ip) return True except DNSException, msg: raise SaChannelUpdateDNSError(msg)
[ "def", "update_dns", "(", "config", ",", "record", ",", "sa_version", ")", ":", "try", ":", "domain", "=", "config", ".", "get", "(", "'domain_name'", ",", "'sa.baruwa.com.'", ")", "dns_key", "=", "config", ".", "get", "(", "'domain_key'", ")", "dns_ip", "=", "config", ".", "get", "(", "'domain_ip'", ",", "'127.0.0.1'", ")", "keyring", "=", "tsigkeyring", ".", "from_text", "(", "{", "domain", ":", "dns_key", "}", ")", "transaction", "=", "update", ".", "Update", "(", "domain", ",", "keyring", "=", "keyring", ",", "keyalgorithm", "=", "tsig", ".", "HMAC_SHA512", ")", "txtrecord", "=", "'%s.%s'", "%", "(", "sa_version", ",", "domain", ")", "transaction", ".", "replace", "(", "txtrecord", ",", "120", ",", "'txt'", ",", "record", ")", "query", ".", "tcp", "(", "transaction", ",", "dns_ip", ")", "return", "True", "except", "DNSException", ",", "msg", ":", "raise", "SaChannelUpdateDNSError", "(", "msg", ")" ]
Update the DNS record
[ "Update", "the", "DNS", "record" ]
a1c3c3d86b874f9c92c2407e2608963165d3ae98
https://github.com/akissa/sachannelupdate/blob/a1c3c3d86b874f9c92c2407e2608963165d3ae98/sachannelupdate/base.py#L119-L135
245,736
akissa/sachannelupdate
sachannelupdate/base.py
sign
def sign(config, s_filename): """sign the package""" gpg_home = config.get('gpg_dir', '/var/lib/sachannelupdate/gnupg') gpg_pass = config.get('gpg_passphrase') gpg_keyid = config.get('gpg_keyid') gpg = GPG(gnupghome=gpg_home) try: plaintext = open(s_filename, 'rb') signature = gpg.sign_file( plaintext, keyid=gpg_keyid, passphrase=gpg_pass, detach=True) with open('%s.asc' % s_filename, 'wb') as handle: handle.write(str(signature)) finally: if 'plaintext' in locals(): plaintext.close()
python
def sign(config, s_filename): """sign the package""" gpg_home = config.get('gpg_dir', '/var/lib/sachannelupdate/gnupg') gpg_pass = config.get('gpg_passphrase') gpg_keyid = config.get('gpg_keyid') gpg = GPG(gnupghome=gpg_home) try: plaintext = open(s_filename, 'rb') signature = gpg.sign_file( plaintext, keyid=gpg_keyid, passphrase=gpg_pass, detach=True) with open('%s.asc' % s_filename, 'wb') as handle: handle.write(str(signature)) finally: if 'plaintext' in locals(): plaintext.close()
[ "def", "sign", "(", "config", ",", "s_filename", ")", ":", "gpg_home", "=", "config", ".", "get", "(", "'gpg_dir'", ",", "'/var/lib/sachannelupdate/gnupg'", ")", "gpg_pass", "=", "config", ".", "get", "(", "'gpg_passphrase'", ")", "gpg_keyid", "=", "config", ".", "get", "(", "'gpg_keyid'", ")", "gpg", "=", "GPG", "(", "gnupghome", "=", "gpg_home", ")", "try", ":", "plaintext", "=", "open", "(", "s_filename", ",", "'rb'", ")", "signature", "=", "gpg", ".", "sign_file", "(", "plaintext", ",", "keyid", "=", "gpg_keyid", ",", "passphrase", "=", "gpg_pass", ",", "detach", "=", "True", ")", "with", "open", "(", "'%s.asc'", "%", "s_filename", ",", "'wb'", ")", "as", "handle", ":", "handle", ".", "write", "(", "str", "(", "signature", ")", ")", "finally", ":", "if", "'plaintext'", "in", "locals", "(", ")", ":", "plaintext", ".", "close", "(", ")" ]
sign the package
[ "sign", "the", "package" ]
a1c3c3d86b874f9c92c2407e2608963165d3ae98
https://github.com/akissa/sachannelupdate/blob/a1c3c3d86b874f9c92c2407e2608963165d3ae98/sachannelupdate/base.py#L138-L152
245,737
akissa/sachannelupdate
sachannelupdate/base.py
hash_file
def hash_file(tar_filename): """hash the file""" hasher = sha1() with open(tar_filename, 'rb') as afile: buf = afile.read(BLOCKSIZE) while len(buf) > 0: hasher.update(buf) buf = afile.read(BLOCKSIZE) data = HASHTMPL % (hasher.hexdigest(), os.path.basename(tar_filename)) create_file('%s.sha1' % tar_filename, data)
python
def hash_file(tar_filename): """hash the file""" hasher = sha1() with open(tar_filename, 'rb') as afile: buf = afile.read(BLOCKSIZE) while len(buf) > 0: hasher.update(buf) buf = afile.read(BLOCKSIZE) data = HASHTMPL % (hasher.hexdigest(), os.path.basename(tar_filename)) create_file('%s.sha1' % tar_filename, data)
[ "def", "hash_file", "(", "tar_filename", ")", ":", "hasher", "=", "sha1", "(", ")", "with", "open", "(", "tar_filename", ",", "'rb'", ")", "as", "afile", ":", "buf", "=", "afile", ".", "read", "(", "BLOCKSIZE", ")", "while", "len", "(", "buf", ")", ">", "0", ":", "hasher", ".", "update", "(", "buf", ")", "buf", "=", "afile", ".", "read", "(", "BLOCKSIZE", ")", "data", "=", "HASHTMPL", "%", "(", "hasher", ".", "hexdigest", "(", ")", ",", "os", ".", "path", ".", "basename", "(", "tar_filename", ")", ")", "create_file", "(", "'%s.sha1'", "%", "tar_filename", ",", "data", ")" ]
hash the file
[ "hash", "the", "file" ]
a1c3c3d86b874f9c92c2407e2608963165d3ae98
https://github.com/akissa/sachannelupdate/blob/a1c3c3d86b874f9c92c2407e2608963165d3ae98/sachannelupdate/base.py#L155-L164
245,738
akissa/sachannelupdate
sachannelupdate/base.py
upload
def upload(config, remote_loc, u_filename): """Upload the files""" rcode = False try: sftp, transport = get_sftp_conn(config) remote_dir = get_remote_path(remote_loc) for part in ['sha1', 'asc']: local_file = '%s.%s' % (u_filename, part) remote_file = os.path.join(remote_dir, local_file) sftp.put(local_file, remote_file) sftp.put(remote_dir, os.path.join(remote_dir, u_filename)) rcode = True except BaseException: pass finally: if 'transport' in locals(): transport.close() return rcode
python
def upload(config, remote_loc, u_filename): """Upload the files""" rcode = False try: sftp, transport = get_sftp_conn(config) remote_dir = get_remote_path(remote_loc) for part in ['sha1', 'asc']: local_file = '%s.%s' % (u_filename, part) remote_file = os.path.join(remote_dir, local_file) sftp.put(local_file, remote_file) sftp.put(remote_dir, os.path.join(remote_dir, u_filename)) rcode = True except BaseException: pass finally: if 'transport' in locals(): transport.close() return rcode
[ "def", "upload", "(", "config", ",", "remote_loc", ",", "u_filename", ")", ":", "rcode", "=", "False", "try", ":", "sftp", ",", "transport", "=", "get_sftp_conn", "(", "config", ")", "remote_dir", "=", "get_remote_path", "(", "remote_loc", ")", "for", "part", "in", "[", "'sha1'", ",", "'asc'", "]", ":", "local_file", "=", "'%s.%s'", "%", "(", "u_filename", ",", "part", ")", "remote_file", "=", "os", ".", "path", ".", "join", "(", "remote_dir", ",", "local_file", ")", "sftp", ".", "put", "(", "local_file", ",", "remote_file", ")", "sftp", ".", "put", "(", "remote_dir", ",", "os", ".", "path", ".", "join", "(", "remote_dir", ",", "u_filename", ")", ")", "rcode", "=", "True", "except", "BaseException", ":", "pass", "finally", ":", "if", "'transport'", "in", "locals", "(", ")", ":", "transport", ".", "close", "(", ")", "return", "rcode" ]
Upload the files
[ "Upload", "the", "files" ]
a1c3c3d86b874f9c92c2407e2608963165d3ae98
https://github.com/akissa/sachannelupdate/blob/a1c3c3d86b874f9c92c2407e2608963165d3ae98/sachannelupdate/base.py#L167-L184
245,739
akissa/sachannelupdate
sachannelupdate/base.py
queue_files
def queue_files(dirpath, queue): """Add files in a directory to a queue""" for root, _, files in os.walk(os.path.abspath(dirpath)): if not files: continue for filename in files: queue.put(os.path.join(root, filename))
python
def queue_files(dirpath, queue): """Add files in a directory to a queue""" for root, _, files in os.walk(os.path.abspath(dirpath)): if not files: continue for filename in files: queue.put(os.path.join(root, filename))
[ "def", "queue_files", "(", "dirpath", ",", "queue", ")", ":", "for", "root", ",", "_", ",", "files", "in", "os", ".", "walk", "(", "os", ".", "path", ".", "abspath", "(", "dirpath", ")", ")", ":", "if", "not", "files", ":", "continue", "for", "filename", "in", "files", ":", "queue", ".", "put", "(", "os", ".", "path", ".", "join", "(", "root", ",", "filename", ")", ")" ]
Add files in a directory to a queue
[ "Add", "files", "in", "a", "directory", "to", "a", "queue" ]
a1c3c3d86b874f9c92c2407e2608963165d3ae98
https://github.com/akissa/sachannelupdate/blob/a1c3c3d86b874f9c92c2407e2608963165d3ae98/sachannelupdate/base.py#L187-L193
245,740
akissa/sachannelupdate
sachannelupdate/base.py
get_cf_files
def get_cf_files(path, queue): """Get rule files in a directory and put them in a queue""" for root, _, files in os.walk(os.path.abspath(path)): if not files: continue for filename in files: fullname = os.path.join(root, filename) if os.path.isfile(fullname) and fullname.endswith('.cf') or \ fullname.endswith('.post'): queue.put(fullname)
python
def get_cf_files(path, queue): """Get rule files in a directory and put them in a queue""" for root, _, files in os.walk(os.path.abspath(path)): if not files: continue for filename in files: fullname = os.path.join(root, filename) if os.path.isfile(fullname) and fullname.endswith('.cf') or \ fullname.endswith('.post'): queue.put(fullname)
[ "def", "get_cf_files", "(", "path", ",", "queue", ")", ":", "for", "root", ",", "_", ",", "files", "in", "os", ".", "walk", "(", "os", ".", "path", ".", "abspath", "(", "path", ")", ")", ":", "if", "not", "files", ":", "continue", "for", "filename", "in", "files", ":", "fullname", "=", "os", ".", "path", ".", "join", "(", "root", ",", "filename", ")", "if", "os", ".", "path", ".", "isfile", "(", "fullname", ")", "and", "fullname", ".", "endswith", "(", "'.cf'", ")", "or", "fullname", ".", "endswith", "(", "'.post'", ")", ":", "queue", ".", "put", "(", "fullname", ")" ]
Get rule files in a directory and put them in a queue
[ "Get", "rule", "files", "in", "a", "directory", "and", "put", "them", "in", "a", "queue" ]
a1c3c3d86b874f9c92c2407e2608963165d3ae98
https://github.com/akissa/sachannelupdate/blob/a1c3c3d86b874f9c92c2407e2608963165d3ae98/sachannelupdate/base.py#L196-L205
245,741
akissa/sachannelupdate
sachannelupdate/base.py
cleanup
def cleanup(dest, tardir, counterfile): """Remove existing rules""" thefiles = Queue() # dest directory files queue_files(dest, thefiles) # tar directory files queue_files(tardir, thefiles) while not thefiles.empty(): d_file = thefiles.get() info("Deleting file: %s" % d_file) os.unlink(d_file) if os.path.exists(counterfile): info("Deleting the counter file %s" % counterfile) os.unlink(counterfile)
python
def cleanup(dest, tardir, counterfile): """Remove existing rules""" thefiles = Queue() # dest directory files queue_files(dest, thefiles) # tar directory files queue_files(tardir, thefiles) while not thefiles.empty(): d_file = thefiles.get() info("Deleting file: %s" % d_file) os.unlink(d_file) if os.path.exists(counterfile): info("Deleting the counter file %s" % counterfile) os.unlink(counterfile)
[ "def", "cleanup", "(", "dest", ",", "tardir", ",", "counterfile", ")", ":", "thefiles", "=", "Queue", "(", ")", "# dest directory files", "queue_files", "(", "dest", ",", "thefiles", ")", "# tar directory files", "queue_files", "(", "tardir", ",", "thefiles", ")", "while", "not", "thefiles", ".", "empty", "(", ")", ":", "d_file", "=", "thefiles", ".", "get", "(", ")", "info", "(", "\"Deleting file: %s\"", "%", "d_file", ")", "os", ".", "unlink", "(", "d_file", ")", "if", "os", ".", "path", ".", "exists", "(", "counterfile", ")", ":", "info", "(", "\"Deleting the counter file %s\"", "%", "counterfile", ")", "os", ".", "unlink", "(", "counterfile", ")" ]
Remove existing rules
[ "Remove", "existing", "rules" ]
a1c3c3d86b874f9c92c2407e2608963165d3ae98
https://github.com/akissa/sachannelupdate/blob/a1c3c3d86b874f9c92c2407e2608963165d3ae98/sachannelupdate/base.py#L208-L221
245,742
akissa/sachannelupdate
sachannelupdate/base.py
check_required
def check_required(config): """Validate the input""" if config.get('domain_key') is None: raise CfgError("The domain_key option is required") if config.get('remote_loc') is None: raise CfgError("The remote_location option is required") if config.get('gpg_keyid') is None: raise CfgError("The gpg_keyid option is required")
python
def check_required(config): """Validate the input""" if config.get('domain_key') is None: raise CfgError("The domain_key option is required") if config.get('remote_loc') is None: raise CfgError("The remote_location option is required") if config.get('gpg_keyid') is None: raise CfgError("The gpg_keyid option is required")
[ "def", "check_required", "(", "config", ")", ":", "if", "config", ".", "get", "(", "'domain_key'", ")", "is", "None", ":", "raise", "CfgError", "(", "\"The domain_key option is required\"", ")", "if", "config", ".", "get", "(", "'remote_loc'", ")", "is", "None", ":", "raise", "CfgError", "(", "\"The remote_location option is required\"", ")", "if", "config", ".", "get", "(", "'gpg_keyid'", ")", "is", "None", ":", "raise", "CfgError", "(", "\"The gpg_keyid option is required\"", ")" ]
Validate the input
[ "Validate", "the", "input" ]
a1c3c3d86b874f9c92c2407e2608963165d3ae98
https://github.com/akissa/sachannelupdate/blob/a1c3c3d86b874f9c92c2407e2608963165d3ae98/sachannelupdate/base.py#L224-L231
245,743
edeposit/edeposit.amqp.antivirus
src/edeposit/amqp/antivirus/wrappers/clamscan.py
_parse_result
def _parse_result(result): """ Parse ``clamscan`` output into same dictionary structured used by ``pyclamd``. Input example:: /home/bystrousak/Plocha/prace/test/eicar.com: Eicar-Test-Signature FOUND Output dict:: { "/home/bystrousak/Plocha/prace/test/eicar.com": ( "FOUND", "Eicar-Test-Signature" ) } """ lines = filter(lambda x: x.strip(), result.splitlines()) # rm blank lines if not lines: return {} out = {} for line in lines: line = line.split(":") fn = line[0].strip() line = " ".join(line[1:]) line = line.rsplit(None, 1) status = line.pop().strip() out[fn] = (status, " ".join(line).strip()) return out
python
def _parse_result(result): """ Parse ``clamscan`` output into same dictionary structured used by ``pyclamd``. Input example:: /home/bystrousak/Plocha/prace/test/eicar.com: Eicar-Test-Signature FOUND Output dict:: { "/home/bystrousak/Plocha/prace/test/eicar.com": ( "FOUND", "Eicar-Test-Signature" ) } """ lines = filter(lambda x: x.strip(), result.splitlines()) # rm blank lines if not lines: return {} out = {} for line in lines: line = line.split(":") fn = line[0].strip() line = " ".join(line[1:]) line = line.rsplit(None, 1) status = line.pop().strip() out[fn] = (status, " ".join(line).strip()) return out
[ "def", "_parse_result", "(", "result", ")", ":", "lines", "=", "filter", "(", "lambda", "x", ":", "x", ".", "strip", "(", ")", ",", "result", ".", "splitlines", "(", ")", ")", "# rm blank lines", "if", "not", "lines", ":", "return", "{", "}", "out", "=", "{", "}", "for", "line", "in", "lines", ":", "line", "=", "line", ".", "split", "(", "\":\"", ")", "fn", "=", "line", "[", "0", "]", ".", "strip", "(", ")", "line", "=", "\" \"", ".", "join", "(", "line", "[", "1", ":", "]", ")", "line", "=", "line", ".", "rsplit", "(", "None", ",", "1", ")", "status", "=", "line", ".", "pop", "(", ")", ".", "strip", "(", ")", "out", "[", "fn", "]", "=", "(", "status", ",", "\" \"", ".", "join", "(", "line", ")", ".", "strip", "(", ")", ")", "return", "out" ]
Parse ``clamscan`` output into same dictionary structured used by ``pyclamd``. Input example:: /home/bystrousak/Plocha/prace/test/eicar.com: Eicar-Test-Signature FOUND Output dict:: { "/home/bystrousak/Plocha/prace/test/eicar.com": ( "FOUND", "Eicar-Test-Signature" ) }
[ "Parse", "clamscan", "output", "into", "same", "dictionary", "structured", "used", "by", "pyclamd", "." ]
011b38bbe920819fab99a5891b1e70732321a598
https://github.com/edeposit/edeposit.amqp.antivirus/blob/011b38bbe920819fab99a5891b1e70732321a598/src/edeposit/amqp/antivirus/wrappers/clamscan.py#L17-L50
245,744
edeposit/edeposit.amqp.antivirus
src/edeposit/amqp/antivirus/wrappers/clamscan.py
scan_file
def scan_file(path): """ Scan `path` for viruses using ``clamscan`` program. Args: path (str): Relative or absolute path of file/directory you need to scan. Returns: dict: ``{filename: ("FOUND", "virus type")}`` or blank dict. Raises: AssertionError: When the internal file doesn't exists. """ path = os.path.abspath(path) assert os.path.exists(path), "Unreachable file '%s'." % path result = sh.clamscan(path, no_summary=True, infected=True, _ok_code=[0, 1]) return _parse_result(result)
python
def scan_file(path): """ Scan `path` for viruses using ``clamscan`` program. Args: path (str): Relative or absolute path of file/directory you need to scan. Returns: dict: ``{filename: ("FOUND", "virus type")}`` or blank dict. Raises: AssertionError: When the internal file doesn't exists. """ path = os.path.abspath(path) assert os.path.exists(path), "Unreachable file '%s'." % path result = sh.clamscan(path, no_summary=True, infected=True, _ok_code=[0, 1]) return _parse_result(result)
[ "def", "scan_file", "(", "path", ")", ":", "path", "=", "os", ".", "path", ".", "abspath", "(", "path", ")", "assert", "os", ".", "path", ".", "exists", "(", "path", ")", ",", "\"Unreachable file '%s'.\"", "%", "path", "result", "=", "sh", ".", "clamscan", "(", "path", ",", "no_summary", "=", "True", ",", "infected", "=", "True", ",", "_ok_code", "=", "[", "0", ",", "1", "]", ")", "return", "_parse_result", "(", "result", ")" ]
Scan `path` for viruses using ``clamscan`` program. Args: path (str): Relative or absolute path of file/directory you need to scan. Returns: dict: ``{filename: ("FOUND", "virus type")}`` or blank dict. Raises: AssertionError: When the internal file doesn't exists.
[ "Scan", "path", "for", "viruses", "using", "clamscan", "program", "." ]
011b38bbe920819fab99a5891b1e70732321a598
https://github.com/edeposit/edeposit.amqp.antivirus/blob/011b38bbe920819fab99a5891b1e70732321a598/src/edeposit/amqp/antivirus/wrappers/clamscan.py#L53-L72
245,745
costastf/emaillib
emaillib/emaillib.py
SmtpServer.connect
def connect(self): """Initializes a connection to the smtp server :return: True on success, False otherwise """ connection_method = 'SMTP_SSL' if self.ssl else 'SMTP' self._logger.debug('Trying to connect via {}'.format(connection_method)) smtp = getattr(smtplib, connection_method) if self.port: self._smtp = smtp(self.address, self.port) else: self._smtp = smtp(self.address) self._smtp.ehlo() if self.tls: self._smtp.starttls() self._smtp.ehlo() self._logger.info('Got smtp connection') if self.username and self.password: self._logger.info('Logging in') self._smtp.login(self.username, self.password) self._connected = True
python
def connect(self): """Initializes a connection to the smtp server :return: True on success, False otherwise """ connection_method = 'SMTP_SSL' if self.ssl else 'SMTP' self._logger.debug('Trying to connect via {}'.format(connection_method)) smtp = getattr(smtplib, connection_method) if self.port: self._smtp = smtp(self.address, self.port) else: self._smtp = smtp(self.address) self._smtp.ehlo() if self.tls: self._smtp.starttls() self._smtp.ehlo() self._logger.info('Got smtp connection') if self.username and self.password: self._logger.info('Logging in') self._smtp.login(self.username, self.password) self._connected = True
[ "def", "connect", "(", "self", ")", ":", "connection_method", "=", "'SMTP_SSL'", "if", "self", ".", "ssl", "else", "'SMTP'", "self", ".", "_logger", ".", "debug", "(", "'Trying to connect via {}'", ".", "format", "(", "connection_method", ")", ")", "smtp", "=", "getattr", "(", "smtplib", ",", "connection_method", ")", "if", "self", ".", "port", ":", "self", ".", "_smtp", "=", "smtp", "(", "self", ".", "address", ",", "self", ".", "port", ")", "else", ":", "self", ".", "_smtp", "=", "smtp", "(", "self", ".", "address", ")", "self", ".", "_smtp", ".", "ehlo", "(", ")", "if", "self", ".", "tls", ":", "self", ".", "_smtp", ".", "starttls", "(", ")", "self", ".", "_smtp", ".", "ehlo", "(", ")", "self", ".", "_logger", ".", "info", "(", "'Got smtp connection'", ")", "if", "self", ".", "username", "and", "self", ".", "password", ":", "self", ".", "_logger", ".", "info", "(", "'Logging in'", ")", "self", ".", "_smtp", ".", "login", "(", "self", ".", "username", ",", "self", ".", "password", ")", "self", ".", "_connected", "=", "True" ]
Initializes a connection to the smtp server :return: True on success, False otherwise
[ "Initializes", "a", "connection", "to", "the", "smtp", "server" ]
2a00a3c5d4745898b96e858607b43784fa566fac
https://github.com/costastf/emaillib/blob/2a00a3c5d4745898b96e858607b43784fa566fac/emaillib/emaillib.py#L80-L100
245,746
costastf/emaillib
emaillib/emaillib.py
SmtpServer.send
def send(self, sender, recipients, cc=None, bcc=None, subject='', body='', attachments=None, content='text'): """Sends the email :param sender: The server of the message :param recipients: The recipients (To:) of the message :param cc: The CC recipients of the message :param bcc: The BCC recipients of the message :param subject: The subject of the message :param body: The body of the message :param attachments: The attachments of the message :param content: The type of content the message [text/html] :return: True on success, False otherwise """ if not self.connected: self._logger.error(('Server not connected, cannot send message, ' 'please connect() first and disconnect() when ' 'the connection is not needed any more')) return False try: message = Message(sender, recipients, cc, bcc, subject, body, attachments, content) self._smtp.sendmail(message.sender, message.recipients, message.as_string) result = True self._connected = False self._logger.debug('Done') except Exception: # noqa self._logger.exception('Something went wrong!') result = False return result
python
def send(self, sender, recipients, cc=None, bcc=None, subject='', body='', attachments=None, content='text'): """Sends the email :param sender: The server of the message :param recipients: The recipients (To:) of the message :param cc: The CC recipients of the message :param bcc: The BCC recipients of the message :param subject: The subject of the message :param body: The body of the message :param attachments: The attachments of the message :param content: The type of content the message [text/html] :return: True on success, False otherwise """ if not self.connected: self._logger.error(('Server not connected, cannot send message, ' 'please connect() first and disconnect() when ' 'the connection is not needed any more')) return False try: message = Message(sender, recipients, cc, bcc, subject, body, attachments, content) self._smtp.sendmail(message.sender, message.recipients, message.as_string) result = True self._connected = False self._logger.debug('Done') except Exception: # noqa self._logger.exception('Something went wrong!') result = False return result
[ "def", "send", "(", "self", ",", "sender", ",", "recipients", ",", "cc", "=", "None", ",", "bcc", "=", "None", ",", "subject", "=", "''", ",", "body", "=", "''", ",", "attachments", "=", "None", ",", "content", "=", "'text'", ")", ":", "if", "not", "self", ".", "connected", ":", "self", ".", "_logger", ".", "error", "(", "(", "'Server not connected, cannot send message, '", "'please connect() first and disconnect() when '", "'the connection is not needed any more'", ")", ")", "return", "False", "try", ":", "message", "=", "Message", "(", "sender", ",", "recipients", ",", "cc", ",", "bcc", ",", "subject", ",", "body", ",", "attachments", ",", "content", ")", "self", ".", "_smtp", ".", "sendmail", "(", "message", ".", "sender", ",", "message", ".", "recipients", ",", "message", ".", "as_string", ")", "result", "=", "True", "self", ".", "_connected", "=", "False", "self", ".", "_logger", ".", "debug", "(", "'Done'", ")", "except", "Exception", ":", "# noqa", "self", ".", "_logger", ".", "exception", "(", "'Something went wrong!'", ")", "result", "=", "False", "return", "result" ]
Sends the email :param sender: The server of the message :param recipients: The recipients (To:) of the message :param cc: The CC recipients of the message :param bcc: The BCC recipients of the message :param subject: The subject of the message :param body: The body of the message :param attachments: The attachments of the message :param content: The type of content the message [text/html] :return: True on success, False otherwise
[ "Sends", "the", "email" ]
2a00a3c5d4745898b96e858607b43784fa566fac
https://github.com/costastf/emaillib/blob/2a00a3c5d4745898b96e858607b43784fa566fac/emaillib/emaillib.py#L102-L147
245,747
costastf/emaillib
emaillib/emaillib.py
SmtpServer.disconnect
def disconnect(self): """Disconnects from the remote smtp server :return: True on success, False otherwise """ if self.connected: try: self._smtp.close() self._connected = False result = True except Exception: # noqa self._logger.exception('Something went wrong!') result = False return result
python
def disconnect(self): """Disconnects from the remote smtp server :return: True on success, False otherwise """ if self.connected: try: self._smtp.close() self._connected = False result = True except Exception: # noqa self._logger.exception('Something went wrong!') result = False return result
[ "def", "disconnect", "(", "self", ")", ":", "if", "self", ".", "connected", ":", "try", ":", "self", ".", "_smtp", ".", "close", "(", ")", "self", ".", "_connected", "=", "False", "result", "=", "True", "except", "Exception", ":", "# noqa", "self", ".", "_logger", ".", "exception", "(", "'Something went wrong!'", ")", "result", "=", "False", "return", "result" ]
Disconnects from the remote smtp server :return: True on success, False otherwise
[ "Disconnects", "from", "the", "remote", "smtp", "server" ]
2a00a3c5d4745898b96e858607b43784fa566fac
https://github.com/costastf/emaillib/blob/2a00a3c5d4745898b96e858607b43784fa566fac/emaillib/emaillib.py#L149-L162
245,748
costastf/emaillib
emaillib/emaillib.py
EasySender.send
def send(self, sender, recipients, cc=None, bcc=None, subject='', body='', attachments=None, content='text'): """Sends the email by connecting and disconnecting after the send :param sender: The sender of the message :param recipients: The recipients (To:) of the message :param cc: The CC recipients of the message :param bcc: The BCC recipients of the message :param subject: The subject of the message :param body: The body of the message :param attachments: The attachments of the message :param content: The type of content the message [text/html] :return: True on success, False otherwise """ self._server.connect() self._server.send(sender, recipients, cc, bcc, subject, body, attachments, content) self._server.disconnect() return True
python
def send(self, sender, recipients, cc=None, bcc=None, subject='', body='', attachments=None, content='text'): """Sends the email by connecting and disconnecting after the send :param sender: The sender of the message :param recipients: The recipients (To:) of the message :param cc: The CC recipients of the message :param bcc: The BCC recipients of the message :param subject: The subject of the message :param body: The body of the message :param attachments: The attachments of the message :param content: The type of content the message [text/html] :return: True on success, False otherwise """ self._server.connect() self._server.send(sender, recipients, cc, bcc, subject, body, attachments, content) self._server.disconnect() return True
[ "def", "send", "(", "self", ",", "sender", ",", "recipients", ",", "cc", "=", "None", ",", "bcc", "=", "None", ",", "subject", "=", "''", ",", "body", "=", "''", ",", "attachments", "=", "None", ",", "content", "=", "'text'", ")", ":", "self", ".", "_server", ".", "connect", "(", ")", "self", ".", "_server", ".", "send", "(", "sender", ",", "recipients", ",", "cc", ",", "bcc", ",", "subject", ",", "body", ",", "attachments", ",", "content", ")", "self", ".", "_server", ".", "disconnect", "(", ")", "return", "True" ]
Sends the email by connecting and disconnecting after the send :param sender: The sender of the message :param recipients: The recipients (To:) of the message :param cc: The CC recipients of the message :param bcc: The BCC recipients of the message :param subject: The subject of the message :param body: The body of the message :param attachments: The attachments of the message :param content: The type of content the message [text/html] :return: True on success, False otherwise
[ "Sends", "the", "email", "by", "connecting", "and", "disconnecting", "after", "the", "send" ]
2a00a3c5d4745898b96e858607b43784fa566fac
https://github.com/costastf/emaillib/blob/2a00a3c5d4745898b96e858607b43784fa566fac/emaillib/emaillib.py#L182-L214
245,749
costastf/emaillib
emaillib/emaillib.py
Message._setup_message
def _setup_message(self): """Constructs the actual underlying message with provided values""" if self.content == 'html': self._message = MIMEMultipart('alternative') part = MIMEText(self.body, 'html', 'UTF-8') else: self._message = MIMEMultipart() part = MIMEText(self.body, 'plain', 'UTF-8') self._message.preamble = 'Multipart massage.\n' self._message.attach(part) self._message['From'] = self.sender self._message['To'] = COMMASPACE.join(self.to) if self.cc: self._message['Cc'] = COMMASPACE.join(self.cc) self._message['Date'] = formatdate(localtime=True) self._message['Subject'] = self.subject for part in self._parts: self._message.attach(part)
python
def _setup_message(self): """Constructs the actual underlying message with provided values""" if self.content == 'html': self._message = MIMEMultipart('alternative') part = MIMEText(self.body, 'html', 'UTF-8') else: self._message = MIMEMultipart() part = MIMEText(self.body, 'plain', 'UTF-8') self._message.preamble = 'Multipart massage.\n' self._message.attach(part) self._message['From'] = self.sender self._message['To'] = COMMASPACE.join(self.to) if self.cc: self._message['Cc'] = COMMASPACE.join(self.cc) self._message['Date'] = formatdate(localtime=True) self._message['Subject'] = self.subject for part in self._parts: self._message.attach(part)
[ "def", "_setup_message", "(", "self", ")", ":", "if", "self", ".", "content", "==", "'html'", ":", "self", ".", "_message", "=", "MIMEMultipart", "(", "'alternative'", ")", "part", "=", "MIMEText", "(", "self", ".", "body", ",", "'html'", ",", "'UTF-8'", ")", "else", ":", "self", ".", "_message", "=", "MIMEMultipart", "(", ")", "part", "=", "MIMEText", "(", "self", ".", "body", ",", "'plain'", ",", "'UTF-8'", ")", "self", ".", "_message", ".", "preamble", "=", "'Multipart massage.\\n'", "self", ".", "_message", ".", "attach", "(", "part", ")", "self", ".", "_message", "[", "'From'", "]", "=", "self", ".", "sender", "self", ".", "_message", "[", "'To'", "]", "=", "COMMASPACE", ".", "join", "(", "self", ".", "to", ")", "if", "self", ".", "cc", ":", "self", ".", "_message", "[", "'Cc'", "]", "=", "COMMASPACE", ".", "join", "(", "self", ".", "cc", ")", "self", ".", "_message", "[", "'Date'", "]", "=", "formatdate", "(", "localtime", "=", "True", ")", "self", ".", "_message", "[", "'Subject'", "]", "=", "self", ".", "subject", "for", "part", "in", "self", ".", "_parts", ":", "self", ".", "_message", ".", "attach", "(", "part", ")" ]
Constructs the actual underlying message with provided values
[ "Constructs", "the", "actual", "underlying", "message", "with", "provided", "values" ]
2a00a3c5d4745898b96e858607b43784fa566fac
https://github.com/costastf/emaillib/blob/2a00a3c5d4745898b96e858607b43784fa566fac/emaillib/emaillib.py#L250-L267
245,750
costastf/emaillib
emaillib/emaillib.py
Message._validate_simple
def _validate_simple(email): """Does a simple validation of an email by matching it to a regexps :param email: The email to check :return: The valid Email address :raises: ValueError if value is not a valid email """ name, address = parseaddr(email) if not re.match('[^@]+@[^@]+\.[^@]+', address): raise ValueError('Invalid email :{email}'.format(email=email)) return address
python
def _validate_simple(email): """Does a simple validation of an email by matching it to a regexps :param email: The email to check :return: The valid Email address :raises: ValueError if value is not a valid email """ name, address = parseaddr(email) if not re.match('[^@]+@[^@]+\.[^@]+', address): raise ValueError('Invalid email :{email}'.format(email=email)) return address
[ "def", "_validate_simple", "(", "email", ")", ":", "name", ",", "address", "=", "parseaddr", "(", "email", ")", "if", "not", "re", ".", "match", "(", "'[^@]+@[^@]+\\.[^@]+'", ",", "address", ")", ":", "raise", "ValueError", "(", "'Invalid email :{email}'", ".", "format", "(", "email", "=", "email", ")", ")", "return", "address" ]
Does a simple validation of an email by matching it to a regexps :param email: The email to check :return: The valid Email address :raises: ValueError if value is not a valid email
[ "Does", "a", "simple", "validation", "of", "an", "email", "by", "matching", "it", "to", "a", "regexps" ]
2a00a3c5d4745898b96e858607b43784fa566fac
https://github.com/costastf/emaillib/blob/2a00a3c5d4745898b96e858607b43784fa566fac/emaillib/emaillib.py#L270-L281
245,751
edeposit/edeposit.amqp.harvester
src/edeposit/amqp/harvester/filters/dup_filter.py
save_cache
def save_cache(cache): """ Save cahce to the disk. Args: cache (set): Set with cached data. """ with open(settings.DUP_FILTER_FILE, "w") as f: f.write( json.dumps(list(cache)) )
python
def save_cache(cache): """ Save cahce to the disk. Args: cache (set): Set with cached data. """ with open(settings.DUP_FILTER_FILE, "w") as f: f.write( json.dumps(list(cache)) )
[ "def", "save_cache", "(", "cache", ")", ":", "with", "open", "(", "settings", ".", "DUP_FILTER_FILE", ",", "\"w\"", ")", "as", "f", ":", "f", ".", "write", "(", "json", ".", "dumps", "(", "list", "(", "cache", ")", ")", ")" ]
Save cahce to the disk. Args: cache (set): Set with cached data.
[ "Save", "cahce", "to", "the", "disk", "." ]
38cb87ccdf6bf2f550a98460d0a329c4b9dc8e2e
https://github.com/edeposit/edeposit.amqp.harvester/blob/38cb87ccdf6bf2f550a98460d0a329c4b9dc8e2e/src/edeposit/amqp/harvester/filters/dup_filter.py#L29-L39
245,752
edeposit/edeposit.amqp.harvester
src/edeposit/amqp/harvester/filters/dup_filter.py
load_cache
def load_cache(): """ Load cache from the disk. Return: set: Deserialized data from disk. """ if not os.path.exists(settings.DUP_FILTER_FILE): return set() with open(settings.DUP_FILTER_FILE) as f: return set( json.loads(f.read()) )
python
def load_cache(): """ Load cache from the disk. Return: set: Deserialized data from disk. """ if not os.path.exists(settings.DUP_FILTER_FILE): return set() with open(settings.DUP_FILTER_FILE) as f: return set( json.loads(f.read()) )
[ "def", "load_cache", "(", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "settings", ".", "DUP_FILTER_FILE", ")", ":", "return", "set", "(", ")", "with", "open", "(", "settings", ".", "DUP_FILTER_FILE", ")", "as", "f", ":", "return", "set", "(", "json", ".", "loads", "(", "f", ".", "read", "(", ")", ")", ")" ]
Load cache from the disk. Return: set: Deserialized data from disk.
[ "Load", "cache", "from", "the", "disk", "." ]
38cb87ccdf6bf2f550a98460d0a329c4b9dc8e2e
https://github.com/edeposit/edeposit.amqp.harvester/blob/38cb87ccdf6bf2f550a98460d0a329c4b9dc8e2e/src/edeposit/amqp/harvester/filters/dup_filter.py#L42-L55
245,753
edeposit/edeposit.amqp.harvester
src/edeposit/amqp/harvester/filters/dup_filter.py
filter_publication
def filter_publication(publication, cache=_CACHE): """ Deduplication function, which compares `publication` with samples stored in `cache`. If the match NOT is found, `publication` is returned, else None. Args: publication (obj): :class:`.Publication` instance. cache (obj): Cache which is used for lookups. Returns: obj/None: Depends whether the object is found in cache or not. """ if cache is None: cache = load_cache() if publication._get_hash() in cache: return None cache.update( [publication._get_hash()] ) save_cache(cache) return publication
python
def filter_publication(publication, cache=_CACHE): """ Deduplication function, which compares `publication` with samples stored in `cache`. If the match NOT is found, `publication` is returned, else None. Args: publication (obj): :class:`.Publication` instance. cache (obj): Cache which is used for lookups. Returns: obj/None: Depends whether the object is found in cache or not. """ if cache is None: cache = load_cache() if publication._get_hash() in cache: return None cache.update( [publication._get_hash()] ) save_cache(cache) return publication
[ "def", "filter_publication", "(", "publication", ",", "cache", "=", "_CACHE", ")", ":", "if", "cache", "is", "None", ":", "cache", "=", "load_cache", "(", ")", "if", "publication", ".", "_get_hash", "(", ")", "in", "cache", ":", "return", "None", "cache", ".", "update", "(", "[", "publication", ".", "_get_hash", "(", ")", "]", ")", "save_cache", "(", "cache", ")", "return", "publication" ]
Deduplication function, which compares `publication` with samples stored in `cache`. If the match NOT is found, `publication` is returned, else None. Args: publication (obj): :class:`.Publication` instance. cache (obj): Cache which is used for lookups. Returns: obj/None: Depends whether the object is found in cache or not.
[ "Deduplication", "function", "which", "compares", "publication", "with", "samples", "stored", "in", "cache", ".", "If", "the", "match", "NOT", "is", "found", "publication", "is", "returned", "else", "None", "." ]
38cb87ccdf6bf2f550a98460d0a329c4b9dc8e2e
https://github.com/edeposit/edeposit.amqp.harvester/blob/38cb87ccdf6bf2f550a98460d0a329c4b9dc8e2e/src/edeposit/amqp/harvester/filters/dup_filter.py#L58-L80
245,754
minhhoit/yacms
yacms/core/fields.py
RichTextField.formfield
def formfield(self, **kwargs): """ Apply the widget class defined by the ``RICHTEXT_WIDGET_CLASS`` setting. """ default = kwargs.get("widget", None) or AdminTextareaWidget if default is AdminTextareaWidget: from yacms.conf import settings richtext_widget_path = settings.RICHTEXT_WIDGET_CLASS try: widget_class = import_dotted_path(richtext_widget_path) except ImportError: raise ImproperlyConfigured(_("Could not import the value of " "settings.RICHTEXT_WIDGET_CLASS: " "%s" % richtext_widget_path)) kwargs["widget"] = widget_class() kwargs.setdefault("required", False) formfield = super(RichTextField, self).formfield(**kwargs) return formfield
python
def formfield(self, **kwargs): """ Apply the widget class defined by the ``RICHTEXT_WIDGET_CLASS`` setting. """ default = kwargs.get("widget", None) or AdminTextareaWidget if default is AdminTextareaWidget: from yacms.conf import settings richtext_widget_path = settings.RICHTEXT_WIDGET_CLASS try: widget_class = import_dotted_path(richtext_widget_path) except ImportError: raise ImproperlyConfigured(_("Could not import the value of " "settings.RICHTEXT_WIDGET_CLASS: " "%s" % richtext_widget_path)) kwargs["widget"] = widget_class() kwargs.setdefault("required", False) formfield = super(RichTextField, self).formfield(**kwargs) return formfield
[ "def", "formfield", "(", "self", ",", "*", "*", "kwargs", ")", ":", "default", "=", "kwargs", ".", "get", "(", "\"widget\"", ",", "None", ")", "or", "AdminTextareaWidget", "if", "default", "is", "AdminTextareaWidget", ":", "from", "yacms", ".", "conf", "import", "settings", "richtext_widget_path", "=", "settings", ".", "RICHTEXT_WIDGET_CLASS", "try", ":", "widget_class", "=", "import_dotted_path", "(", "richtext_widget_path", ")", "except", "ImportError", ":", "raise", "ImproperlyConfigured", "(", "_", "(", "\"Could not import the value of \"", "\"settings.RICHTEXT_WIDGET_CLASS: \"", "\"%s\"", "%", "richtext_widget_path", ")", ")", "kwargs", "[", "\"widget\"", "]", "=", "widget_class", "(", ")", "kwargs", ".", "setdefault", "(", "\"required\"", ",", "False", ")", "formfield", "=", "super", "(", "RichTextField", ",", "self", ")", ".", "formfield", "(", "*", "*", "kwargs", ")", "return", "formfield" ]
Apply the widget class defined by the ``RICHTEXT_WIDGET_CLASS`` setting.
[ "Apply", "the", "widget", "class", "defined", "by", "the", "RICHTEXT_WIDGET_CLASS", "setting", "." ]
2921b706b7107c6e8c5f2bbf790ff11f85a2167f
https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/core/fields.py#L29-L47
245,755
Pringley/spyglass
spyglass/util.py
get
def get(url): """Query a web URL. Return a Response object with the following attributes: - text: the full text of the web page - soup: a BeautifulSoup object representing the web page """ text = urlopen(url).read() soup = BeautifulSoup(text) return Response(text=text, soup=soup)
python
def get(url): """Query a web URL. Return a Response object with the following attributes: - text: the full text of the web page - soup: a BeautifulSoup object representing the web page """ text = urlopen(url).read() soup = BeautifulSoup(text) return Response(text=text, soup=soup)
[ "def", "get", "(", "url", ")", ":", "text", "=", "urlopen", "(", "url", ")", ".", "read", "(", ")", "soup", "=", "BeautifulSoup", "(", "text", ")", "return", "Response", "(", "text", "=", "text", ",", "soup", "=", "soup", ")" ]
Query a web URL. Return a Response object with the following attributes: - text: the full text of the web page - soup: a BeautifulSoup object representing the web page
[ "Query", "a", "web", "URL", "." ]
091d74f34837673af936daa9f462ad8216be9916
https://github.com/Pringley/spyglass/blob/091d74f34837673af936daa9f462ad8216be9916/spyglass/util.py#L7-L17
245,756
bennylope/garland
garland.py
mock_decorator
def mock_decorator(*a, **k): """ An pass-through decorator that returns the underlying function. This is used as the default for replacing decorators. """ # This is a decorator without parameters, e.g. # # @login_required # def some_view(request): # ... # if a: # This could fail in the instance where a callable argument is passed # as a parameter to the decorator! if callable(a[0]): def wrapper(*args, **kwargs): return a[0](*args, **kwargs) return wrapper # This is a decorator with parameters, e.g. # # @render_template("index.html") # def some_view(request): # ... # def real_decorator(function): def wrapper(*args, **kwargs): return function(*args, **kwargs) return wrapper return real_decorator
python
def mock_decorator(*a, **k): """ An pass-through decorator that returns the underlying function. This is used as the default for replacing decorators. """ # This is a decorator without parameters, e.g. # # @login_required # def some_view(request): # ... # if a: # This could fail in the instance where a callable argument is passed # as a parameter to the decorator! if callable(a[0]): def wrapper(*args, **kwargs): return a[0](*args, **kwargs) return wrapper # This is a decorator with parameters, e.g. # # @render_template("index.html") # def some_view(request): # ... # def real_decorator(function): def wrapper(*args, **kwargs): return function(*args, **kwargs) return wrapper return real_decorator
[ "def", "mock_decorator", "(", "*", "a", ",", "*", "*", "k", ")", ":", "# This is a decorator without parameters, e.g.", "#", "# @login_required", "# def some_view(request):", "# ...", "#", "if", "a", ":", "# This could fail in the instance where a callable argument is passed", "# as a parameter to the decorator!", "if", "callable", "(", "a", "[", "0", "]", ")", ":", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "a", "[", "0", "]", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "wrapper", "# This is a decorator with parameters, e.g.", "#", "# @render_template(\"index.html\")", "# def some_view(request):", "# ...", "#", "def", "real_decorator", "(", "function", ")", ":", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "function", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "wrapper", "return", "real_decorator" ]
An pass-through decorator that returns the underlying function. This is used as the default for replacing decorators.
[ "An", "pass", "-", "through", "decorator", "that", "returns", "the", "underlying", "function", "." ]
3540d80043f096c16fa2cbc48609aee849f18995
https://github.com/bennylope/garland/blob/3540d80043f096c16fa2cbc48609aee849f18995/garland.py#L21-L51
245,757
bennylope/garland
garland.py
tinsel
def tinsel(to_patch, module_name, decorator=mock_decorator): """ Decorator for simple in-place decorator mocking for tests Args: to_patch: the string path of the function to patch module_name: complete string path of the module to reload decorator (optional): replacement decorator. By default a pass-through will be used. Returns: A wrapped test function, during the context of execution the specified path is patched. """ def fn_decorator(function): def wrapper(*args, **kwargs): with patch(to_patch, decorator): m = importlib.import_module(module_name) reload(m) function(*args, **kwargs) reload(m) return wrapper return fn_decorator
python
def tinsel(to_patch, module_name, decorator=mock_decorator): """ Decorator for simple in-place decorator mocking for tests Args: to_patch: the string path of the function to patch module_name: complete string path of the module to reload decorator (optional): replacement decorator. By default a pass-through will be used. Returns: A wrapped test function, during the context of execution the specified path is patched. """ def fn_decorator(function): def wrapper(*args, **kwargs): with patch(to_patch, decorator): m = importlib.import_module(module_name) reload(m) function(*args, **kwargs) reload(m) return wrapper return fn_decorator
[ "def", "tinsel", "(", "to_patch", ",", "module_name", ",", "decorator", "=", "mock_decorator", ")", ":", "def", "fn_decorator", "(", "function", ")", ":", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "with", "patch", "(", "to_patch", ",", "decorator", ")", ":", "m", "=", "importlib", ".", "import_module", "(", "module_name", ")", "reload", "(", "m", ")", "function", "(", "*", "args", ",", "*", "*", "kwargs", ")", "reload", "(", "m", ")", "return", "wrapper", "return", "fn_decorator" ]
Decorator for simple in-place decorator mocking for tests Args: to_patch: the string path of the function to patch module_name: complete string path of the module to reload decorator (optional): replacement decorator. By default a pass-through will be used. Returns: A wrapped test function, during the context of execution the specified path is patched.
[ "Decorator", "for", "simple", "in", "-", "place", "decorator", "mocking", "for", "tests" ]
3540d80043f096c16fa2cbc48609aee849f18995
https://github.com/bennylope/garland/blob/3540d80043f096c16fa2cbc48609aee849f18995/garland.py#L54-L78
245,758
akatrevorjay/uninhibited
uninhibited/async/__init__.py
EventFireIter.anext
async def anext(self): """Fetch the next value from the iterable.""" try: f = next(self._iter) except StopIteration as exc: raise StopAsyncIteration() from exc return await f
python
async def anext(self): """Fetch the next value from the iterable.""" try: f = next(self._iter) except StopIteration as exc: raise StopAsyncIteration() from exc return await f
[ "async", "def", "anext", "(", "self", ")", ":", "try", ":", "f", "=", "next", "(", "self", ".", "_iter", ")", "except", "StopIteration", "as", "exc", ":", "raise", "StopAsyncIteration", "(", ")", "from", "exc", "return", "await", "f" ]
Fetch the next value from the iterable.
[ "Fetch", "the", "next", "value", "from", "the", "iterable", "." ]
f23079fe61cf831fa274d3c60bda8076c571d3f1
https://github.com/akatrevorjay/uninhibited/blob/f23079fe61cf831fa274d3c60bda8076c571d3f1/uninhibited/async/__init__.py#L27-L33
245,759
xtrementl/focus
focus/parser/lexer.py
SettingLexer._new_token
def _new_token(self, chars=None, line_no=None): """ Appends new token to token stream. `chars` List of token characters. Defaults to current token list. `line_no` Line number for token. Defaults to current line number. """ if not line_no: line_no = self._line_no if not chars: chars = self._token_chars if chars: # add new token self._tokens.append((line_no, ''.join(chars))) self._token_chars = []
python
def _new_token(self, chars=None, line_no=None): """ Appends new token to token stream. `chars` List of token characters. Defaults to current token list. `line_no` Line number for token. Defaults to current line number. """ if not line_no: line_no = self._line_no if not chars: chars = self._token_chars if chars: # add new token self._tokens.append((line_no, ''.join(chars))) self._token_chars = []
[ "def", "_new_token", "(", "self", ",", "chars", "=", "None", ",", "line_no", "=", "None", ")", ":", "if", "not", "line_no", ":", "line_no", "=", "self", ".", "_line_no", "if", "not", "chars", ":", "chars", "=", "self", ".", "_token_chars", "if", "chars", ":", "# add new token", "self", ".", "_tokens", ".", "append", "(", "(", "line_no", ",", "''", ".", "join", "(", "chars", ")", ")", ")", "self", ".", "_token_chars", "=", "[", "]" ]
Appends new token to token stream. `chars` List of token characters. Defaults to current token list. `line_no` Line number for token. Defaults to current line number.
[ "Appends", "new", "token", "to", "token", "stream", "." ]
cbbbc0b49a7409f9e0dc899de5b7e057f50838e4
https://github.com/xtrementl/focus/blob/cbbbc0b49a7409f9e0dc899de5b7e057f50838e4/focus/parser/lexer.py#L65-L83
245,760
xtrementl/focus
focus/parser/lexer.py
SettingLexer._process_newline
def _process_newline(self, char): """ Process a newline character. """ state = self._state # inside string, just append char to token if state == self.ST_STRING: self._token_chars.append(char) else: # otherwise, add new token self._new_token() self._line_no += 1 # update line counter # finished with comment if state == self.ST_COMMENT: self._state = self.ST_TOKEN
python
def _process_newline(self, char): """ Process a newline character. """ state = self._state # inside string, just append char to token if state == self.ST_STRING: self._token_chars.append(char) else: # otherwise, add new token self._new_token() self._line_no += 1 # update line counter # finished with comment if state == self.ST_COMMENT: self._state = self.ST_TOKEN
[ "def", "_process_newline", "(", "self", ",", "char", ")", ":", "state", "=", "self", ".", "_state", "# inside string, just append char to token", "if", "state", "==", "self", ".", "ST_STRING", ":", "self", ".", "_token_chars", ".", "append", "(", "char", ")", "else", ":", "# otherwise, add new token", "self", ".", "_new_token", "(", ")", "self", ".", "_line_no", "+=", "1", "# update line counter", "# finished with comment", "if", "state", "==", "self", ".", "ST_COMMENT", ":", "self", ".", "_state", "=", "self", ".", "ST_TOKEN" ]
Process a newline character.
[ "Process", "a", "newline", "character", "." ]
cbbbc0b49a7409f9e0dc899de5b7e057f50838e4
https://github.com/xtrementl/focus/blob/cbbbc0b49a7409f9e0dc899de5b7e057f50838e4/focus/parser/lexer.py#L85-L102
245,761
xtrementl/focus
focus/parser/lexer.py
SettingLexer._process_string
def _process_string(self, char): """ Process a character as part of a string token. """ if char in self.QUOTES: # end of quoted string: # 1) quote must match original quote # 2) not escaped quote (e.g. "hey there" vs "hey there\") # 3) actual escape char prior (e.g. "hey there\\") if (char == self._last_quote and not self._escaped or self._double_escaped): # store token self._new_token() self._state = self.ST_TOKEN return # skip adding token char elif char == self.ESCAPE: # escape character: # double escaped if prior char was escape (e.g. "hey \\ there") if not self._double_escaped: self._double_escaped = self._escaped else: self._double_escaped = False self._token_chars.append(char)
python
def _process_string(self, char): """ Process a character as part of a string token. """ if char in self.QUOTES: # end of quoted string: # 1) quote must match original quote # 2) not escaped quote (e.g. "hey there" vs "hey there\") # 3) actual escape char prior (e.g. "hey there\\") if (char == self._last_quote and not self._escaped or self._double_escaped): # store token self._new_token() self._state = self.ST_TOKEN return # skip adding token char elif char == self.ESCAPE: # escape character: # double escaped if prior char was escape (e.g. "hey \\ there") if not self._double_escaped: self._double_escaped = self._escaped else: self._double_escaped = False self._token_chars.append(char)
[ "def", "_process_string", "(", "self", ",", "char", ")", ":", "if", "char", "in", "self", ".", "QUOTES", ":", "# end of quoted string:", "# 1) quote must match original quote", "# 2) not escaped quote (e.g. \"hey there\" vs \"hey there\\\")", "# 3) actual escape char prior (e.g. \"hey there\\\\\")", "if", "(", "char", "==", "self", ".", "_last_quote", "and", "not", "self", ".", "_escaped", "or", "self", ".", "_double_escaped", ")", ":", "# store token", "self", ".", "_new_token", "(", ")", "self", ".", "_state", "=", "self", ".", "ST_TOKEN", "return", "# skip adding token char", "elif", "char", "==", "self", ".", "ESCAPE", ":", "# escape character:", "# double escaped if prior char was escape (e.g. \"hey \\\\ there\")", "if", "not", "self", ".", "_double_escaped", ":", "self", ".", "_double_escaped", "=", "self", ".", "_escaped", "else", ":", "self", ".", "_double_escaped", "=", "False", "self", ".", "_token_chars", ".", "append", "(", "char", ")" ]
Process a character as part of a string token.
[ "Process", "a", "character", "as", "part", "of", "a", "string", "token", "." ]
cbbbc0b49a7409f9e0dc899de5b7e057f50838e4
https://github.com/xtrementl/focus/blob/cbbbc0b49a7409f9e0dc899de5b7e057f50838e4/focus/parser/lexer.py#L104-L132
245,762
xtrementl/focus
focus/parser/lexer.py
SettingLexer._process_tokens
def _process_tokens(self, char): """ Process a token character. """ if (char in self.WHITESPACE or char == self.COMMENT_START or char in self.QUOTES or char in self.TOKENS): add_token = True # escaped chars, keep going if char == self.SPACE or char in self.TOKENS: if self._escaped: add_token = False # start of comment elif char == self.COMMENT_START: self._state = self.ST_COMMENT # start of quoted string elif char in self.QUOTES: if self._escaped: # escaped, keep going add_token = False else: self._state = self.ST_STRING self._last_quote = char # store for later quote matching if add_token: # store token self._new_token() if char in self.TOKENS: # store char as a new token self._new_token([char]) return # skip adding token char self._token_chars.append(char)
python
def _process_tokens(self, char): """ Process a token character. """ if (char in self.WHITESPACE or char == self.COMMENT_START or char in self.QUOTES or char in self.TOKENS): add_token = True # escaped chars, keep going if char == self.SPACE or char in self.TOKENS: if self._escaped: add_token = False # start of comment elif char == self.COMMENT_START: self._state = self.ST_COMMENT # start of quoted string elif char in self.QUOTES: if self._escaped: # escaped, keep going add_token = False else: self._state = self.ST_STRING self._last_quote = char # store for later quote matching if add_token: # store token self._new_token() if char in self.TOKENS: # store char as a new token self._new_token([char]) return # skip adding token char self._token_chars.append(char)
[ "def", "_process_tokens", "(", "self", ",", "char", ")", ":", "if", "(", "char", "in", "self", ".", "WHITESPACE", "or", "char", "==", "self", ".", "COMMENT_START", "or", "char", "in", "self", ".", "QUOTES", "or", "char", "in", "self", ".", "TOKENS", ")", ":", "add_token", "=", "True", "# escaped chars, keep going", "if", "char", "==", "self", ".", "SPACE", "or", "char", "in", "self", ".", "TOKENS", ":", "if", "self", ".", "_escaped", ":", "add_token", "=", "False", "# start of comment", "elif", "char", "==", "self", ".", "COMMENT_START", ":", "self", ".", "_state", "=", "self", ".", "ST_COMMENT", "# start of quoted string", "elif", "char", "in", "self", ".", "QUOTES", ":", "if", "self", ".", "_escaped", ":", "# escaped, keep going", "add_token", "=", "False", "else", ":", "self", ".", "_state", "=", "self", ".", "ST_STRING", "self", ".", "_last_quote", "=", "char", "# store for later quote matching", "if", "add_token", ":", "# store token", "self", ".", "_new_token", "(", ")", "if", "char", "in", "self", ".", "TOKENS", ":", "# store char as a new token", "self", ".", "_new_token", "(", "[", "char", "]", ")", "return", "# skip adding token char", "self", ".", "_token_chars", ".", "append", "(", "char", ")" ]
Process a token character.
[ "Process", "a", "token", "character", "." ]
cbbbc0b49a7409f9e0dc899de5b7e057f50838e4
https://github.com/xtrementl/focus/blob/cbbbc0b49a7409f9e0dc899de5b7e057f50838e4/focus/parser/lexer.py#L134-L172
245,763
xtrementl/focus
focus/parser/lexer.py
SettingLexer._tokenize
def _tokenize(self, stream): """ Tokenizes data from the provided string. ``stream`` ``File``-like object. """ self._tokens = [] self._reset_token() self._state = self.ST_TOKEN for chunk in iter(lambda: stream.read(8192), ''): for char in chunk: if char in self.NEWLINES: self._process_newline(char) else: state = self._state if state == self.ST_STRING: self._process_string(char) elif state == self.ST_TOKEN: self._process_tokens(char)
python
def _tokenize(self, stream): """ Tokenizes data from the provided string. ``stream`` ``File``-like object. """ self._tokens = [] self._reset_token() self._state = self.ST_TOKEN for chunk in iter(lambda: stream.read(8192), ''): for char in chunk: if char in self.NEWLINES: self._process_newline(char) else: state = self._state if state == self.ST_STRING: self._process_string(char) elif state == self.ST_TOKEN: self._process_tokens(char)
[ "def", "_tokenize", "(", "self", ",", "stream", ")", ":", "self", ".", "_tokens", "=", "[", "]", "self", ".", "_reset_token", "(", ")", "self", ".", "_state", "=", "self", ".", "ST_TOKEN", "for", "chunk", "in", "iter", "(", "lambda", ":", "stream", ".", "read", "(", "8192", ")", ",", "''", ")", ":", "for", "char", "in", "chunk", ":", "if", "char", "in", "self", ".", "NEWLINES", ":", "self", ".", "_process_newline", "(", "char", ")", "else", ":", "state", "=", "self", ".", "_state", "if", "state", "==", "self", ".", "ST_STRING", ":", "self", ".", "_process_string", "(", "char", ")", "elif", "state", "==", "self", ".", "ST_TOKEN", ":", "self", ".", "_process_tokens", "(", "char", ")" ]
Tokenizes data from the provided string. ``stream`` ``File``-like object.
[ "Tokenizes", "data", "from", "the", "provided", "string", "." ]
cbbbc0b49a7409f9e0dc899de5b7e057f50838e4
https://github.com/xtrementl/focus/blob/cbbbc0b49a7409f9e0dc899de5b7e057f50838e4/focus/parser/lexer.py#L174-L197
245,764
xtrementl/focus
focus/parser/lexer.py
SettingLexer.read
def read(self, filename): """ Reads the file specified and tokenizes the data for parsing. """ try: with open(filename, 'r') as _file: self._filename = filename self.readstream(_file) return True except IOError: self._filename = None return False
python
def read(self, filename): """ Reads the file specified and tokenizes the data for parsing. """ try: with open(filename, 'r') as _file: self._filename = filename self.readstream(_file) return True except IOError: self._filename = None return False
[ "def", "read", "(", "self", ",", "filename", ")", ":", "try", ":", "with", "open", "(", "filename", ",", "'r'", ")", "as", "_file", ":", "self", ".", "_filename", "=", "filename", "self", ".", "readstream", "(", "_file", ")", "return", "True", "except", "IOError", ":", "self", ".", "_filename", "=", "None", "return", "False" ]
Reads the file specified and tokenizes the data for parsing.
[ "Reads", "the", "file", "specified", "and", "tokenizes", "the", "data", "for", "parsing", "." ]
cbbbc0b49a7409f9e0dc899de5b7e057f50838e4
https://github.com/xtrementl/focus/blob/cbbbc0b49a7409f9e0dc899de5b7e057f50838e4/focus/parser/lexer.py#L199-L211
245,765
xtrementl/focus
focus/parser/lexer.py
SettingLexer._escaped
def _escaped(self): """ Escape character is at end of accumulated token character list. """ chars = self._token_info['chars'] count = len(chars) # prev char is escape, keep going if count and chars[count - 1] == self.ESCAPE: chars.pop() # swallow escape char return True else: return False
python
def _escaped(self): """ Escape character is at end of accumulated token character list. """ chars = self._token_info['chars'] count = len(chars) # prev char is escape, keep going if count and chars[count - 1] == self.ESCAPE: chars.pop() # swallow escape char return True else: return False
[ "def", "_escaped", "(", "self", ")", ":", "chars", "=", "self", ".", "_token_info", "[", "'chars'", "]", "count", "=", "len", "(", "chars", ")", "# prev char is escape, keep going", "if", "count", "and", "chars", "[", "count", "-", "1", "]", "==", "self", ".", "ESCAPE", ":", "chars", ".", "pop", "(", ")", "# swallow escape char", "return", "True", "else", ":", "return", "False" ]
Escape character is at end of accumulated token character list.
[ "Escape", "character", "is", "at", "end", "of", "accumulated", "token", "character", "list", "." ]
cbbbc0b49a7409f9e0dc899de5b7e057f50838e4
https://github.com/xtrementl/focus/blob/cbbbc0b49a7409f9e0dc899de5b7e057f50838e4/focus/parser/lexer.py#L303-L316
245,766
4Kaylum/Brickfront
brickfront/client.py
Client.checkResponse
def checkResponse(request): ''' Returns if a request has an okay error code, otherwise raises InvalidRequest. ''' # Check the status code of the returned request if str(request.status_code)[0] not in ['2', '3']: w = str(request.text).split('\\r')[0][2:] raise InvalidRequest(w) return
python
def checkResponse(request): ''' Returns if a request has an okay error code, otherwise raises InvalidRequest. ''' # Check the status code of the returned request if str(request.status_code)[0] not in ['2', '3']: w = str(request.text).split('\\r')[0][2:] raise InvalidRequest(w) return
[ "def", "checkResponse", "(", "request", ")", ":", "# Check the status code of the returned request", "if", "str", "(", "request", ".", "status_code", ")", "[", "0", "]", "not", "in", "[", "'2'", ",", "'3'", "]", ":", "w", "=", "str", "(", "request", ".", "text", ")", ".", "split", "(", "'\\\\r'", ")", "[", "0", "]", "[", "2", ":", "]", "raise", "InvalidRequest", "(", "w", ")", "return" ]
Returns if a request has an okay error code, otherwise raises InvalidRequest.
[ "Returns", "if", "a", "request", "has", "an", "okay", "error", "code", "otherwise", "raises", "InvalidRequest", "." ]
9545f2183249862b077677d48fcfb9b4bfe1f87d
https://github.com/4Kaylum/Brickfront/blob/9545f2183249862b077677d48fcfb9b4bfe1f87d/brickfront/client.py#L30-L39
245,767
4Kaylum/Brickfront
brickfront/client.py
Client.checkKey
def checkKey(self, key=None): ''' Checks that an API key is valid. :param str key: (optional) A key that you want to check the validity of. Defaults to the one provided on initialization. :returns: If the key is valid, this method will return ``True``. :rtype: `bool` :raises: :class:`brickfront.errors.InvalidApiKey` ''' # Get site url = Client.ENDPOINT.format('checkKey') if not key: key = self.apiKey params = { 'apiKey': key or self.apiKey } returned = get(url, params=params) self.checkResponse(returned) # Parse and return root = ET.fromstring(returned.text) if root.text == 'OK': return True raise InvalidApiKey('The provided API key `{}` was invalid.'.format(key))
python
def checkKey(self, key=None): ''' Checks that an API key is valid. :param str key: (optional) A key that you want to check the validity of. Defaults to the one provided on initialization. :returns: If the key is valid, this method will return ``True``. :rtype: `bool` :raises: :class:`brickfront.errors.InvalidApiKey` ''' # Get site url = Client.ENDPOINT.format('checkKey') if not key: key = self.apiKey params = { 'apiKey': key or self.apiKey } returned = get(url, params=params) self.checkResponse(returned) # Parse and return root = ET.fromstring(returned.text) if root.text == 'OK': return True raise InvalidApiKey('The provided API key `{}` was invalid.'.format(key))
[ "def", "checkKey", "(", "self", ",", "key", "=", "None", ")", ":", "# Get site", "url", "=", "Client", ".", "ENDPOINT", ".", "format", "(", "'checkKey'", ")", "if", "not", "key", ":", "key", "=", "self", ".", "apiKey", "params", "=", "{", "'apiKey'", ":", "key", "or", "self", ".", "apiKey", "}", "returned", "=", "get", "(", "url", ",", "params", "=", "params", ")", "self", ".", "checkResponse", "(", "returned", ")", "# Parse and return", "root", "=", "ET", ".", "fromstring", "(", "returned", ".", "text", ")", "if", "root", ".", "text", "==", "'OK'", ":", "return", "True", "raise", "InvalidApiKey", "(", "'The provided API key `{}` was invalid.'", ".", "format", "(", "key", ")", ")" ]
Checks that an API key is valid. :param str key: (optional) A key that you want to check the validity of. Defaults to the one provided on initialization. :returns: If the key is valid, this method will return ``True``. :rtype: `bool` :raises: :class:`brickfront.errors.InvalidApiKey`
[ "Checks", "that", "an", "API", "key", "is", "valid", "." ]
9545f2183249862b077677d48fcfb9b4bfe1f87d
https://github.com/4Kaylum/Brickfront/blob/9545f2183249862b077677d48fcfb9b4bfe1f87d/brickfront/client.py#L42-L65
245,768
4Kaylum/Brickfront
brickfront/client.py
Client.getSet
def getSet(self, setID): ''' Gets the information of one specific build using its Brickset set ID. :param str setID: The ID of the build from Brickset. :returns: A single Build object. :rtype: :class:`brickfront.build.Build` :raises brickfront.errors.InvalidSetID: If no sets exist by that ID. ''' params = { 'apiKey': self.apiKey, 'userHash': self.userHash, 'setID': setID } url = Client.ENDPOINT.format('getSet') returned = get(url, params=params) self.checkResponse(returned) # Put it into a Build class root = ET.fromstring(returned.text) v = [Build(i, self) for i in root] # Return to user try: return v[0] except IndexError: raise InvalidSetID('There is no set with the ID of `{}`.'.format(setID))
python
def getSet(self, setID): ''' Gets the information of one specific build using its Brickset set ID. :param str setID: The ID of the build from Brickset. :returns: A single Build object. :rtype: :class:`brickfront.build.Build` :raises brickfront.errors.InvalidSetID: If no sets exist by that ID. ''' params = { 'apiKey': self.apiKey, 'userHash': self.userHash, 'setID': setID } url = Client.ENDPOINT.format('getSet') returned = get(url, params=params) self.checkResponse(returned) # Put it into a Build class root = ET.fromstring(returned.text) v = [Build(i, self) for i in root] # Return to user try: return v[0] except IndexError: raise InvalidSetID('There is no set with the ID of `{}`.'.format(setID))
[ "def", "getSet", "(", "self", ",", "setID", ")", ":", "params", "=", "{", "'apiKey'", ":", "self", ".", "apiKey", ",", "'userHash'", ":", "self", ".", "userHash", ",", "'setID'", ":", "setID", "}", "url", "=", "Client", ".", "ENDPOINT", ".", "format", "(", "'getSet'", ")", "returned", "=", "get", "(", "url", ",", "params", "=", "params", ")", "self", ".", "checkResponse", "(", "returned", ")", "# Put it into a Build class", "root", "=", "ET", ".", "fromstring", "(", "returned", ".", "text", ")", "v", "=", "[", "Build", "(", "i", ",", "self", ")", "for", "i", "in", "root", "]", "# Return to user", "try", ":", "return", "v", "[", "0", "]", "except", "IndexError", ":", "raise", "InvalidSetID", "(", "'There is no set with the ID of `{}`.'", ".", "format", "(", "setID", ")", ")" ]
Gets the information of one specific build using its Brickset set ID. :param str setID: The ID of the build from Brickset. :returns: A single Build object. :rtype: :class:`brickfront.build.Build` :raises brickfront.errors.InvalidSetID: If no sets exist by that ID.
[ "Gets", "the", "information", "of", "one", "specific", "build", "using", "its", "Brickset", "set", "ID", "." ]
9545f2183249862b077677d48fcfb9b4bfe1f87d
https://github.com/4Kaylum/Brickfront/blob/9545f2183249862b077677d48fcfb9b4bfe1f87d/brickfront/client.py#L144-L171
245,769
4Kaylum/Brickfront
brickfront/client.py
Client.getRecentlyUpdatedSets
def getRecentlyUpdatedSets(self, minutesAgo): ''' Gets the information of recently updated sets. :param int minutesAgo: The amount of time ago that the set was updated. :returns: A list of Build instances that were updated within the given time. :rtype: list .. warning:: An empty list will be returned if there are no sets in the given time limit. ''' params = { 'apiKey': self.apiKey, 'minutesAgo': minutesAgo } url = Client.ENDPOINT.format('getRecentlyUpdatedSets') returned = get(url, params=params) self.checkResponse(returned) # Parse them in to build objects root = ET.fromstring(returned.text) return [Build(i, self) for i in root]
python
def getRecentlyUpdatedSets(self, minutesAgo): ''' Gets the information of recently updated sets. :param int minutesAgo: The amount of time ago that the set was updated. :returns: A list of Build instances that were updated within the given time. :rtype: list .. warning:: An empty list will be returned if there are no sets in the given time limit. ''' params = { 'apiKey': self.apiKey, 'minutesAgo': minutesAgo } url = Client.ENDPOINT.format('getRecentlyUpdatedSets') returned = get(url, params=params) self.checkResponse(returned) # Parse them in to build objects root = ET.fromstring(returned.text) return [Build(i, self) for i in root]
[ "def", "getRecentlyUpdatedSets", "(", "self", ",", "minutesAgo", ")", ":", "params", "=", "{", "'apiKey'", ":", "self", ".", "apiKey", ",", "'minutesAgo'", ":", "minutesAgo", "}", "url", "=", "Client", ".", "ENDPOINT", ".", "format", "(", "'getRecentlyUpdatedSets'", ")", "returned", "=", "get", "(", "url", ",", "params", "=", "params", ")", "self", ".", "checkResponse", "(", "returned", ")", "# Parse them in to build objects", "root", "=", "ET", ".", "fromstring", "(", "returned", ".", "text", ")", "return", "[", "Build", "(", "i", ",", "self", ")", "for", "i", "in", "root", "]" ]
Gets the information of recently updated sets. :param int minutesAgo: The amount of time ago that the set was updated. :returns: A list of Build instances that were updated within the given time. :rtype: list .. warning:: An empty list will be returned if there are no sets in the given time limit.
[ "Gets", "the", "information", "of", "recently", "updated", "sets", "." ]
9545f2183249862b077677d48fcfb9b4bfe1f87d
https://github.com/4Kaylum/Brickfront/blob/9545f2183249862b077677d48fcfb9b4bfe1f87d/brickfront/client.py#L174-L194
245,770
4Kaylum/Brickfront
brickfront/client.py
Client.getAdditionalImages
def getAdditionalImages(self, setID): ''' Gets a list of URLs containing images of the set. :param str setID: The ID of the set you want to grab the images for. :returns: A list of URL strings. :rtype: list .. warning:: An empty list will be returned if there are no additional images, or if the set ID is invalid. ''' params = { 'apiKey': self.apiKey, 'setID': setID } url = Client.ENDPOINT.format('getAdditionalImages') returned = get(url, params=params) self.checkResponse(returned) # I really fuckin hate XML root = ET.fromstring(returned.text) urlList = [] for imageHolder in root: urlList.append(imageHolder[-1].text) return urlList
python
def getAdditionalImages(self, setID): ''' Gets a list of URLs containing images of the set. :param str setID: The ID of the set you want to grab the images for. :returns: A list of URL strings. :rtype: list .. warning:: An empty list will be returned if there are no additional images, or if the set ID is invalid. ''' params = { 'apiKey': self.apiKey, 'setID': setID } url = Client.ENDPOINT.format('getAdditionalImages') returned = get(url, params=params) self.checkResponse(returned) # I really fuckin hate XML root = ET.fromstring(returned.text) urlList = [] for imageHolder in root: urlList.append(imageHolder[-1].text) return urlList
[ "def", "getAdditionalImages", "(", "self", ",", "setID", ")", ":", "params", "=", "{", "'apiKey'", ":", "self", ".", "apiKey", ",", "'setID'", ":", "setID", "}", "url", "=", "Client", ".", "ENDPOINT", ".", "format", "(", "'getAdditionalImages'", ")", "returned", "=", "get", "(", "url", ",", "params", "=", "params", ")", "self", ".", "checkResponse", "(", "returned", ")", "# I really fuckin hate XML", "root", "=", "ET", ".", "fromstring", "(", "returned", ".", "text", ")", "urlList", "=", "[", "]", "for", "imageHolder", "in", "root", ":", "urlList", ".", "append", "(", "imageHolder", "[", "-", "1", "]", ".", "text", ")", "return", "urlList" ]
Gets a list of URLs containing images of the set. :param str setID: The ID of the set you want to grab the images for. :returns: A list of URL strings. :rtype: list .. warning:: An empty list will be returned if there are no additional images, or if the set ID is invalid.
[ "Gets", "a", "list", "of", "URLs", "containing", "images", "of", "the", "set", "." ]
9545f2183249862b077677d48fcfb9b4bfe1f87d
https://github.com/4Kaylum/Brickfront/blob/9545f2183249862b077677d48fcfb9b4bfe1f87d/brickfront/client.py#L197-L221
245,771
4Kaylum/Brickfront
brickfront/client.py
Client.getReviews
def getReviews(self, setID): ''' Get the reviews for a set. :param str setID: The ID of the set you want to get the reviews of. :returns: A list of reviews. :rtype: List[:class:`brickfront.review.Review`] .. warning:: An empty list will be returned if there are no reviews, or if the set ID is invalid. ''' params = { 'apiKey': self.apiKey, 'setID': setID } url = Client.ENDPOINT.format('getReviews') returned = get(url, params=params) self.checkResponse(returned) # Parse into review objects root = ET.fromstring(returned.text) return [Review(i) for i in root]
python
def getReviews(self, setID): ''' Get the reviews for a set. :param str setID: The ID of the set you want to get the reviews of. :returns: A list of reviews. :rtype: List[:class:`brickfront.review.Review`] .. warning:: An empty list will be returned if there are no reviews, or if the set ID is invalid. ''' params = { 'apiKey': self.apiKey, 'setID': setID } url = Client.ENDPOINT.format('getReviews') returned = get(url, params=params) self.checkResponse(returned) # Parse into review objects root = ET.fromstring(returned.text) return [Review(i) for i in root]
[ "def", "getReviews", "(", "self", ",", "setID", ")", ":", "params", "=", "{", "'apiKey'", ":", "self", ".", "apiKey", ",", "'setID'", ":", "setID", "}", "url", "=", "Client", ".", "ENDPOINT", ".", "format", "(", "'getReviews'", ")", "returned", "=", "get", "(", "url", ",", "params", "=", "params", ")", "self", ".", "checkResponse", "(", "returned", ")", "# Parse into review objects", "root", "=", "ET", ".", "fromstring", "(", "returned", ".", "text", ")", "return", "[", "Review", "(", "i", ")", "for", "i", "in", "root", "]" ]
Get the reviews for a set. :param str setID: The ID of the set you want to get the reviews of. :returns: A list of reviews. :rtype: List[:class:`brickfront.review.Review`] .. warning:: An empty list will be returned if there are no reviews, or if the set ID is invalid.
[ "Get", "the", "reviews", "for", "a", "set", "." ]
9545f2183249862b077677d48fcfb9b4bfe1f87d
https://github.com/4Kaylum/Brickfront/blob/9545f2183249862b077677d48fcfb9b4bfe1f87d/brickfront/client.py#L224-L244
245,772
arteymix/benchpy
benchpy/__init__.py
benchmarked.results
def results(cls, function, group=None): """ Returns a numpy nparray representing the benchmark results of a function in a group. """ return numpy.array(cls._results[group][function])
python
def results(cls, function, group=None): """ Returns a numpy nparray representing the benchmark results of a function in a group. """ return numpy.array(cls._results[group][function])
[ "def", "results", "(", "cls", ",", "function", ",", "group", "=", "None", ")", ":", "return", "numpy", ".", "array", "(", "cls", ".", "_results", "[", "group", "]", "[", "function", "]", ")" ]
Returns a numpy nparray representing the benchmark results of a function in a group.
[ "Returns", "a", "numpy", "nparray", "representing", "the", "benchmark", "results", "of", "a", "function", "in", "a", "group", "." ]
3b5d949ec2e71541997923b1c7fcc67b634a9264
https://github.com/arteymix/benchpy/blob/3b5d949ec2e71541997923b1c7fcc67b634a9264/benchpy/__init__.py#L38-L43
245,773
b3j0f/annotation
b3j0f/annotation/oop.py
Mixin.mixin_class
def mixin_class(target, cls): """Mix cls content in target.""" for name, field in getmembers(cls): Mixin.mixin(target, field, name)
python
def mixin_class(target, cls): """Mix cls content in target.""" for name, field in getmembers(cls): Mixin.mixin(target, field, name)
[ "def", "mixin_class", "(", "target", ",", "cls", ")", ":", "for", "name", ",", "field", "in", "getmembers", "(", "cls", ")", ":", "Mixin", ".", "mixin", "(", "target", ",", "field", ",", "name", ")" ]
Mix cls content in target.
[ "Mix", "cls", "content", "in", "target", "." ]
738035a974e4092696d9dc1bbd149faa21c8c51f
https://github.com/b3j0f/annotation/blob/738035a974e4092696d9dc1bbd149faa21c8c51f/b3j0f/annotation/oop.py#L144-L148
245,774
b3j0f/annotation
b3j0f/annotation/oop.py
Mixin.mixin_function_or_method
def mixin_function_or_method(target, routine, name=None, isbound=False): """Mixin a routine into the target. :param routine: routine to mix in target. :param str name: mixin name. Routine name by default. :param bool isbound: If True (False by default), the mixin result is a bound method to target. """ function = None if isfunction(routine): function = routine elif ismethod(routine): function = get_method_function(routine) else: raise Mixin.MixInError( "{0} must be a function or a method.".format(routine)) if name is None: name = routine.__name__ if not isclass(target) or isbound: _type = type(target) method_args = [function, target] if PY2: method_args += _type result = MethodType(*method_args) else: if PY2: result = MethodType(function, None, target) else: result = function Mixin.set_mixin(target, result, name) return result
python
def mixin_function_or_method(target, routine, name=None, isbound=False): """Mixin a routine into the target. :param routine: routine to mix in target. :param str name: mixin name. Routine name by default. :param bool isbound: If True (False by default), the mixin result is a bound method to target. """ function = None if isfunction(routine): function = routine elif ismethod(routine): function = get_method_function(routine) else: raise Mixin.MixInError( "{0} must be a function or a method.".format(routine)) if name is None: name = routine.__name__ if not isclass(target) or isbound: _type = type(target) method_args = [function, target] if PY2: method_args += _type result = MethodType(*method_args) else: if PY2: result = MethodType(function, None, target) else: result = function Mixin.set_mixin(target, result, name) return result
[ "def", "mixin_function_or_method", "(", "target", ",", "routine", ",", "name", "=", "None", ",", "isbound", "=", "False", ")", ":", "function", "=", "None", "if", "isfunction", "(", "routine", ")", ":", "function", "=", "routine", "elif", "ismethod", "(", "routine", ")", ":", "function", "=", "get_method_function", "(", "routine", ")", "else", ":", "raise", "Mixin", ".", "MixInError", "(", "\"{0} must be a function or a method.\"", ".", "format", "(", "routine", ")", ")", "if", "name", "is", "None", ":", "name", "=", "routine", ".", "__name__", "if", "not", "isclass", "(", "target", ")", "or", "isbound", ":", "_type", "=", "type", "(", "target", ")", "method_args", "=", "[", "function", ",", "target", "]", "if", "PY2", ":", "method_args", "+=", "_type", "result", "=", "MethodType", "(", "*", "method_args", ")", "else", ":", "if", "PY2", ":", "result", "=", "MethodType", "(", "function", ",", "None", ",", "target", ")", "else", ":", "result", "=", "function", "Mixin", ".", "set_mixin", "(", "target", ",", "result", ",", "name", ")", "return", "result" ]
Mixin a routine into the target. :param routine: routine to mix in target. :param str name: mixin name. Routine name by default. :param bool isbound: If True (False by default), the mixin result is a bound method to target.
[ "Mixin", "a", "routine", "into", "the", "target", "." ]
738035a974e4092696d9dc1bbd149faa21c8c51f
https://github.com/b3j0f/annotation/blob/738035a974e4092696d9dc1bbd149faa21c8c51f/b3j0f/annotation/oop.py#L151-L194
245,775
b3j0f/annotation
b3j0f/annotation/oop.py
Mixin.mixin
def mixin(target, resource, name=None): """Do the correct mixin depending on the type of input resource. - Method or Function: mixin_function_or_method. - class: mixin_class. - other: set_mixin. And returns the result of the choosen method (one or a list of mixins). """ result = None if ismethod(resource) or isfunction(resource): result = Mixin.mixin_function_or_method(target, resource, name) elif isclass(resource): result = list() for name, content in getmembers(resource): if isclass(content): mixin = Mixin.set_mixin(target, content, name) else: mixin = Mixin.mixin(target, content, name) result.append(mixin) else: result = Mixin.set_mixin(target, resource, name) return result
python
def mixin(target, resource, name=None): """Do the correct mixin depending on the type of input resource. - Method or Function: mixin_function_or_method. - class: mixin_class. - other: set_mixin. And returns the result of the choosen method (one or a list of mixins). """ result = None if ismethod(resource) or isfunction(resource): result = Mixin.mixin_function_or_method(target, resource, name) elif isclass(resource): result = list() for name, content in getmembers(resource): if isclass(content): mixin = Mixin.set_mixin(target, content, name) else: mixin = Mixin.mixin(target, content, name) result.append(mixin) else: result = Mixin.set_mixin(target, resource, name) return result
[ "def", "mixin", "(", "target", ",", "resource", ",", "name", "=", "None", ")", ":", "result", "=", "None", "if", "ismethod", "(", "resource", ")", "or", "isfunction", "(", "resource", ")", ":", "result", "=", "Mixin", ".", "mixin_function_or_method", "(", "target", ",", "resource", ",", "name", ")", "elif", "isclass", "(", "resource", ")", ":", "result", "=", "list", "(", ")", "for", "name", ",", "content", "in", "getmembers", "(", "resource", ")", ":", "if", "isclass", "(", "content", ")", ":", "mixin", "=", "Mixin", ".", "set_mixin", "(", "target", ",", "content", ",", "name", ")", "else", ":", "mixin", "=", "Mixin", ".", "mixin", "(", "target", ",", "content", ",", "name", ")", "result", ".", "append", "(", "mixin", ")", "else", ":", "result", "=", "Mixin", ".", "set_mixin", "(", "target", ",", "resource", ",", "name", ")", "return", "result" ]
Do the correct mixin depending on the type of input resource. - Method or Function: mixin_function_or_method. - class: mixin_class. - other: set_mixin. And returns the result of the choosen method (one or a list of mixins).
[ "Do", "the", "correct", "mixin", "depending", "on", "the", "type", "of", "input", "resource", "." ]
738035a974e4092696d9dc1bbd149faa21c8c51f
https://github.com/b3j0f/annotation/blob/738035a974e4092696d9dc1bbd149faa21c8c51f/b3j0f/annotation/oop.py#L197-L227
245,776
b3j0f/annotation
b3j0f/annotation/oop.py
Mixin.remove_mixins
def remove_mixins(target): """Tries to get back target in a no mixin consistent state. """ mixedins_by_name = Mixin.get_mixedins_by_name(target).copy() for _name in mixedins_by_name: # for all named mixins while True: # remove all mixins named _name try: Mixin.remove_mixin(target, _name) except Mixin.MixInError: break
python
def remove_mixins(target): """Tries to get back target in a no mixin consistent state. """ mixedins_by_name = Mixin.get_mixedins_by_name(target).copy() for _name in mixedins_by_name: # for all named mixins while True: # remove all mixins named _name try: Mixin.remove_mixin(target, _name) except Mixin.MixInError: break
[ "def", "remove_mixins", "(", "target", ")", ":", "mixedins_by_name", "=", "Mixin", ".", "get_mixedins_by_name", "(", "target", ")", ".", "copy", "(", ")", "for", "_name", "in", "mixedins_by_name", ":", "# for all named mixins", "while", "True", ":", "# remove all mixins named _name", "try", ":", "Mixin", ".", "remove_mixin", "(", "target", ",", "_name", ")", "except", "Mixin", ".", "MixInError", ":", "break" ]
Tries to get back target in a no mixin consistent state.
[ "Tries", "to", "get", "back", "target", "in", "a", "no", "mixin", "consistent", "state", "." ]
738035a974e4092696d9dc1bbd149faa21c8c51f
https://github.com/b3j0f/annotation/blob/738035a974e4092696d9dc1bbd149faa21c8c51f/b3j0f/annotation/oop.py#L363-L374
245,777
edeposit/edeposit.amqp.storage
bin/edeposit_storage_server.py
error403
def error403(error): """ Custom 403 page. """ tb = error.traceback if isinstance(tb, dict) and "name" in tb and "uuid" in tb: return SimpleTemplate(PRIVATE_ACCESS_MSG).render( name=error.traceback["name"], uuid=error.traceback["uuid"] ) return "Access denied!"
python
def error403(error): """ Custom 403 page. """ tb = error.traceback if isinstance(tb, dict) and "name" in tb and "uuid" in tb: return SimpleTemplate(PRIVATE_ACCESS_MSG).render( name=error.traceback["name"], uuid=error.traceback["uuid"] ) return "Access denied!"
[ "def", "error403", "(", "error", ")", ":", "tb", "=", "error", ".", "traceback", "if", "isinstance", "(", "tb", ",", "dict", ")", "and", "\"name\"", "in", "tb", "and", "\"uuid\"", "in", "tb", ":", "return", "SimpleTemplate", "(", "PRIVATE_ACCESS_MSG", ")", ".", "render", "(", "name", "=", "error", ".", "traceback", "[", "\"name\"", "]", ",", "uuid", "=", "error", ".", "traceback", "[", "\"uuid\"", "]", ")", "return", "\"Access denied!\"" ]
Custom 403 page.
[ "Custom", "403", "page", "." ]
fb6bd326249847de04b17b64e856c878665cea92
https://github.com/edeposit/edeposit.amqp.storage/blob/fb6bd326249847de04b17b64e856c878665cea92/bin/edeposit_storage_server.py#L251-L263
245,778
edeposit/edeposit.amqp.storage
bin/edeposit_storage_server.py
render_trees
def render_trees(trees, path_composer): """ Render list of `trees` to HTML. Args: trees (list): List of :class:`.Tree`. path_composer (fn reference): Function used to compose paths from UUID. Look at :func:`.compose_tree_path` from :mod:`.web_tools`. Returns: str: HTML representation of trees. """ trees = list(trees) # by default, this is set def create_pub_cache(trees): """ Create uuid -> DBPublication cache from all uuid's linked from `trees`. Args: trees (list): List of :class:`.Tree`. Returns: dict: {uuid: DBPublication} """ sub_pubs_uuids = sum((x.collect_publications() for x in trees), []) uuid_mapping = { uuid: search_pubs_by_uuid(uuid) for uuid in set(sub_pubs_uuids) } # cleaned dict without blank matches return { uuid: pub[0] for uuid, pub in uuid_mapping.iteritems() if pub } # create uuid -> DBPublication cache pub_cache = create_pub_cache(trees) def render_tree(tree, ind=1): """ Render the tree into HTML using :attr:`TREE_TEMPLATE`. Private trees are ignored. Args: tree (obj): :class:`.Tree` instance. ind (int, default 1): Indentation. This function is called recursively. Returns: str: Rendered string. """ if not tree.is_public: return "" rendered_tree = SimpleTemplate(TREE_TEMPLATE).render( tree=tree, render_tree=render_tree, ind=ind, path_composer=path_composer, pub_cache=pub_cache, ) # keep nice indentation ind_txt = ind * " " return ind_txt + ("\n" + ind_txt).join(rendered_tree.splitlines()) # this is used to get reference for back button parent = tree_handler().get_parent(trees[0]) link_up = path_composer(parent) if parent else None return SimpleTemplate(TREES_TEMPLATE).render( trees=trees, render_tree=render_tree, link_up=link_up, )
python
def render_trees(trees, path_composer): """ Render list of `trees` to HTML. Args: trees (list): List of :class:`.Tree`. path_composer (fn reference): Function used to compose paths from UUID. Look at :func:`.compose_tree_path` from :mod:`.web_tools`. Returns: str: HTML representation of trees. """ trees = list(trees) # by default, this is set def create_pub_cache(trees): """ Create uuid -> DBPublication cache from all uuid's linked from `trees`. Args: trees (list): List of :class:`.Tree`. Returns: dict: {uuid: DBPublication} """ sub_pubs_uuids = sum((x.collect_publications() for x in trees), []) uuid_mapping = { uuid: search_pubs_by_uuid(uuid) for uuid in set(sub_pubs_uuids) } # cleaned dict without blank matches return { uuid: pub[0] for uuid, pub in uuid_mapping.iteritems() if pub } # create uuid -> DBPublication cache pub_cache = create_pub_cache(trees) def render_tree(tree, ind=1): """ Render the tree into HTML using :attr:`TREE_TEMPLATE`. Private trees are ignored. Args: tree (obj): :class:`.Tree` instance. ind (int, default 1): Indentation. This function is called recursively. Returns: str: Rendered string. """ if not tree.is_public: return "" rendered_tree = SimpleTemplate(TREE_TEMPLATE).render( tree=tree, render_tree=render_tree, ind=ind, path_composer=path_composer, pub_cache=pub_cache, ) # keep nice indentation ind_txt = ind * " " return ind_txt + ("\n" + ind_txt).join(rendered_tree.splitlines()) # this is used to get reference for back button parent = tree_handler().get_parent(trees[0]) link_up = path_composer(parent) if parent else None return SimpleTemplate(TREES_TEMPLATE).render( trees=trees, render_tree=render_tree, link_up=link_up, )
[ "def", "render_trees", "(", "trees", ",", "path_composer", ")", ":", "trees", "=", "list", "(", "trees", ")", "# by default, this is set", "def", "create_pub_cache", "(", "trees", ")", ":", "\"\"\"\n Create uuid -> DBPublication cache from all uuid's linked from `trees`.\n\n Args:\n trees (list): List of :class:`.Tree`.\n\n Returns:\n dict: {uuid: DBPublication}\n \"\"\"", "sub_pubs_uuids", "=", "sum", "(", "(", "x", ".", "collect_publications", "(", ")", "for", "x", "in", "trees", ")", ",", "[", "]", ")", "uuid_mapping", "=", "{", "uuid", ":", "search_pubs_by_uuid", "(", "uuid", ")", "for", "uuid", "in", "set", "(", "sub_pubs_uuids", ")", "}", "# cleaned dict without blank matches", "return", "{", "uuid", ":", "pub", "[", "0", "]", "for", "uuid", ",", "pub", "in", "uuid_mapping", ".", "iteritems", "(", ")", "if", "pub", "}", "# create uuid -> DBPublication cache", "pub_cache", "=", "create_pub_cache", "(", "trees", ")", "def", "render_tree", "(", "tree", ",", "ind", "=", "1", ")", ":", "\"\"\"\n Render the tree into HTML using :attr:`TREE_TEMPLATE`. Private trees\n are ignored.\n\n Args:\n tree (obj): :class:`.Tree` instance.\n ind (int, default 1): Indentation. This function is called\n recursively.\n\n Returns:\n str: Rendered string.\n \"\"\"", "if", "not", "tree", ".", "is_public", ":", "return", "\"\"", "rendered_tree", "=", "SimpleTemplate", "(", "TREE_TEMPLATE", ")", ".", "render", "(", "tree", "=", "tree", ",", "render_tree", "=", "render_tree", ",", "ind", "=", "ind", ",", "path_composer", "=", "path_composer", ",", "pub_cache", "=", "pub_cache", ",", ")", "# keep nice indentation", "ind_txt", "=", "ind", "*", "\" \"", "return", "ind_txt", "+", "(", "\"\\n\"", "+", "ind_txt", ")", ".", "join", "(", "rendered_tree", ".", "splitlines", "(", ")", ")", "# this is used to get reference for back button", "parent", "=", "tree_handler", "(", ")", ".", "get_parent", "(", "trees", "[", "0", "]", ")", "link_up", "=", "path_composer", "(", "parent", ")", "if", "parent", "else", "None", "return", "SimpleTemplate", "(", "TREES_TEMPLATE", ")", ".", "render", "(", "trees", "=", "trees", ",", "render_tree", "=", "render_tree", ",", "link_up", "=", "link_up", ",", ")" ]
Render list of `trees` to HTML. Args: trees (list): List of :class:`.Tree`. path_composer (fn reference): Function used to compose paths from UUID. Look at :func:`.compose_tree_path` from :mod:`.web_tools`. Returns: str: HTML representation of trees.
[ "Render", "list", "of", "trees", "to", "HTML", "." ]
fb6bd326249847de04b17b64e856c878665cea92
https://github.com/edeposit/edeposit.amqp.storage/blob/fb6bd326249847de04b17b64e856c878665cea92/bin/edeposit_storage_server.py#L327-L404
245,779
edeposit/edeposit.amqp.storage
bin/edeposit_storage_server.py
list_publications
def list_publications(): """ Return list of all publications in basic graphic HTML render. """ publications = search_publications( DBPublication(is_public=True) ) return SimpleTemplate(INDEX_TEMPLATE).render( publications=publications, compose_path=web_tools.compose_path, delimiter=":", )
python
def list_publications(): """ Return list of all publications in basic graphic HTML render. """ publications = search_publications( DBPublication(is_public=True) ) return SimpleTemplate(INDEX_TEMPLATE).render( publications=publications, compose_path=web_tools.compose_path, delimiter=":", )
[ "def", "list_publications", "(", ")", ":", "publications", "=", "search_publications", "(", "DBPublication", "(", "is_public", "=", "True", ")", ")", "return", "SimpleTemplate", "(", "INDEX_TEMPLATE", ")", ".", "render", "(", "publications", "=", "publications", ",", "compose_path", "=", "web_tools", ".", "compose_path", ",", "delimiter", "=", "\":\"", ",", ")" ]
Return list of all publications in basic graphic HTML render.
[ "Return", "list", "of", "all", "publications", "in", "basic", "graphic", "HTML", "render", "." ]
fb6bd326249847de04b17b64e856c878665cea92
https://github.com/edeposit/edeposit.amqp.storage/blob/fb6bd326249847de04b17b64e856c878665cea92/bin/edeposit_storage_server.py#L441-L453
245,780
roaet/eh
eh/mdv/markdownviewer.py
set_theme
def set_theme(theme=None, for_code=None): """ set md and code theme """ try: if theme == 'default': return theme = theme or os.environ.get('AXC_THEME', 'random') # all the themes from here: themes = read_themes() if theme == 'random': rand = randint(0, len(themes)-1) theme = themes.keys()[rand] t = themes.get(theme) if not t or len(t.get('ct')) != 5: # leave defaults: return _for = '' if for_code: _for = ' (code)' if is_app: print >> sys.stderr, low('theme%s: %s (%s)' % (_for, theme, t.get('name'))) t = t['ct'] cols = (t[0], t[1], t[2], t[3], t[4]) if for_code: global CH1, CH2, CH3, CH4, CH5 CH1, CH2, CH3, CH4, CH5 = cols else: global H1, H2, H3, H4, H5 # set the colors now from the ansi codes in the theme: H1, H2, H3, H4, H5 = cols finally: if for_code: build_hl_by_token()
python
def set_theme(theme=None, for_code=None): """ set md and code theme """ try: if theme == 'default': return theme = theme or os.environ.get('AXC_THEME', 'random') # all the themes from here: themes = read_themes() if theme == 'random': rand = randint(0, len(themes)-1) theme = themes.keys()[rand] t = themes.get(theme) if not t or len(t.get('ct')) != 5: # leave defaults: return _for = '' if for_code: _for = ' (code)' if is_app: print >> sys.stderr, low('theme%s: %s (%s)' % (_for, theme, t.get('name'))) t = t['ct'] cols = (t[0], t[1], t[2], t[3], t[4]) if for_code: global CH1, CH2, CH3, CH4, CH5 CH1, CH2, CH3, CH4, CH5 = cols else: global H1, H2, H3, H4, H5 # set the colors now from the ansi codes in the theme: H1, H2, H3, H4, H5 = cols finally: if for_code: build_hl_by_token()
[ "def", "set_theme", "(", "theme", "=", "None", ",", "for_code", "=", "None", ")", ":", "try", ":", "if", "theme", "==", "'default'", ":", "return", "theme", "=", "theme", "or", "os", ".", "environ", ".", "get", "(", "'AXC_THEME'", ",", "'random'", ")", "# all the themes from here:", "themes", "=", "read_themes", "(", ")", "if", "theme", "==", "'random'", ":", "rand", "=", "randint", "(", "0", ",", "len", "(", "themes", ")", "-", "1", ")", "theme", "=", "themes", ".", "keys", "(", ")", "[", "rand", "]", "t", "=", "themes", ".", "get", "(", "theme", ")", "if", "not", "t", "or", "len", "(", "t", ".", "get", "(", "'ct'", ")", ")", "!=", "5", ":", "# leave defaults:", "return", "_for", "=", "''", "if", "for_code", ":", "_for", "=", "' (code)'", "if", "is_app", ":", "print", ">>", "sys", ".", "stderr", ",", "low", "(", "'theme%s: %s (%s)'", "%", "(", "_for", ",", "theme", ",", "t", ".", "get", "(", "'name'", ")", ")", ")", "t", "=", "t", "[", "'ct'", "]", "cols", "=", "(", "t", "[", "0", "]", ",", "t", "[", "1", "]", ",", "t", "[", "2", "]", ",", "t", "[", "3", "]", ",", "t", "[", "4", "]", ")", "if", "for_code", ":", "global", "CH1", ",", "CH2", ",", "CH3", ",", "CH4", ",", "CH5", "CH1", ",", "CH2", ",", "CH3", ",", "CH4", ",", "CH5", "=", "cols", "else", ":", "global", "H1", ",", "H2", ",", "H3", ",", "H4", ",", "H5", "# set the colors now from the ansi codes in the theme:", "H1", ",", "H2", ",", "H3", ",", "H4", ",", "H5", "=", "cols", "finally", ":", "if", "for_code", ":", "build_hl_by_token", "(", ")" ]
set md and code theme
[ "set", "md", "and", "code", "theme" ]
9370864a9f1d65bb0f822d0aea83f1169c98f3bd
https://github.com/roaet/eh/blob/9370864a9f1d65bb0f822d0aea83f1169c98f3bd/eh/mdv/markdownviewer.py#L236-L268
245,781
roaet/eh
eh/mdv/markdownviewer.py
style_ansi
def style_ansi(raw_code, lang=None): """ actual code hilite """ lexer = 0 if lang: try: lexer = get_lexer_by_name(lang) except ValueError: print col(R, 'Lexer for %s not found' % lang) lexer = None if not lexer: try: if guess_lexer: lexer = pyg_guess_lexer(raw_code) except: pass if not lexer: lexer = get_lexer_by_name(def_lexer) tokens = lex(raw_code, lexer) cod = [] for t, v in tokens: if not v: continue _col = code_hl_tokens.get(t) if _col: cod.append(col(v, _col)) else: cod.append(v) return ''.join(cod)
python
def style_ansi(raw_code, lang=None): """ actual code hilite """ lexer = 0 if lang: try: lexer = get_lexer_by_name(lang) except ValueError: print col(R, 'Lexer for %s not found' % lang) lexer = None if not lexer: try: if guess_lexer: lexer = pyg_guess_lexer(raw_code) except: pass if not lexer: lexer = get_lexer_by_name(def_lexer) tokens = lex(raw_code, lexer) cod = [] for t, v in tokens: if not v: continue _col = code_hl_tokens.get(t) if _col: cod.append(col(v, _col)) else: cod.append(v) return ''.join(cod)
[ "def", "style_ansi", "(", "raw_code", ",", "lang", "=", "None", ")", ":", "lexer", "=", "0", "if", "lang", ":", "try", ":", "lexer", "=", "get_lexer_by_name", "(", "lang", ")", "except", "ValueError", ":", "print", "col", "(", "R", ",", "'Lexer for %s not found'", "%", "lang", ")", "lexer", "=", "None", "if", "not", "lexer", ":", "try", ":", "if", "guess_lexer", ":", "lexer", "=", "pyg_guess_lexer", "(", "raw_code", ")", "except", ":", "pass", "if", "not", "lexer", ":", "lexer", "=", "get_lexer_by_name", "(", "def_lexer", ")", "tokens", "=", "lex", "(", "raw_code", ",", "lexer", ")", "cod", "=", "[", "]", "for", "t", ",", "v", "in", "tokens", ":", "if", "not", "v", ":", "continue", "_col", "=", "code_hl_tokens", ".", "get", "(", "t", ")", "if", "_col", ":", "cod", ".", "append", "(", "col", "(", "v", ",", "_col", ")", ")", "else", ":", "cod", ".", "append", "(", "v", ")", "return", "''", ".", "join", "(", "cod", ")" ]
actual code hilite
[ "actual", "code", "hilite" ]
9370864a9f1d65bb0f822d0aea83f1169c98f3bd
https://github.com/roaet/eh/blob/9370864a9f1d65bb0f822d0aea83f1169c98f3bd/eh/mdv/markdownviewer.py#L271-L298
245,782
roaet/eh
eh/mdv/markdownviewer.py
rewrap
def rewrap(el, t, ind, pref): """ Reasonably smart rewrapping checking punctuations """ global term_columns cols = term_columns - len(ind + pref) if el.tag == 'code' or len(t) <= cols: return t # wrapping: # we want to keep existing linebreaks after punctuation # marks. the others we rewrap: puncs = ',', '.', '?', '!', '-', ':' parts = [] origp = t.splitlines() if len(origp) > 1: pos = -1 while pos < len(origp) - 1: pos += 1 # last char punctuation? if origp[pos][-1] not in puncs and \ not pos == len(origp) -1: # concat: parts.append(origp[pos].strip() + ' ' + \ origp[pos+1].strip()) pos += 1 else: parts.append(origp[pos].strip()) t = '\n'.join(parts) # having only the linebreaks with puncs before we rewrap # now: parts = [] for part in t.splitlines(): parts.extend([part[i:i+cols] \ for i in range(0, len(part), cols)]) # last remove leading ' ' (if '\n' came just before): t = [] for p in parts: t.append(p.strip()) return '\n'.join(t)
python
def rewrap(el, t, ind, pref): """ Reasonably smart rewrapping checking punctuations """ global term_columns cols = term_columns - len(ind + pref) if el.tag == 'code' or len(t) <= cols: return t # wrapping: # we want to keep existing linebreaks after punctuation # marks. the others we rewrap: puncs = ',', '.', '?', '!', '-', ':' parts = [] origp = t.splitlines() if len(origp) > 1: pos = -1 while pos < len(origp) - 1: pos += 1 # last char punctuation? if origp[pos][-1] not in puncs and \ not pos == len(origp) -1: # concat: parts.append(origp[pos].strip() + ' ' + \ origp[pos+1].strip()) pos += 1 else: parts.append(origp[pos].strip()) t = '\n'.join(parts) # having only the linebreaks with puncs before we rewrap # now: parts = [] for part in t.splitlines(): parts.extend([part[i:i+cols] \ for i in range(0, len(part), cols)]) # last remove leading ' ' (if '\n' came just before): t = [] for p in parts: t.append(p.strip()) return '\n'.join(t)
[ "def", "rewrap", "(", "el", ",", "t", ",", "ind", ",", "pref", ")", ":", "global", "term_columns", "cols", "=", "term_columns", "-", "len", "(", "ind", "+", "pref", ")", "if", "el", ".", "tag", "==", "'code'", "or", "len", "(", "t", ")", "<=", "cols", ":", "return", "t", "# wrapping:", "# we want to keep existing linebreaks after punctuation", "# marks. the others we rewrap:", "puncs", "=", "','", ",", "'.'", ",", "'?'", ",", "'!'", ",", "'-'", ",", "':'", "parts", "=", "[", "]", "origp", "=", "t", ".", "splitlines", "(", ")", "if", "len", "(", "origp", ")", ">", "1", ":", "pos", "=", "-", "1", "while", "pos", "<", "len", "(", "origp", ")", "-", "1", ":", "pos", "+=", "1", "# last char punctuation?", "if", "origp", "[", "pos", "]", "[", "-", "1", "]", "not", "in", "puncs", "and", "not", "pos", "==", "len", "(", "origp", ")", "-", "1", ":", "# concat:", "parts", ".", "append", "(", "origp", "[", "pos", "]", ".", "strip", "(", ")", "+", "' '", "+", "origp", "[", "pos", "+", "1", "]", ".", "strip", "(", ")", ")", "pos", "+=", "1", "else", ":", "parts", ".", "append", "(", "origp", "[", "pos", "]", ".", "strip", "(", ")", ")", "t", "=", "'\\n'", ".", "join", "(", "parts", ")", "# having only the linebreaks with puncs before we rewrap", "# now:", "parts", "=", "[", "]", "for", "part", "in", "t", ".", "splitlines", "(", ")", ":", "parts", ".", "extend", "(", "[", "part", "[", "i", ":", "i", "+", "cols", "]", "for", "i", "in", "range", "(", "0", ",", "len", "(", "part", ")", ",", "cols", ")", "]", ")", "# last remove leading ' ' (if '\\n' came just before):", "t", "=", "[", "]", "for", "p", "in", "parts", ":", "t", ".", "append", "(", "p", ".", "strip", "(", ")", ")", "return", "'\\n'", ".", "join", "(", "t", ")" ]
Reasonably smart rewrapping checking punctuations
[ "Reasonably", "smart", "rewrapping", "checking", "punctuations" ]
9370864a9f1d65bb0f822d0aea83f1169c98f3bd
https://github.com/roaet/eh/blob/9370864a9f1d65bb0f822d0aea83f1169c98f3bd/eh/mdv/markdownviewer.py#L402-L439
245,783
roaet/eh
eh/mdv/markdownviewer.py
monitor
def monitor(args): """ file monitor mode """ filename = args.get('MDFILE') if not filename: print col('Need file argument', 2) raise SystemExit last_err = '' last_stat = 0 while True: if not os.path.exists(filename): last_err = 'File %s not found. Will continue trying.' % filename else: try: stat = os.stat(filename)[8] if stat != last_stat: parsed = run_args(args) print parsed last_stat = stat last_err = '' except Exception, ex: last_err = str(ex) if last_err: print 'Error: %s' % last_err sleep()
python
def monitor(args): """ file monitor mode """ filename = args.get('MDFILE') if not filename: print col('Need file argument', 2) raise SystemExit last_err = '' last_stat = 0 while True: if not os.path.exists(filename): last_err = 'File %s not found. Will continue trying.' % filename else: try: stat = os.stat(filename)[8] if stat != last_stat: parsed = run_args(args) print parsed last_stat = stat last_err = '' except Exception, ex: last_err = str(ex) if last_err: print 'Error: %s' % last_err sleep()
[ "def", "monitor", "(", "args", ")", ":", "filename", "=", "args", ".", "get", "(", "'MDFILE'", ")", "if", "not", "filename", ":", "print", "col", "(", "'Need file argument'", ",", "2", ")", "raise", "SystemExit", "last_err", "=", "''", "last_stat", "=", "0", "while", "True", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "filename", ")", ":", "last_err", "=", "'File %s not found. Will continue trying.'", "%", "filename", "else", ":", "try", ":", "stat", "=", "os", ".", "stat", "(", "filename", ")", "[", "8", "]", "if", "stat", "!=", "last_stat", ":", "parsed", "=", "run_args", "(", "args", ")", "print", "parsed", "last_stat", "=", "stat", "last_err", "=", "''", "except", "Exception", ",", "ex", ":", "last_err", "=", "str", "(", "ex", ")", "if", "last_err", ":", "print", "'Error: %s'", "%", "last_err", "sleep", "(", ")" ]
file monitor mode
[ "file", "monitor", "mode" ]
9370864a9f1d65bb0f822d0aea83f1169c98f3bd
https://github.com/roaet/eh/blob/9370864a9f1d65bb0f822d0aea83f1169c98f3bd/eh/mdv/markdownviewer.py#L849-L872
245,784
roaet/eh
eh/mdv/markdownviewer.py
run_changed_file_cmd
def run_changed_file_cmd(cmd, fp, pretty): """ running commands on changes. pretty the parsed file """ with open(fp) as f: raw = f.read() # go sure regarding quotes: for ph in (dir_mon_filepath_ph, dir_mon_content_raw, dir_mon_content_pretty): if ph in cmd and not ('"%s"' % ph) in cmd \ and not ("'%s'" % ph) in cmd: cmd = cmd.replace(ph, '"%s"' % ph) cmd = cmd.replace(dir_mon_filepath_ph, fp) print col('Running %s' % cmd, H1) for r, what in ((dir_mon_content_raw, raw), (dir_mon_content_pretty, pretty)): cmd = cmd.replace(r, what.encode('base64')) # yeah, i know, sub bla bla... if os.system(cmd): print col('(the command failed)', R)
python
def run_changed_file_cmd(cmd, fp, pretty): """ running commands on changes. pretty the parsed file """ with open(fp) as f: raw = f.read() # go sure regarding quotes: for ph in (dir_mon_filepath_ph, dir_mon_content_raw, dir_mon_content_pretty): if ph in cmd and not ('"%s"' % ph) in cmd \ and not ("'%s'" % ph) in cmd: cmd = cmd.replace(ph, '"%s"' % ph) cmd = cmd.replace(dir_mon_filepath_ph, fp) print col('Running %s' % cmd, H1) for r, what in ((dir_mon_content_raw, raw), (dir_mon_content_pretty, pretty)): cmd = cmd.replace(r, what.encode('base64')) # yeah, i know, sub bla bla... if os.system(cmd): print col('(the command failed)', R)
[ "def", "run_changed_file_cmd", "(", "cmd", ",", "fp", ",", "pretty", ")", ":", "with", "open", "(", "fp", ")", "as", "f", ":", "raw", "=", "f", ".", "read", "(", ")", "# go sure regarding quotes:", "for", "ph", "in", "(", "dir_mon_filepath_ph", ",", "dir_mon_content_raw", ",", "dir_mon_content_pretty", ")", ":", "if", "ph", "in", "cmd", "and", "not", "(", "'\"%s\"'", "%", "ph", ")", "in", "cmd", "and", "not", "(", "\"'%s'\"", "%", "ph", ")", "in", "cmd", ":", "cmd", "=", "cmd", ".", "replace", "(", "ph", ",", "'\"%s\"'", "%", "ph", ")", "cmd", "=", "cmd", ".", "replace", "(", "dir_mon_filepath_ph", ",", "fp", ")", "print", "col", "(", "'Running %s'", "%", "cmd", ",", "H1", ")", "for", "r", ",", "what", "in", "(", "(", "dir_mon_content_raw", ",", "raw", ")", ",", "(", "dir_mon_content_pretty", ",", "pretty", ")", ")", ":", "cmd", "=", "cmd", ".", "replace", "(", "r", ",", "what", ".", "encode", "(", "'base64'", ")", ")", "# yeah, i know, sub bla bla...", "if", "os", ".", "system", "(", "cmd", ")", ":", "print", "col", "(", "'(the command failed)'", ",", "R", ")" ]
running commands on changes. pretty the parsed file
[ "running", "commands", "on", "changes", ".", "pretty", "the", "parsed", "file" ]
9370864a9f1d65bb0f822d0aea83f1169c98f3bd
https://github.com/roaet/eh/blob/9370864a9f1d65bb0f822d0aea83f1169c98f3bd/eh/mdv/markdownviewer.py#L883-L904
245,785
roaet/eh
eh/mdv/markdownviewer.py
monitor_dir
def monitor_dir(args): """ displaying the changed files """ def show_fp(fp): args['MDFILE'] = fp pretty = run_args(args) print pretty print "(%s)" % col(fp, L) cmd = args.get('change_cmd') if cmd: run_changed_file_cmd(cmd, fp=fp, pretty=pretty) ftree = {} d = args.get('-M') # was a change command given? d += '::' d, args['change_cmd'] = d.split('::')[:2] args.pop('-M') # collides: args.pop('-m') d, exts = (d + ':md,mdown,markdown').split(':')[:2] exts = exts.split(',') if not os.path.exists(d): print col('Does not exist: %s' % d, R) sys.exit(2) dir_black_list = ['.', '..'] def check_dir(d, ftree): check_latest = ftree.get('latest_ts') d = os.path.abspath(d) if d in dir_black_list: return if len(ftree) > mon_max_files: # too deep: print col('Max files (%s) reached' % c(mon_max_files, R)) dir_black_list.append(d) return try: files = os.listdir(d) except Exception, ex: print '%s when scanning dir %s' % (col(ex, R), d) dir_black_list.append(d) return for f in files: fp = j(d, f) if os.path.isfile(fp): f_ext = f.rsplit('.', 1)[-1] if f_ext == f: f_ext == '' if not f_ext in exts: continue old = ftree.get(fp) # size: now = os.stat(fp)[6] if check_latest: if os.stat(fp)[7] > ftree['latest_ts']: ftree['latest'] = fp ftree['latest_ts'] = os.stat(fp)[8] if now == old: continue # change: ftree[fp] = now if not old: # At first time we don't display ALL the files...: continue # no binary. make sure: if 'text' in os.popen('file "%s"' % fp).read(): show_fp(fp) elif os.path.isdir(fp): check_dir(j(d, fp), ftree) ftree['latest_ts'] = 1 while True: check_dir(d, ftree) if 'latest_ts' in ftree: ftree.pop('latest_ts') fp = ftree.get('latest') if fp: show_fp(fp) else: print 'sth went wrong, no file found' sleep()
python
def monitor_dir(args): """ displaying the changed files """ def show_fp(fp): args['MDFILE'] = fp pretty = run_args(args) print pretty print "(%s)" % col(fp, L) cmd = args.get('change_cmd') if cmd: run_changed_file_cmd(cmd, fp=fp, pretty=pretty) ftree = {} d = args.get('-M') # was a change command given? d += '::' d, args['change_cmd'] = d.split('::')[:2] args.pop('-M') # collides: args.pop('-m') d, exts = (d + ':md,mdown,markdown').split(':')[:2] exts = exts.split(',') if not os.path.exists(d): print col('Does not exist: %s' % d, R) sys.exit(2) dir_black_list = ['.', '..'] def check_dir(d, ftree): check_latest = ftree.get('latest_ts') d = os.path.abspath(d) if d in dir_black_list: return if len(ftree) > mon_max_files: # too deep: print col('Max files (%s) reached' % c(mon_max_files, R)) dir_black_list.append(d) return try: files = os.listdir(d) except Exception, ex: print '%s when scanning dir %s' % (col(ex, R), d) dir_black_list.append(d) return for f in files: fp = j(d, f) if os.path.isfile(fp): f_ext = f.rsplit('.', 1)[-1] if f_ext == f: f_ext == '' if not f_ext in exts: continue old = ftree.get(fp) # size: now = os.stat(fp)[6] if check_latest: if os.stat(fp)[7] > ftree['latest_ts']: ftree['latest'] = fp ftree['latest_ts'] = os.stat(fp)[8] if now == old: continue # change: ftree[fp] = now if not old: # At first time we don't display ALL the files...: continue # no binary. make sure: if 'text' in os.popen('file "%s"' % fp).read(): show_fp(fp) elif os.path.isdir(fp): check_dir(j(d, fp), ftree) ftree['latest_ts'] = 1 while True: check_dir(d, ftree) if 'latest_ts' in ftree: ftree.pop('latest_ts') fp = ftree.get('latest') if fp: show_fp(fp) else: print 'sth went wrong, no file found' sleep()
[ "def", "monitor_dir", "(", "args", ")", ":", "def", "show_fp", "(", "fp", ")", ":", "args", "[", "'MDFILE'", "]", "=", "fp", "pretty", "=", "run_args", "(", "args", ")", "print", "pretty", "print", "\"(%s)\"", "%", "col", "(", "fp", ",", "L", ")", "cmd", "=", "args", ".", "get", "(", "'change_cmd'", ")", "if", "cmd", ":", "run_changed_file_cmd", "(", "cmd", ",", "fp", "=", "fp", ",", "pretty", "=", "pretty", ")", "ftree", "=", "{", "}", "d", "=", "args", ".", "get", "(", "'-M'", ")", "# was a change command given?", "d", "+=", "'::'", "d", ",", "args", "[", "'change_cmd'", "]", "=", "d", ".", "split", "(", "'::'", ")", "[", ":", "2", "]", "args", ".", "pop", "(", "'-M'", ")", "# collides:", "args", ".", "pop", "(", "'-m'", ")", "d", ",", "exts", "=", "(", "d", "+", "':md,mdown,markdown'", ")", ".", "split", "(", "':'", ")", "[", ":", "2", "]", "exts", "=", "exts", ".", "split", "(", "','", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "d", ")", ":", "print", "col", "(", "'Does not exist: %s'", "%", "d", ",", "R", ")", "sys", ".", "exit", "(", "2", ")", "dir_black_list", "=", "[", "'.'", ",", "'..'", "]", "def", "check_dir", "(", "d", ",", "ftree", ")", ":", "check_latest", "=", "ftree", ".", "get", "(", "'latest_ts'", ")", "d", "=", "os", ".", "path", ".", "abspath", "(", "d", ")", "if", "d", "in", "dir_black_list", ":", "return", "if", "len", "(", "ftree", ")", ">", "mon_max_files", ":", "# too deep:", "print", "col", "(", "'Max files (%s) reached'", "%", "c", "(", "mon_max_files", ",", "R", ")", ")", "dir_black_list", ".", "append", "(", "d", ")", "return", "try", ":", "files", "=", "os", ".", "listdir", "(", "d", ")", "except", "Exception", ",", "ex", ":", "print", "'%s when scanning dir %s'", "%", "(", "col", "(", "ex", ",", "R", ")", ",", "d", ")", "dir_black_list", ".", "append", "(", "d", ")", "return", "for", "f", "in", "files", ":", "fp", "=", "j", "(", "d", ",", "f", ")", "if", "os", ".", "path", ".", "isfile", "(", "fp", ")", ":", "f_ext", "=", "f", ".", "rsplit", "(", "'.'", ",", "1", ")", "[", "-", "1", "]", "if", "f_ext", "==", "f", ":", "f_ext", "==", "''", "if", "not", "f_ext", "in", "exts", ":", "continue", "old", "=", "ftree", ".", "get", "(", "fp", ")", "# size:", "now", "=", "os", ".", "stat", "(", "fp", ")", "[", "6", "]", "if", "check_latest", ":", "if", "os", ".", "stat", "(", "fp", ")", "[", "7", "]", ">", "ftree", "[", "'latest_ts'", "]", ":", "ftree", "[", "'latest'", "]", "=", "fp", "ftree", "[", "'latest_ts'", "]", "=", "os", ".", "stat", "(", "fp", ")", "[", "8", "]", "if", "now", "==", "old", ":", "continue", "# change:", "ftree", "[", "fp", "]", "=", "now", "if", "not", "old", ":", "# At first time we don't display ALL the files...:", "continue", "# no binary. make sure:", "if", "'text'", "in", "os", ".", "popen", "(", "'file \"%s\"'", "%", "fp", ")", ".", "read", "(", ")", ":", "show_fp", "(", "fp", ")", "elif", "os", ".", "path", ".", "isdir", "(", "fp", ")", ":", "check_dir", "(", "j", "(", "d", ",", "fp", ")", ",", "ftree", ")", "ftree", "[", "'latest_ts'", "]", "=", "1", "while", "True", ":", "check_dir", "(", "d", ",", "ftree", ")", "if", "'latest_ts'", "in", "ftree", ":", "ftree", ".", "pop", "(", "'latest_ts'", ")", "fp", "=", "ftree", ".", "get", "(", "'latest'", ")", "if", "fp", ":", "show_fp", "(", "fp", ")", "else", ":", "print", "'sth went wrong, no file found'", "sleep", "(", ")" ]
displaying the changed files
[ "displaying", "the", "changed", "files" ]
9370864a9f1d65bb0f822d0aea83f1169c98f3bd
https://github.com/roaet/eh/blob/9370864a9f1d65bb0f822d0aea83f1169c98f3bd/eh/mdv/markdownviewer.py#L907-L991
245,786
roaet/eh
eh/mdv/markdownviewer.py
run_args
def run_args(args): """ call the lib entry function with CLI args """ return main(filename = args.get('MDFILE') ,theme = args.get('-t', 'random') ,cols = args.get('-c') ,from_txt = args.get('-f') ,c_theme = args.get('-T') ,c_no_guess = args.get('-x') ,do_html = args.get('-H') ,no_colors = args.get('-A') ,display_links = args.get('-L'))
python
def run_args(args): """ call the lib entry function with CLI args """ return main(filename = args.get('MDFILE') ,theme = args.get('-t', 'random') ,cols = args.get('-c') ,from_txt = args.get('-f') ,c_theme = args.get('-T') ,c_no_guess = args.get('-x') ,do_html = args.get('-H') ,no_colors = args.get('-A') ,display_links = args.get('-L'))
[ "def", "run_args", "(", "args", ")", ":", "return", "main", "(", "filename", "=", "args", ".", "get", "(", "'MDFILE'", ")", ",", "theme", "=", "args", ".", "get", "(", "'-t'", ",", "'random'", ")", ",", "cols", "=", "args", ".", "get", "(", "'-c'", ")", ",", "from_txt", "=", "args", ".", "get", "(", "'-f'", ")", ",", "c_theme", "=", "args", ".", "get", "(", "'-T'", ")", ",", "c_no_guess", "=", "args", ".", "get", "(", "'-x'", ")", ",", "do_html", "=", "args", ".", "get", "(", "'-H'", ")", ",", "no_colors", "=", "args", ".", "get", "(", "'-A'", ")", ",", "display_links", "=", "args", ".", "get", "(", "'-L'", ")", ")" ]
call the lib entry function with CLI args
[ "call", "the", "lib", "entry", "function", "with", "CLI", "args" ]
9370864a9f1d65bb0f822d0aea83f1169c98f3bd
https://github.com/roaet/eh/blob/9370864a9f1d65bb0f822d0aea83f1169c98f3bd/eh/mdv/markdownviewer.py#L1011-L1021
245,787
roaet/eh
eh/mdv/markdownviewer.py
Tags.code
def code(_, s, from_fenced_block = None, **kw): """ md code AND ``` style fenced raw code ends here""" lang = kw.get('lang') raw_code = s if have_pygments: s = style_ansi(raw_code, lang=lang) # outest hir is 2, use it for fenced: ind = ' ' * kw.get('hir', 2) #if from_fenced_block: ... WE treat equal. # shift to the far left, no matter the indent (screenspace matters): firstl = s.split('\n')[0] del_spaces = ' ' * (len(firstl) - len(firstl.lstrip())) s = ('\n' + s).replace('\n%s' % del_spaces, '\n')[1:] # we want an indent of one and low vis prefix. this does it: code_lines = ('\n' + s).splitlines() prefix = ('\n%s%s %s' % (ind, low(code_pref), col('', C, no_reset=1))) code = prefix.join(code_lines) return code + '\n' + reset_col
python
def code(_, s, from_fenced_block = None, **kw): """ md code AND ``` style fenced raw code ends here""" lang = kw.get('lang') raw_code = s if have_pygments: s = style_ansi(raw_code, lang=lang) # outest hir is 2, use it for fenced: ind = ' ' * kw.get('hir', 2) #if from_fenced_block: ... WE treat equal. # shift to the far left, no matter the indent (screenspace matters): firstl = s.split('\n')[0] del_spaces = ' ' * (len(firstl) - len(firstl.lstrip())) s = ('\n' + s).replace('\n%s' % del_spaces, '\n')[1:] # we want an indent of one and low vis prefix. this does it: code_lines = ('\n' + s).splitlines() prefix = ('\n%s%s %s' % (ind, low(code_pref), col('', C, no_reset=1))) code = prefix.join(code_lines) return code + '\n' + reset_col
[ "def", "code", "(", "_", ",", "s", ",", "from_fenced_block", "=", "None", ",", "*", "*", "kw", ")", ":", "lang", "=", "kw", ".", "get", "(", "'lang'", ")", "raw_code", "=", "s", "if", "have_pygments", ":", "s", "=", "style_ansi", "(", "raw_code", ",", "lang", "=", "lang", ")", "# outest hir is 2, use it for fenced:", "ind", "=", "' '", "*", "kw", ".", "get", "(", "'hir'", ",", "2", ")", "#if from_fenced_block: ... WE treat equal.", "# shift to the far left, no matter the indent (screenspace matters):", "firstl", "=", "s", ".", "split", "(", "'\\n'", ")", "[", "0", "]", "del_spaces", "=", "' '", "*", "(", "len", "(", "firstl", ")", "-", "len", "(", "firstl", ".", "lstrip", "(", ")", ")", ")", "s", "=", "(", "'\\n'", "+", "s", ")", ".", "replace", "(", "'\\n%s'", "%", "del_spaces", ",", "'\\n'", ")", "[", "1", ":", "]", "# we want an indent of one and low vis prefix. this does it:", "code_lines", "=", "(", "'\\n'", "+", "s", ")", ".", "splitlines", "(", ")", "prefix", "=", "(", "'\\n%s%s %s'", "%", "(", "ind", ",", "low", "(", "code_pref", ")", ",", "col", "(", "''", ",", "C", ",", "no_reset", "=", "1", ")", ")", ")", "code", "=", "prefix", ".", "join", "(", "code_lines", ")", "return", "code", "+", "'\\n'", "+", "reset_col" ]
md code AND ``` style fenced raw code ends here
[ "md", "code", "AND", "style", "fenced", "raw", "code", "ends", "here" ]
9370864a9f1d65bb0f822d0aea83f1169c98f3bd
https://github.com/roaet/eh/blob/9370864a9f1d65bb0f822d0aea83f1169c98f3bd/eh/mdv/markdownviewer.py#L361-L383
245,788
calvinku96/labreporthelper
labreporthelper/bestfit/curvefit.py
ODRFit.bestfit_func
def bestfit_func(self, bestfit_x): """ Returns y value """ if not self.bestfit_func: raise KeyError("Do do_bestfit first") return self.args["func"](self.fit_args, bestfit_x)
python
def bestfit_func(self, bestfit_x): """ Returns y value """ if not self.bestfit_func: raise KeyError("Do do_bestfit first") return self.args["func"](self.fit_args, bestfit_x)
[ "def", "bestfit_func", "(", "self", ",", "bestfit_x", ")", ":", "if", "not", "self", ".", "bestfit_func", ":", "raise", "KeyError", "(", "\"Do do_bestfit first\"", ")", "return", "self", ".", "args", "[", "\"func\"", "]", "(", "self", ".", "fit_args", ",", "bestfit_x", ")" ]
Returns y value
[ "Returns", "y", "value" ]
4d436241f389c02eb188c313190df62ab28c3763
https://github.com/calvinku96/labreporthelper/blob/4d436241f389c02eb188c313190df62ab28c3763/labreporthelper/bestfit/curvefit.py#L57-L63
245,789
calvinku96/labreporthelper
labreporthelper/bestfit/curvefit.py
ODRFit.do_bestfit
def do_bestfit(self): """ do bestfit using scipy.odr """ self.check_important_variables() x = np.array(self.args["x"]) y = np.array(self.args["y"]) if self.args.get("use_RealData", True): realdata_kwargs = self.args.get("RealData_kwargs", {}) data = RealData(x, y, **realdata_kwargs) else: data_kwargs = self.args.get("Data_kwargs", {}) data = Data(x, y, **data_kwargs) model = self.args.get("Model", None) if model is None: if "func" not in self.args.keys(): raise KeyError("Need fitting function") model_kwargs = self.args.get("Model_kwargs", {}) model = Model(self.args["func"], **model_kwargs) odr_kwargs = self.args.get("ODR_kwargs", {}) odr = ODR(data, model, **odr_kwargs) self.output = odr.run() if self.args.get("pprint", False): self.output.pprint() self.fit_args = self.output.beta return self.fit_args
python
def do_bestfit(self): """ do bestfit using scipy.odr """ self.check_important_variables() x = np.array(self.args["x"]) y = np.array(self.args["y"]) if self.args.get("use_RealData", True): realdata_kwargs = self.args.get("RealData_kwargs", {}) data = RealData(x, y, **realdata_kwargs) else: data_kwargs = self.args.get("Data_kwargs", {}) data = Data(x, y, **data_kwargs) model = self.args.get("Model", None) if model is None: if "func" not in self.args.keys(): raise KeyError("Need fitting function") model_kwargs = self.args.get("Model_kwargs", {}) model = Model(self.args["func"], **model_kwargs) odr_kwargs = self.args.get("ODR_kwargs", {}) odr = ODR(data, model, **odr_kwargs) self.output = odr.run() if self.args.get("pprint", False): self.output.pprint() self.fit_args = self.output.beta return self.fit_args
[ "def", "do_bestfit", "(", "self", ")", ":", "self", ".", "check_important_variables", "(", ")", "x", "=", "np", ".", "array", "(", "self", ".", "args", "[", "\"x\"", "]", ")", "y", "=", "np", ".", "array", "(", "self", ".", "args", "[", "\"y\"", "]", ")", "if", "self", ".", "args", ".", "get", "(", "\"use_RealData\"", ",", "True", ")", ":", "realdata_kwargs", "=", "self", ".", "args", ".", "get", "(", "\"RealData_kwargs\"", ",", "{", "}", ")", "data", "=", "RealData", "(", "x", ",", "y", ",", "*", "*", "realdata_kwargs", ")", "else", ":", "data_kwargs", "=", "self", ".", "args", ".", "get", "(", "\"Data_kwargs\"", ",", "{", "}", ")", "data", "=", "Data", "(", "x", ",", "y", ",", "*", "*", "data_kwargs", ")", "model", "=", "self", ".", "args", ".", "get", "(", "\"Model\"", ",", "None", ")", "if", "model", "is", "None", ":", "if", "\"func\"", "not", "in", "self", ".", "args", ".", "keys", "(", ")", ":", "raise", "KeyError", "(", "\"Need fitting function\"", ")", "model_kwargs", "=", "self", ".", "args", ".", "get", "(", "\"Model_kwargs\"", ",", "{", "}", ")", "model", "=", "Model", "(", "self", ".", "args", "[", "\"func\"", "]", ",", "*", "*", "model_kwargs", ")", "odr_kwargs", "=", "self", ".", "args", ".", "get", "(", "\"ODR_kwargs\"", ",", "{", "}", ")", "odr", "=", "ODR", "(", "data", ",", "model", ",", "*", "*", "odr_kwargs", ")", "self", ".", "output", "=", "odr", ".", "run", "(", ")", "if", "self", ".", "args", ".", "get", "(", "\"pprint\"", ",", "False", ")", ":", "self", ".", "output", ".", "pprint", "(", ")", "self", ".", "fit_args", "=", "self", ".", "output", ".", "beta", "return", "self", ".", "fit_args" ]
do bestfit using scipy.odr
[ "do", "bestfit", "using", "scipy", ".", "odr" ]
4d436241f389c02eb188c313190df62ab28c3763
https://github.com/calvinku96/labreporthelper/blob/4d436241f389c02eb188c313190df62ab28c3763/labreporthelper/bestfit/curvefit.py#L65-L90
245,790
scdoshi/django-bits
bits/gis.py
change_in_longitude
def change_in_longitude(lat, miles): """Given a latitude and a distance west, return the change in longitude.""" # Find the radius of a circle around the earth at given latitude. r = earth_radius * math.cos(lat * degrees_to_radians) return (miles / r) * radians_to_degrees
python
def change_in_longitude(lat, miles): """Given a latitude and a distance west, return the change in longitude.""" # Find the radius of a circle around the earth at given latitude. r = earth_radius * math.cos(lat * degrees_to_radians) return (miles / r) * radians_to_degrees
[ "def", "change_in_longitude", "(", "lat", ",", "miles", ")", ":", "# Find the radius of a circle around the earth at given latitude.", "r", "=", "earth_radius", "*", "math", ".", "cos", "(", "lat", "*", "degrees_to_radians", ")", "return", "(", "miles", "/", "r", ")", "*", "radians_to_degrees" ]
Given a latitude and a distance west, return the change in longitude.
[ "Given", "a", "latitude", "and", "a", "distance", "west", "return", "the", "change", "in", "longitude", "." ]
0a2f4fd9374d2a8acb8df9a7b83eebcf2782256f
https://github.com/scdoshi/django-bits/blob/0a2f4fd9374d2a8acb8df9a7b83eebcf2782256f/bits/gis.py#L55-L60
245,791
20c/xbahn
xbahn/connection/link.py
Wire.disconnect
def disconnect(self): """ Close all connections that are set on this wire """ if self.connection_receive: self.connection_receive.close() if self.connection_respond: self.connection_respond.close() if self.connection_send: self.connection_send.close()
python
def disconnect(self): """ Close all connections that are set on this wire """ if self.connection_receive: self.connection_receive.close() if self.connection_respond: self.connection_respond.close() if self.connection_send: self.connection_send.close()
[ "def", "disconnect", "(", "self", ")", ":", "if", "self", ".", "connection_receive", ":", "self", ".", "connection_receive", ".", "close", "(", ")", "if", "self", ".", "connection_respond", ":", "self", ".", "connection_respond", ".", "close", "(", ")", "if", "self", ".", "connection_send", ":", "self", ".", "connection_send", ".", "close", "(", ")" ]
Close all connections that are set on this wire
[ "Close", "all", "connections", "that", "are", "set", "on", "this", "wire" ]
afb27b0576841338a366d7cac0200a782bd84be6
https://github.com/20c/xbahn/blob/afb27b0576841338a366d7cac0200a782bd84be6/xbahn/connection/link.py#L32-L42
245,792
20c/xbahn
xbahn/connection/link.py
Wire.send_and_wait
def send_and_wait(self, path, message, timeout=0, responder=None): """ Send a message and block until a response is received. Return response message """ message.on("response", lambda x,event_origin,source:None, once=True) if timeout > 0: ts = time.time() else: ts = 0 sent = False while not message.response_received: if not sent: self.send(path, message) sent = True if ts: if time.time() - ts > timeout: raise exceptions.TimeoutError("send_and_wait(%s)"%path, timeout) return message.response_message
python
def send_and_wait(self, path, message, timeout=0, responder=None): """ Send a message and block until a response is received. Return response message """ message.on("response", lambda x,event_origin,source:None, once=True) if timeout > 0: ts = time.time() else: ts = 0 sent = False while not message.response_received: if not sent: self.send(path, message) sent = True if ts: if time.time() - ts > timeout: raise exceptions.TimeoutError("send_and_wait(%s)"%path, timeout) return message.response_message
[ "def", "send_and_wait", "(", "self", ",", "path", ",", "message", ",", "timeout", "=", "0", ",", "responder", "=", "None", ")", ":", "message", ".", "on", "(", "\"response\"", ",", "lambda", "x", ",", "event_origin", ",", "source", ":", "None", ",", "once", "=", "True", ")", "if", "timeout", ">", "0", ":", "ts", "=", "time", ".", "time", "(", ")", "else", ":", "ts", "=", "0", "sent", "=", "False", "while", "not", "message", ".", "response_received", ":", "if", "not", "sent", ":", "self", ".", "send", "(", "path", ",", "message", ")", "sent", "=", "True", "if", "ts", ":", "if", "time", ".", "time", "(", ")", "-", "ts", ">", "timeout", ":", "raise", "exceptions", ".", "TimeoutError", "(", "\"send_and_wait(%s)\"", "%", "path", ",", "timeout", ")", "return", "message", ".", "response_message" ]
Send a message and block until a response is received. Return response message
[ "Send", "a", "message", "and", "block", "until", "a", "response", "is", "received", ".", "Return", "response", "message" ]
afb27b0576841338a366d7cac0200a782bd84be6
https://github.com/20c/xbahn/blob/afb27b0576841338a366d7cac0200a782bd84be6/xbahn/connection/link.py#L61-L82
245,793
20c/xbahn
xbahn/connection/link.py
Link.wire
def wire(self, name, receive=None, send=None, respond=None, **kwargs): """ Wires the link to a connection. Can be called multiple times to set up wires to different connections After creation wire will be accessible on the link via its name as an attribute. You can undo this action with the cut() method Arguments: - name (str): unique name for the wire Keyword Arguments: - receive (Connection): wire receiver to this connection - respond (Connection): wire responder to this connection - send (Connection): wire sender to this connection - meta (dict): attach these meta variables to any message sent from this wire Returns: - Wire: the created wire instance """ if hasattr(self, name) and name != "main": raise AttributeError("cannot use '%s' as name for wire, attribute already exists") if send: self.log_debug("Wiring '%s'.send: %s" % (name, send)) if respond: self.log_debug("Wiring '%s'.respond: %s" % (name, respond)) if receive: self.log_debug("Wiring '%s'.receive: %s" % (name, receive)) wire = Wire(receive=receive, send=send, respond=respond) wire.name = "%s.%s" % (self.name, name) wire.meta = kwargs.get("meta",{}) wire.on("receive", self.on_receive) setattr(self, name, wire) if not self.main: self.main = wire return wire
python
def wire(self, name, receive=None, send=None, respond=None, **kwargs): """ Wires the link to a connection. Can be called multiple times to set up wires to different connections After creation wire will be accessible on the link via its name as an attribute. You can undo this action with the cut() method Arguments: - name (str): unique name for the wire Keyword Arguments: - receive (Connection): wire receiver to this connection - respond (Connection): wire responder to this connection - send (Connection): wire sender to this connection - meta (dict): attach these meta variables to any message sent from this wire Returns: - Wire: the created wire instance """ if hasattr(self, name) and name != "main": raise AttributeError("cannot use '%s' as name for wire, attribute already exists") if send: self.log_debug("Wiring '%s'.send: %s" % (name, send)) if respond: self.log_debug("Wiring '%s'.respond: %s" % (name, respond)) if receive: self.log_debug("Wiring '%s'.receive: %s" % (name, receive)) wire = Wire(receive=receive, send=send, respond=respond) wire.name = "%s.%s" % (self.name, name) wire.meta = kwargs.get("meta",{}) wire.on("receive", self.on_receive) setattr(self, name, wire) if not self.main: self.main = wire return wire
[ "def", "wire", "(", "self", ",", "name", ",", "receive", "=", "None", ",", "send", "=", "None", ",", "respond", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "hasattr", "(", "self", ",", "name", ")", "and", "name", "!=", "\"main\"", ":", "raise", "AttributeError", "(", "\"cannot use '%s' as name for wire, attribute already exists\"", ")", "if", "send", ":", "self", ".", "log_debug", "(", "\"Wiring '%s'.send: %s\"", "%", "(", "name", ",", "send", ")", ")", "if", "respond", ":", "self", ".", "log_debug", "(", "\"Wiring '%s'.respond: %s\"", "%", "(", "name", ",", "respond", ")", ")", "if", "receive", ":", "self", ".", "log_debug", "(", "\"Wiring '%s'.receive: %s\"", "%", "(", "name", ",", "receive", ")", ")", "wire", "=", "Wire", "(", "receive", "=", "receive", ",", "send", "=", "send", ",", "respond", "=", "respond", ")", "wire", ".", "name", "=", "\"%s.%s\"", "%", "(", "self", ".", "name", ",", "name", ")", "wire", ".", "meta", "=", "kwargs", ".", "get", "(", "\"meta\"", ",", "{", "}", ")", "wire", ".", "on", "(", "\"receive\"", ",", "self", ".", "on_receive", ")", "setattr", "(", "self", ",", "name", ",", "wire", ")", "if", "not", "self", ".", "main", ":", "self", ".", "main", "=", "wire", "return", "wire" ]
Wires the link to a connection. Can be called multiple times to set up wires to different connections After creation wire will be accessible on the link via its name as an attribute. You can undo this action with the cut() method Arguments: - name (str): unique name for the wire Keyword Arguments: - receive (Connection): wire receiver to this connection - respond (Connection): wire responder to this connection - send (Connection): wire sender to this connection - meta (dict): attach these meta variables to any message sent from this wire Returns: - Wire: the created wire instance
[ "Wires", "the", "link", "to", "a", "connection", ".", "Can", "be", "called", "multiple", "times", "to", "set", "up", "wires", "to", "different", "connections" ]
afb27b0576841338a366d7cac0200a782bd84be6
https://github.com/20c/xbahn/blob/afb27b0576841338a366d7cac0200a782bd84be6/xbahn/connection/link.py#L152-L199
245,794
20c/xbahn
xbahn/connection/link.py
Link.disconnect
def disconnect(self): """ Cut all wires and disconnect all connections established on this link """ for name, wire in self.wires(): self.cut(name, disconnect=True)
python
def disconnect(self): """ Cut all wires and disconnect all connections established on this link """ for name, wire in self.wires(): self.cut(name, disconnect=True)
[ "def", "disconnect", "(", "self", ")", ":", "for", "name", ",", "wire", "in", "self", ".", "wires", "(", ")", ":", "self", ".", "cut", "(", "name", ",", "disconnect", "=", "True", ")" ]
Cut all wires and disconnect all connections established on this link
[ "Cut", "all", "wires", "and", "disconnect", "all", "connections", "established", "on", "this", "link" ]
afb27b0576841338a366d7cac0200a782bd84be6
https://github.com/20c/xbahn/blob/afb27b0576841338a366d7cac0200a782bd84be6/xbahn/connection/link.py#L266-L272
245,795
AtteqCom/zsl_client
python/zsl_client.py
Service.call
def call(self, task, decorators=None): """ Call given task on service layer. :param task: task to be called. task will be decorated with TaskDecorator's contained in 'decorators' list :type task: instance of Task class :param decorators: list of TaskDecorator's / TaskResultDecorator's inherited classes :type decorators: list :return task_result: result of task call decorated with TaskResultDecorator's contained in 'decorators' list :rtype TaskResult instance """ if decorators is None: decorators = [] task = self.apply_task_decorators(task, decorators) data = task.get_data() name = task.get_name() result = self._inner_call(name, data) task_result = RawTaskResult(task, result) return self.apply_task_result_decorators(task_result, decorators)
python
def call(self, task, decorators=None): """ Call given task on service layer. :param task: task to be called. task will be decorated with TaskDecorator's contained in 'decorators' list :type task: instance of Task class :param decorators: list of TaskDecorator's / TaskResultDecorator's inherited classes :type decorators: list :return task_result: result of task call decorated with TaskResultDecorator's contained in 'decorators' list :rtype TaskResult instance """ if decorators is None: decorators = [] task = self.apply_task_decorators(task, decorators) data = task.get_data() name = task.get_name() result = self._inner_call(name, data) task_result = RawTaskResult(task, result) return self.apply_task_result_decorators(task_result, decorators)
[ "def", "call", "(", "self", ",", "task", ",", "decorators", "=", "None", ")", ":", "if", "decorators", "is", "None", ":", "decorators", "=", "[", "]", "task", "=", "self", ".", "apply_task_decorators", "(", "task", ",", "decorators", ")", "data", "=", "task", ".", "get_data", "(", ")", "name", "=", "task", ".", "get_name", "(", ")", "result", "=", "self", ".", "_inner_call", "(", "name", ",", "data", ")", "task_result", "=", "RawTaskResult", "(", "task", ",", "result", ")", "return", "self", ".", "apply_task_result_decorators", "(", "task_result", ",", "decorators", ")" ]
Call given task on service layer. :param task: task to be called. task will be decorated with TaskDecorator's contained in 'decorators' list :type task: instance of Task class :param decorators: list of TaskDecorator's / TaskResultDecorator's inherited classes :type decorators: list :return task_result: result of task call decorated with TaskResultDecorator's contained in 'decorators' list :rtype TaskResult instance
[ "Call", "given", "task", "on", "service", "layer", "." ]
d362c618f7d7b7fd7e85220a17f9854fd229d583
https://github.com/AtteqCom/zsl_client/blob/d362c618f7d7b7fd7e85220a17f9854fd229d583/python/zsl_client.py#L173-L198
245,796
edeposit/edeposit.amqp.pdfgen
src/edeposit/amqp/pdfgen/specialization.py
_resource_context
def _resource_context(fn): """ Compose path to the ``resources`` directory for given `fn`. Args: fn (str): Filename of file in ``resources`` directory. Returns: str: Absolute path to the file in resources directory. """ return os.path.join( os.path.dirname(__file__), DES_DIR, fn )
python
def _resource_context(fn): """ Compose path to the ``resources`` directory for given `fn`. Args: fn (str): Filename of file in ``resources`` directory. Returns: str: Absolute path to the file in resources directory. """ return os.path.join( os.path.dirname(__file__), DES_DIR, fn )
[ "def", "_resource_context", "(", "fn", ")", ":", "return", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ",", "DES_DIR", ",", "fn", ")" ]
Compose path to the ``resources`` directory for given `fn`. Args: fn (str): Filename of file in ``resources`` directory. Returns: str: Absolute path to the file in resources directory.
[ "Compose", "path", "to", "the", "resources", "directory", "for", "given", "fn", "." ]
1022d6d01196f4928d664a71e49273c2d8c67e63
https://github.com/edeposit/edeposit.amqp.pdfgen/blob/1022d6d01196f4928d664a71e49273c2d8c67e63/src/edeposit/amqp/pdfgen/specialization.py#L26-L40
245,797
edeposit/edeposit.amqp.pdfgen
src/edeposit/amqp/pdfgen/specialization.py
get_contract
def get_contract(firma, pravni_forma, sidlo, ic, dic, zastoupen): """ Compose contract and create PDF. Args: firma (str): firma pravni_forma (str): pravni_forma sidlo (str): sidlo ic (str): ic dic (str): dic zastoupen (str): zastoupen Returns: obj: StringIO file instance containing PDF file. """ contract_fn = _resource_context( "Licencni_smlouva_o_dodavani_elektronickych_publikaci" "_a_jejich_uziti.rst" ) # load contract with open(contract_fn) as f: contract = f.read()#.decode("utf-8").encode("utf-8") # make sure that `firma` has its heading mark firma = firma.strip() firma = firma + "\n" + ((len(firma) + 1) * "-") # patch template contract = Template(contract).substitute( firma=firma, pravni_forma=pravni_forma.strip(), sidlo=sidlo.strip(), ic=ic.strip(), dic=dic.strip(), zastoupen=zastoupen.strip(), resources_path=RES_PATH ) return gen_pdf( contract, open(_resource_context("style.json")).read(), )
python
def get_contract(firma, pravni_forma, sidlo, ic, dic, zastoupen): """ Compose contract and create PDF. Args: firma (str): firma pravni_forma (str): pravni_forma sidlo (str): sidlo ic (str): ic dic (str): dic zastoupen (str): zastoupen Returns: obj: StringIO file instance containing PDF file. """ contract_fn = _resource_context( "Licencni_smlouva_o_dodavani_elektronickych_publikaci" "_a_jejich_uziti.rst" ) # load contract with open(contract_fn) as f: contract = f.read()#.decode("utf-8").encode("utf-8") # make sure that `firma` has its heading mark firma = firma.strip() firma = firma + "\n" + ((len(firma) + 1) * "-") # patch template contract = Template(contract).substitute( firma=firma, pravni_forma=pravni_forma.strip(), sidlo=sidlo.strip(), ic=ic.strip(), dic=dic.strip(), zastoupen=zastoupen.strip(), resources_path=RES_PATH ) return gen_pdf( contract, open(_resource_context("style.json")).read(), )
[ "def", "get_contract", "(", "firma", ",", "pravni_forma", ",", "sidlo", ",", "ic", ",", "dic", ",", "zastoupen", ")", ":", "contract_fn", "=", "_resource_context", "(", "\"Licencni_smlouva_o_dodavani_elektronickych_publikaci\"", "\"_a_jejich_uziti.rst\"", ")", "# load contract", "with", "open", "(", "contract_fn", ")", "as", "f", ":", "contract", "=", "f", ".", "read", "(", ")", "#.decode(\"utf-8\").encode(\"utf-8\")", "# make sure that `firma` has its heading mark", "firma", "=", "firma", ".", "strip", "(", ")", "firma", "=", "firma", "+", "\"\\n\"", "+", "(", "(", "len", "(", "firma", ")", "+", "1", ")", "*", "\"-\"", ")", "# patch template", "contract", "=", "Template", "(", "contract", ")", ".", "substitute", "(", "firma", "=", "firma", ",", "pravni_forma", "=", "pravni_forma", ".", "strip", "(", ")", ",", "sidlo", "=", "sidlo", ".", "strip", "(", ")", ",", "ic", "=", "ic", ".", "strip", "(", ")", ",", "dic", "=", "dic", ".", "strip", "(", ")", ",", "zastoupen", "=", "zastoupen", ".", "strip", "(", ")", ",", "resources_path", "=", "RES_PATH", ")", "return", "gen_pdf", "(", "contract", ",", "open", "(", "_resource_context", "(", "\"style.json\"", ")", ")", ".", "read", "(", ")", ",", ")" ]
Compose contract and create PDF. Args: firma (str): firma pravni_forma (str): pravni_forma sidlo (str): sidlo ic (str): ic dic (str): dic zastoupen (str): zastoupen Returns: obj: StringIO file instance containing PDF file.
[ "Compose", "contract", "and", "create", "PDF", "." ]
1022d6d01196f4928d664a71e49273c2d8c67e63
https://github.com/edeposit/edeposit.amqp.pdfgen/blob/1022d6d01196f4928d664a71e49273c2d8c67e63/src/edeposit/amqp/pdfgen/specialization.py#L43-L85
245,798
edeposit/edeposit.amqp.pdfgen
src/edeposit/amqp/pdfgen/specialization.py
get_review
def get_review(review_struct): """ Generate review from `review_struct`. Args: review_struct (obj): :class:`.GenerateReview` instance. Returns: obj: StringIO file instance containing PDF file. """ review_fn = _resource_context("review.rst") # read review template with open(review_fn) as f: review = f.read() # generate qr code with NamedTemporaryFile(suffix=".png") as qr_file: url = pyqrcode.create(review_struct.internal_url) url.png(qr_file.name, scale=5) # save the file qr_file.flush() qr_file.seek(0) # generate template review = Template(review).substitute( content=review_struct.get_rst(), datum=time.strftime("%d.%m.%Y", time.localtime()), cas=time.strftime("%H:%M", time.localtime()), resources_path=RES_PATH, qr_path=qr_file.name, ) return gen_pdf( review, open(_resource_context("review_style.json")).read(), )
python
def get_review(review_struct): """ Generate review from `review_struct`. Args: review_struct (obj): :class:`.GenerateReview` instance. Returns: obj: StringIO file instance containing PDF file. """ review_fn = _resource_context("review.rst") # read review template with open(review_fn) as f: review = f.read() # generate qr code with NamedTemporaryFile(suffix=".png") as qr_file: url = pyqrcode.create(review_struct.internal_url) url.png(qr_file.name, scale=5) # save the file qr_file.flush() qr_file.seek(0) # generate template review = Template(review).substitute( content=review_struct.get_rst(), datum=time.strftime("%d.%m.%Y", time.localtime()), cas=time.strftime("%H:%M", time.localtime()), resources_path=RES_PATH, qr_path=qr_file.name, ) return gen_pdf( review, open(_resource_context("review_style.json")).read(), )
[ "def", "get_review", "(", "review_struct", ")", ":", "review_fn", "=", "_resource_context", "(", "\"review.rst\"", ")", "# read review template", "with", "open", "(", "review_fn", ")", "as", "f", ":", "review", "=", "f", ".", "read", "(", ")", "# generate qr code", "with", "NamedTemporaryFile", "(", "suffix", "=", "\".png\"", ")", "as", "qr_file", ":", "url", "=", "pyqrcode", ".", "create", "(", "review_struct", ".", "internal_url", ")", "url", ".", "png", "(", "qr_file", ".", "name", ",", "scale", "=", "5", ")", "# save the file", "qr_file", ".", "flush", "(", ")", "qr_file", ".", "seek", "(", "0", ")", "# generate template", "review", "=", "Template", "(", "review", ")", ".", "substitute", "(", "content", "=", "review_struct", ".", "get_rst", "(", ")", ",", "datum", "=", "time", ".", "strftime", "(", "\"%d.%m.%Y\"", ",", "time", ".", "localtime", "(", ")", ")", ",", "cas", "=", "time", ".", "strftime", "(", "\"%H:%M\"", ",", "time", ".", "localtime", "(", ")", ")", ",", "resources_path", "=", "RES_PATH", ",", "qr_path", "=", "qr_file", ".", "name", ",", ")", "return", "gen_pdf", "(", "review", ",", "open", "(", "_resource_context", "(", "\"review_style.json\"", ")", ")", ".", "read", "(", ")", ",", ")" ]
Generate review from `review_struct`. Args: review_struct (obj): :class:`.GenerateReview` instance. Returns: obj: StringIO file instance containing PDF file.
[ "Generate", "review", "from", "review_struct", "." ]
1022d6d01196f4928d664a71e49273c2d8c67e63
https://github.com/edeposit/edeposit.amqp.pdfgen/blob/1022d6d01196f4928d664a71e49273c2d8c67e63/src/edeposit/amqp/pdfgen/specialization.py#L88-L125
245,799
minhhoit/yacms
yacms/template/__init__.py
Library.render_tag
def render_tag(self, tag_func): """ Creates a tag using the decorated func as the render function for the template tag node. The render function takes two arguments - the template context and the tag token. """ @wraps(tag_func) def tag_wrapper(parser, token): class RenderTagNode(template.Node): def render(self, context): return tag_func(context, token) return RenderTagNode() return self.tag(tag_wrapper)
python
def render_tag(self, tag_func): """ Creates a tag using the decorated func as the render function for the template tag node. The render function takes two arguments - the template context and the tag token. """ @wraps(tag_func) def tag_wrapper(parser, token): class RenderTagNode(template.Node): def render(self, context): return tag_func(context, token) return RenderTagNode() return self.tag(tag_wrapper)
[ "def", "render_tag", "(", "self", ",", "tag_func", ")", ":", "@", "wraps", "(", "tag_func", ")", "def", "tag_wrapper", "(", "parser", ",", "token", ")", ":", "class", "RenderTagNode", "(", "template", ".", "Node", ")", ":", "def", "render", "(", "self", ",", "context", ")", ":", "return", "tag_func", "(", "context", ",", "token", ")", "return", "RenderTagNode", "(", ")", "return", "self", ".", "tag", "(", "tag_wrapper", ")" ]
Creates a tag using the decorated func as the render function for the template tag node. The render function takes two arguments - the template context and the tag token.
[ "Creates", "a", "tag", "using", "the", "decorated", "func", "as", "the", "render", "function", "for", "the", "template", "tag", "node", ".", "The", "render", "function", "takes", "two", "arguments", "-", "the", "template", "context", "and", "the", "tag", "token", "." ]
2921b706b7107c6e8c5f2bbf790ff11f85a2167f
https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/template/__init__.py#L51-L63