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
242,700
jonathansick/paperweight
paperweight/nlputils.py
wordify
def wordify(text): """Generate a list of words given text, removing punctuation. Parameters ---------- text : unicode A piece of english text. Returns ------- words : list List of words. """ stopset = set(nltk.corpus.stopwords.words('english')) tokens = nltk.WordPunctTokenizer().tokenize(text) return [w for w in tokens if w not in stopset]
python
def wordify(text): """Generate a list of words given text, removing punctuation. Parameters ---------- text : unicode A piece of english text. Returns ------- words : list List of words. """ stopset = set(nltk.corpus.stopwords.words('english')) tokens = nltk.WordPunctTokenizer().tokenize(text) return [w for w in tokens if w not in stopset]
[ "def", "wordify", "(", "text", ")", ":", "stopset", "=", "set", "(", "nltk", ".", "corpus", ".", "stopwords", ".", "words", "(", "'english'", ")", ")", "tokens", "=", "nltk", ".", "WordPunctTokenizer", "(", ")", ".", "tokenize", "(", "text", ")", "return", "[", "w", "for", "w", "in", "tokens", "if", "w", "not", "in", "stopset", "]" ]
Generate a list of words given text, removing punctuation. Parameters ---------- text : unicode A piece of english text. Returns ------- words : list List of words.
[ "Generate", "a", "list", "of", "words", "given", "text", "removing", "punctuation", "." ]
803535b939a56d375967cefecd5fdca81323041e
https://github.com/jonathansick/paperweight/blob/803535b939a56d375967cefecd5fdca81323041e/paperweight/nlputils.py#L10-L25
242,701
mkurnikov/typed-env
typed_env/initialize.py
initialize_env
def initialize_env(env_file=None, fail_silently=True, load_globally=True): """ Returns an instance of _Environment after reading the system environment an optionally provided file. """ data = {} data.update(os.environ) if env_file: data.update(read_file_values(env_file, fail_silently)) if load_globally: os.environ.update(data) return Environment(env_dict=data)
python
def initialize_env(env_file=None, fail_silently=True, load_globally=True): """ Returns an instance of _Environment after reading the system environment an optionally provided file. """ data = {} data.update(os.environ) if env_file: data.update(read_file_values(env_file, fail_silently)) if load_globally: os.environ.update(data) return Environment(env_dict=data)
[ "def", "initialize_env", "(", "env_file", "=", "None", ",", "fail_silently", "=", "True", ",", "load_globally", "=", "True", ")", ":", "data", "=", "{", "}", "data", ".", "update", "(", "os", ".", "environ", ")", "if", "env_file", ":", "data", ".", "update", "(", "read_file_values", "(", "env_file", ",", "fail_silently", ")", ")", "if", "load_globally", ":", "os", ".", "environ", ".", "update", "(", "data", ")", "return", "Environment", "(", "env_dict", "=", "data", ")" ]
Returns an instance of _Environment after reading the system environment an optionally provided file.
[ "Returns", "an", "instance", "of", "_Environment", "after", "reading", "the", "system", "environment", "an", "optionally", "provided", "file", "." ]
d0f3e947f0d5561c9fd1679d6faa9830de24d870
https://github.com/mkurnikov/typed-env/blob/d0f3e947f0d5561c9fd1679d6faa9830de24d870/typed_env/initialize.py#L10-L23
242,702
inveniosoftware-attic/invenio-knowledge
docs/_ext/flask_app.py
setup
def setup(sphinx): """Setup Sphinx object.""" from flask import has_app_context from invenio_base.factory import create_app PACKAGES = ['invenio_base', 'invenio.modules.accounts', 'invenio.modules.records', 'invenio_knowledge'] if not has_app_context(): app = create_app(PACKAGES=PACKAGES) ctx = app.test_request_context('/') ctx.push()
python
def setup(sphinx): """Setup Sphinx object.""" from flask import has_app_context from invenio_base.factory import create_app PACKAGES = ['invenio_base', 'invenio.modules.accounts', 'invenio.modules.records', 'invenio_knowledge'] if not has_app_context(): app = create_app(PACKAGES=PACKAGES) ctx = app.test_request_context('/') ctx.push()
[ "def", "setup", "(", "sphinx", ")", ":", "from", "flask", "import", "has_app_context", "from", "invenio_base", ".", "factory", "import", "create_app", "PACKAGES", "=", "[", "'invenio_base'", ",", "'invenio.modules.accounts'", ",", "'invenio.modules.records'", ",", "'invenio_knowledge'", "]", "if", "not", "has_app_context", "(", ")", ":", "app", "=", "create_app", "(", "PACKAGES", "=", "PACKAGES", ")", "ctx", "=", "app", ".", "test_request_context", "(", "'/'", ")", "ctx", ".", "push", "(", ")" ]
Setup Sphinx object.
[ "Setup", "Sphinx", "object", "." ]
b31722dc14243ca8f626f8b3bce9718d0119de55
https://github.com/inveniosoftware-attic/invenio-knowledge/blob/b31722dc14243ca8f626f8b3bce9718d0119de55/docs/_ext/flask_app.py#L23-L33
242,703
oleg-golovanov/unilog
unilog/convert.py
pretty_spaces
def pretty_spaces(level): """ Return spaces and new line. :type level: int or None :param level: deep level :rtype: unicode :return: string with new line and spaces """ if level is None: return u'' return (os.linesep if level >= 0 else u'') + (u' ' * (INDENT * level))
python
def pretty_spaces(level): """ Return spaces and new line. :type level: int or None :param level: deep level :rtype: unicode :return: string with new line and spaces """ if level is None: return u'' return (os.linesep if level >= 0 else u'') + (u' ' * (INDENT * level))
[ "def", "pretty_spaces", "(", "level", ")", ":", "if", "level", "is", "None", ":", "return", "u''", "return", "(", "os", ".", "linesep", "if", "level", ">=", "0", "else", "u''", ")", "+", "(", "u' '", "*", "(", "INDENT", "*", "level", ")", ")" ]
Return spaces and new line. :type level: int or None :param level: deep level :rtype: unicode :return: string with new line and spaces
[ "Return", "spaces", "and", "new", "line", "." ]
4d59cd910032383a71796c4df7446fd5875938c3
https://github.com/oleg-golovanov/unilog/blob/4d59cd910032383a71796c4df7446fd5875938c3/unilog/convert.py#L20-L33
242,704
oleg-golovanov/unilog
unilog/convert.py
unimapping
def unimapping(arg, level): """ Mapping object to unicode string. :type arg: collections.Mapping :param arg: mapping object :type level: int :param level: deep level :rtype: unicode :return: mapping object as unicode string """ if not isinstance(arg, collections.Mapping): raise TypeError( 'expected collections.Mapping, {} received'.format(type(arg).__name__) ) result = [] for i in arg.items(): result.append( pretty_spaces(level) + u': '.join(map(functools.partial(convert, level=level), i)) ) string = join_strings(result, level) if level is not None: string += pretty_spaces(level - 1) return u'{{{}}}'.format(string)
python
def unimapping(arg, level): """ Mapping object to unicode string. :type arg: collections.Mapping :param arg: mapping object :type level: int :param level: deep level :rtype: unicode :return: mapping object as unicode string """ if not isinstance(arg, collections.Mapping): raise TypeError( 'expected collections.Mapping, {} received'.format(type(arg).__name__) ) result = [] for i in arg.items(): result.append( pretty_spaces(level) + u': '.join(map(functools.partial(convert, level=level), i)) ) string = join_strings(result, level) if level is not None: string += pretty_spaces(level - 1) return u'{{{}}}'.format(string)
[ "def", "unimapping", "(", "arg", ",", "level", ")", ":", "if", "not", "isinstance", "(", "arg", ",", "collections", ".", "Mapping", ")", ":", "raise", "TypeError", "(", "'expected collections.Mapping, {} received'", ".", "format", "(", "type", "(", "arg", ")", ".", "__name__", ")", ")", "result", "=", "[", "]", "for", "i", "in", "arg", ".", "items", "(", ")", ":", "result", ".", "append", "(", "pretty_spaces", "(", "level", ")", "+", "u': '", ".", "join", "(", "map", "(", "functools", ".", "partial", "(", "convert", ",", "level", "=", "level", ")", ",", "i", ")", ")", ")", "string", "=", "join_strings", "(", "result", ",", "level", ")", "if", "level", "is", "not", "None", ":", "string", "+=", "pretty_spaces", "(", "level", "-", "1", ")", "return", "u'{{{}}}'", ".", "format", "(", "string", ")" ]
Mapping object to unicode string. :type arg: collections.Mapping :param arg: mapping object :type level: int :param level: deep level :rtype: unicode :return: mapping object as unicode string
[ "Mapping", "object", "to", "unicode", "string", "." ]
4d59cd910032383a71796c4df7446fd5875938c3
https://github.com/oleg-golovanov/unilog/blob/4d59cd910032383a71796c4df7446fd5875938c3/unilog/convert.py#L52-L80
242,705
oleg-golovanov/unilog
unilog/convert.py
uniiterable
def uniiterable(arg, level): """ Iterable object to unicode string. :type arg: collections.Iterable :param arg: iterable object :type level: int :param level: deep level :rtype: unicode :return: iterable object as unicode string """ if not isinstance(arg, collections.Iterable): raise TypeError( 'expected collections.Iterable, {} received'.format(type(arg).__name__) ) templates = { list: u'[{}]', tuple: u'({})' } result = [] for i in arg: result.append(pretty_spaces(level) + convert(i, level=level)) string = join_strings(result, level) if level is not None: string += pretty_spaces(level - 1) return templates.get(type(arg), templates[tuple]).format(string)
python
def uniiterable(arg, level): """ Iterable object to unicode string. :type arg: collections.Iterable :param arg: iterable object :type level: int :param level: deep level :rtype: unicode :return: iterable object as unicode string """ if not isinstance(arg, collections.Iterable): raise TypeError( 'expected collections.Iterable, {} received'.format(type(arg).__name__) ) templates = { list: u'[{}]', tuple: u'({})' } result = [] for i in arg: result.append(pretty_spaces(level) + convert(i, level=level)) string = join_strings(result, level) if level is not None: string += pretty_spaces(level - 1) return templates.get(type(arg), templates[tuple]).format(string)
[ "def", "uniiterable", "(", "arg", ",", "level", ")", ":", "if", "not", "isinstance", "(", "arg", ",", "collections", ".", "Iterable", ")", ":", "raise", "TypeError", "(", "'expected collections.Iterable, {} received'", ".", "format", "(", "type", "(", "arg", ")", ".", "__name__", ")", ")", "templates", "=", "{", "list", ":", "u'[{}]'", ",", "tuple", ":", "u'({})'", "}", "result", "=", "[", "]", "for", "i", "in", "arg", ":", "result", ".", "append", "(", "pretty_spaces", "(", "level", ")", "+", "convert", "(", "i", ",", "level", "=", "level", ")", ")", "string", "=", "join_strings", "(", "result", ",", "level", ")", "if", "level", "is", "not", "None", ":", "string", "+=", "pretty_spaces", "(", "level", "-", "1", ")", "return", "templates", ".", "get", "(", "type", "(", "arg", ")", ",", "templates", "[", "tuple", "]", ")", ".", "format", "(", "string", ")" ]
Iterable object to unicode string. :type arg: collections.Iterable :param arg: iterable object :type level: int :param level: deep level :rtype: unicode :return: iterable object as unicode string
[ "Iterable", "object", "to", "unicode", "string", "." ]
4d59cd910032383a71796c4df7446fd5875938c3
https://github.com/oleg-golovanov/unilog/blob/4d59cd910032383a71796c4df7446fd5875938c3/unilog/convert.py#L83-L114
242,706
oleg-golovanov/unilog
unilog/convert.py
convert
def convert(obj, encoding=LOCALE, level=None): """ Covert any object to unicode string. :param obj: any object :type encoding: str :param encoding: codec for encoding unicode strings (locale.getpreferredencoding() by default) :type level: int :param level: Deep level. If None level is not considered. :rtype: unicode :return: any object as unicode string """ callable_ = CONVERTERS.get(type(obj)) if callable_ is not None: obj = callable_(obj) func = lambda x, level: compat.template.format(x) if isinstance(obj, compat.UnicodeType): # skip if condition, because unicode is a iterable type pass elif isinstance(obj, str): func = lambda x, level: u"'{}'".format(x.decode(encoding)) elif isinstance(obj, (bytearray, bytes)): func = lambda x, level: u"b'{}'".format( u''.join(u'\\x{:02x}'.format(b) for b in x) ) elif isinstance(obj, (type(None), int, float)): func = lambda x, level: compat.UnicodeType(x) elif isinstance(obj, (types.GeneratorType, compat.XRangeType)): func = lambda x, level: u"'{!r}'".format(x) elif isinstance(obj, collections.Mapping): func = unimapping elif isinstance(obj, collections.Iterable): func = uniiterable if level is not None: level += 1 return func(obj, level)
python
def convert(obj, encoding=LOCALE, level=None): """ Covert any object to unicode string. :param obj: any object :type encoding: str :param encoding: codec for encoding unicode strings (locale.getpreferredencoding() by default) :type level: int :param level: Deep level. If None level is not considered. :rtype: unicode :return: any object as unicode string """ callable_ = CONVERTERS.get(type(obj)) if callable_ is not None: obj = callable_(obj) func = lambda x, level: compat.template.format(x) if isinstance(obj, compat.UnicodeType): # skip if condition, because unicode is a iterable type pass elif isinstance(obj, str): func = lambda x, level: u"'{}'".format(x.decode(encoding)) elif isinstance(obj, (bytearray, bytes)): func = lambda x, level: u"b'{}'".format( u''.join(u'\\x{:02x}'.format(b) for b in x) ) elif isinstance(obj, (type(None), int, float)): func = lambda x, level: compat.UnicodeType(x) elif isinstance(obj, (types.GeneratorType, compat.XRangeType)): func = lambda x, level: u"'{!r}'".format(x) elif isinstance(obj, collections.Mapping): func = unimapping elif isinstance(obj, collections.Iterable): func = uniiterable if level is not None: level += 1 return func(obj, level)
[ "def", "convert", "(", "obj", ",", "encoding", "=", "LOCALE", ",", "level", "=", "None", ")", ":", "callable_", "=", "CONVERTERS", ".", "get", "(", "type", "(", "obj", ")", ")", "if", "callable_", "is", "not", "None", ":", "obj", "=", "callable_", "(", "obj", ")", "func", "=", "lambda", "x", ",", "level", ":", "compat", ".", "template", ".", "format", "(", "x", ")", "if", "isinstance", "(", "obj", ",", "compat", ".", "UnicodeType", ")", ":", "# skip if condition, because unicode is a iterable type", "pass", "elif", "isinstance", "(", "obj", ",", "str", ")", ":", "func", "=", "lambda", "x", ",", "level", ":", "u\"'{}'\"", ".", "format", "(", "x", ".", "decode", "(", "encoding", ")", ")", "elif", "isinstance", "(", "obj", ",", "(", "bytearray", ",", "bytes", ")", ")", ":", "func", "=", "lambda", "x", ",", "level", ":", "u\"b'{}'\"", ".", "format", "(", "u''", ".", "join", "(", "u'\\\\x{:02x}'", ".", "format", "(", "b", ")", "for", "b", "in", "x", ")", ")", "elif", "isinstance", "(", "obj", ",", "(", "type", "(", "None", ")", ",", "int", ",", "float", ")", ")", ":", "func", "=", "lambda", "x", ",", "level", ":", "compat", ".", "UnicodeType", "(", "x", ")", "elif", "isinstance", "(", "obj", ",", "(", "types", ".", "GeneratorType", ",", "compat", ".", "XRangeType", ")", ")", ":", "func", "=", "lambda", "x", ",", "level", ":", "u\"'{!r}'\"", ".", "format", "(", "x", ")", "elif", "isinstance", "(", "obj", ",", "collections", ".", "Mapping", ")", ":", "func", "=", "unimapping", "elif", "isinstance", "(", "obj", ",", "collections", ".", "Iterable", ")", ":", "func", "=", "uniiterable", "if", "level", "is", "not", "None", ":", "level", "+=", "1", "return", "func", "(", "obj", ",", "level", ")" ]
Covert any object to unicode string. :param obj: any object :type encoding: str :param encoding: codec for encoding unicode strings (locale.getpreferredencoding() by default) :type level: int :param level: Deep level. If None level is not considered. :rtype: unicode :return: any object as unicode string
[ "Covert", "any", "object", "to", "unicode", "string", "." ]
4d59cd910032383a71796c4df7446fd5875938c3
https://github.com/oleg-golovanov/unilog/blob/4d59cd910032383a71796c4df7446fd5875938c3/unilog/convert.py#L117-L159
242,707
pyvec/pyvodb
pyvodb/cli/show.py
show
def show(ctx, city, date): """Show a particular meetup. city: The meetup series. \b date: The date. May be: - YYYY-MM-DD or YY-MM-DD (e.g. 2015-08-27) - YYYY-MM or YY-MM (e.g. 2015-08) - MM (e.g. 08): the given month in the current year - pN (e.g. p1): show the N-th last meetup - +N (e.g. +2): show the N-th next meetup - Omitted: show the next meetup (same as +1) """ db = ctx.obj['db'] today = ctx.obj['now'].date() term = ctx.obj['term'] event = cliutil.get_event(db, city, date, today) data = event.as_dict() cliutil.handle_raw_output(ctx, data) render_event(term, event, today, verbose=ctx.obj['verbose'])
python
def show(ctx, city, date): """Show a particular meetup. city: The meetup series. \b date: The date. May be: - YYYY-MM-DD or YY-MM-DD (e.g. 2015-08-27) - YYYY-MM or YY-MM (e.g. 2015-08) - MM (e.g. 08): the given month in the current year - pN (e.g. p1): show the N-th last meetup - +N (e.g. +2): show the N-th next meetup - Omitted: show the next meetup (same as +1) """ db = ctx.obj['db'] today = ctx.obj['now'].date() term = ctx.obj['term'] event = cliutil.get_event(db, city, date, today) data = event.as_dict() cliutil.handle_raw_output(ctx, data) render_event(term, event, today, verbose=ctx.obj['verbose'])
[ "def", "show", "(", "ctx", ",", "city", ",", "date", ")", ":", "db", "=", "ctx", ".", "obj", "[", "'db'", "]", "today", "=", "ctx", ".", "obj", "[", "'now'", "]", ".", "date", "(", ")", "term", "=", "ctx", ".", "obj", "[", "'term'", "]", "event", "=", "cliutil", ".", "get_event", "(", "db", ",", "city", ",", "date", ",", "today", ")", "data", "=", "event", ".", "as_dict", "(", ")", "cliutil", ".", "handle_raw_output", "(", "ctx", ",", "data", ")", "render_event", "(", "term", ",", "event", ",", "today", ",", "verbose", "=", "ctx", ".", "obj", "[", "'verbose'", "]", ")" ]
Show a particular meetup. city: The meetup series. \b date: The date. May be: - YYYY-MM-DD or YY-MM-DD (e.g. 2015-08-27) - YYYY-MM or YY-MM (e.g. 2015-08) - MM (e.g. 08): the given month in the current year - pN (e.g. p1): show the N-th last meetup - +N (e.g. +2): show the N-th next meetup - Omitted: show the next meetup (same as +1)
[ "Show", "a", "particular", "meetup", "." ]
07183333df26eb12c5c2b98802cde3fb3a6c1339
https://github.com/pyvec/pyvodb/blob/07183333df26eb12c5c2b98802cde3fb3a6c1339/pyvodb/cli/show.py#L14-L36
242,708
krukas/Trionyx
trionyx/config.py
ModelConfig.get_list_fields
def get_list_fields(self): """Get all list fields""" from trionyx.renderer import renderer model_fields = {f.name: f for f in self.model.get_fields(True, True)} def create_list_fields(config_fields, list_fields=None): list_fields = list_fields if list_fields else {} for field in config_fields: config = field if isinstance(field, str): config = {'field': field} if 'field' not in config: raise Exception("Field config is missing field: {}".format(config)) if 'label' not in config: if config['field'] in model_fields: config['label'] = model_fields[config['field']].verbose_name else: config['label'] = config['field'] if 'renderer' not in config: config['renderer'] = renderer.render_field list_fields[config['field']] = config return list_fields list_fields = create_list_fields(model_fields.keys()) if self.list_fields: list_fields = create_list_fields(self.list_fields, list_fields) return list_fields
python
def get_list_fields(self): """Get all list fields""" from trionyx.renderer import renderer model_fields = {f.name: f for f in self.model.get_fields(True, True)} def create_list_fields(config_fields, list_fields=None): list_fields = list_fields if list_fields else {} for field in config_fields: config = field if isinstance(field, str): config = {'field': field} if 'field' not in config: raise Exception("Field config is missing field: {}".format(config)) if 'label' not in config: if config['field'] in model_fields: config['label'] = model_fields[config['field']].verbose_name else: config['label'] = config['field'] if 'renderer' not in config: config['renderer'] = renderer.render_field list_fields[config['field']] = config return list_fields list_fields = create_list_fields(model_fields.keys()) if self.list_fields: list_fields = create_list_fields(self.list_fields, list_fields) return list_fields
[ "def", "get_list_fields", "(", "self", ")", ":", "from", "trionyx", ".", "renderer", "import", "renderer", "model_fields", "=", "{", "f", ".", "name", ":", "f", "for", "f", "in", "self", ".", "model", ".", "get_fields", "(", "True", ",", "True", ")", "}", "def", "create_list_fields", "(", "config_fields", ",", "list_fields", "=", "None", ")", ":", "list_fields", "=", "list_fields", "if", "list_fields", "else", "{", "}", "for", "field", "in", "config_fields", ":", "config", "=", "field", "if", "isinstance", "(", "field", ",", "str", ")", ":", "config", "=", "{", "'field'", ":", "field", "}", "if", "'field'", "not", "in", "config", ":", "raise", "Exception", "(", "\"Field config is missing field: {}\"", ".", "format", "(", "config", ")", ")", "if", "'label'", "not", "in", "config", ":", "if", "config", "[", "'field'", "]", "in", "model_fields", ":", "config", "[", "'label'", "]", "=", "model_fields", "[", "config", "[", "'field'", "]", "]", ".", "verbose_name", "else", ":", "config", "[", "'label'", "]", "=", "config", "[", "'field'", "]", "if", "'renderer'", "not", "in", "config", ":", "config", "[", "'renderer'", "]", "=", "renderer", ".", "render_field", "list_fields", "[", "config", "[", "'field'", "]", "]", "=", "config", "return", "list_fields", "list_fields", "=", "create_list_fields", "(", "model_fields", ".", "keys", "(", ")", ")", "if", "self", ".", "list_fields", ":", "list_fields", "=", "create_list_fields", "(", "self", ".", "list_fields", ",", "list_fields", ")", "return", "list_fields" ]
Get all list fields
[ "Get", "all", "list", "fields" ]
edac132cc0797190153f2e60bc7e88cb50e80da6
https://github.com/krukas/Trionyx/blob/edac132cc0797190153f2e60bc7e88cb50e80da6/trionyx/config.py#L162-L193
242,709
krukas/Trionyx
trionyx/config.py
ModelConfig._get_form
def _get_form(self, config_name, only_required=False): """Get form for given config else create form""" if getattr(self, config_name, None): return import_object_by_string(getattr(self, config_name)) def use_field(field): if not only_required: return True return field.default == NOT_PROVIDED return modelform_factory(self.model, fields=[f.name for f in self.model.get_fields() if use_field(f)])
python
def _get_form(self, config_name, only_required=False): """Get form for given config else create form""" if getattr(self, config_name, None): return import_object_by_string(getattr(self, config_name)) def use_field(field): if not only_required: return True return field.default == NOT_PROVIDED return modelform_factory(self.model, fields=[f.name for f in self.model.get_fields() if use_field(f)])
[ "def", "_get_form", "(", "self", ",", "config_name", ",", "only_required", "=", "False", ")", ":", "if", "getattr", "(", "self", ",", "config_name", ",", "None", ")", ":", "return", "import_object_by_string", "(", "getattr", "(", "self", ",", "config_name", ")", ")", "def", "use_field", "(", "field", ")", ":", "if", "not", "only_required", ":", "return", "True", "return", "field", ".", "default", "==", "NOT_PROVIDED", "return", "modelform_factory", "(", "self", ".", "model", ",", "fields", "=", "[", "f", ".", "name", "for", "f", "in", "self", ".", "model", ".", "get_fields", "(", ")", "if", "use_field", "(", "f", ")", "]", ")" ]
Get form for given config else create form
[ "Get", "form", "for", "given", "config", "else", "create", "form" ]
edac132cc0797190153f2e60bc7e88cb50e80da6
https://github.com/krukas/Trionyx/blob/edac132cc0797190153f2e60bc7e88cb50e80da6/trionyx/config.py#L195-L205
242,710
krukas/Trionyx
trionyx/config.py
Models.auto_load_configs
def auto_load_configs(self): """Auto load all configs from app configs""" for app in apps.get_app_configs(): for model in app.get_models(): config = ModelConfig(model, getattr(app, model.__name__, None)) self.configs[self.get_model_name(model)] = config
python
def auto_load_configs(self): """Auto load all configs from app configs""" for app in apps.get_app_configs(): for model in app.get_models(): config = ModelConfig(model, getattr(app, model.__name__, None)) self.configs[self.get_model_name(model)] = config
[ "def", "auto_load_configs", "(", "self", ")", ":", "for", "app", "in", "apps", ".", "get_app_configs", "(", ")", ":", "for", "model", "in", "app", ".", "get_models", "(", ")", ":", "config", "=", "ModelConfig", "(", "model", ",", "getattr", "(", "app", ",", "model", ".", "__name__", ",", "None", ")", ")", "self", ".", "configs", "[", "self", ".", "get_model_name", "(", "model", ")", "]", "=", "config" ]
Auto load all configs from app configs
[ "Auto", "load", "all", "configs", "from", "app", "configs" ]
edac132cc0797190153f2e60bc7e88cb50e80da6
https://github.com/krukas/Trionyx/blob/edac132cc0797190153f2e60bc7e88cb50e80da6/trionyx/config.py#L215-L220
242,711
krukas/Trionyx
trionyx/config.py
Models.get_config
def get_config(self, model): """Get config for given model""" if not inspect.isclass(model): model = model.__class__ return self.configs.get(self.get_model_name(model))
python
def get_config(self, model): """Get config for given model""" if not inspect.isclass(model): model = model.__class__ return self.configs.get(self.get_model_name(model))
[ "def", "get_config", "(", "self", ",", "model", ")", ":", "if", "not", "inspect", ".", "isclass", "(", "model", ")", ":", "model", "=", "model", ".", "__class__", "return", "self", ".", "configs", ".", "get", "(", "self", ".", "get_model_name", "(", "model", ")", ")" ]
Get config for given model
[ "Get", "config", "for", "given", "model" ]
edac132cc0797190153f2e60bc7e88cb50e80da6
https://github.com/krukas/Trionyx/blob/edac132cc0797190153f2e60bc7e88cb50e80da6/trionyx/config.py#L222-L226
242,712
krukas/Trionyx
trionyx/config.py
Models.get_all_configs
def get_all_configs(self, trionyx_models_only=True): """Get all model configs""" from trionyx.models import BaseModel for index, config in self.configs.items(): if not isinstance(config.model(), BaseModel): continue yield config
python
def get_all_configs(self, trionyx_models_only=True): """Get all model configs""" from trionyx.models import BaseModel for index, config in self.configs.items(): if not isinstance(config.model(), BaseModel): continue yield config
[ "def", "get_all_configs", "(", "self", ",", "trionyx_models_only", "=", "True", ")", ":", "from", "trionyx", ".", "models", "import", "BaseModel", "for", "index", ",", "config", "in", "self", ".", "configs", ".", "items", "(", ")", ":", "if", "not", "isinstance", "(", "config", ".", "model", "(", ")", ",", "BaseModel", ")", ":", "continue", "yield", "config" ]
Get all model configs
[ "Get", "all", "model", "configs" ]
edac132cc0797190153f2e60bc7e88cb50e80da6
https://github.com/krukas/Trionyx/blob/edac132cc0797190153f2e60bc7e88cb50e80da6/trionyx/config.py#L228-L236
242,713
CivicSpleen/ckcache
ckcache/multi.py
MultiCache.put
def put(self, source, rel_path, metadata=None): """Puts to only the first upstream. This is to be symmetric with put_stream.""" return self.upstreams[0].put(source, rel_path, metadata)
python
def put(self, source, rel_path, metadata=None): """Puts to only the first upstream. This is to be symmetric with put_stream.""" return self.upstreams[0].put(source, rel_path, metadata)
[ "def", "put", "(", "self", ",", "source", ",", "rel_path", ",", "metadata", "=", "None", ")", ":", "return", "self", ".", "upstreams", "[", "0", "]", ".", "put", "(", "source", ",", "rel_path", ",", "metadata", ")" ]
Puts to only the first upstream. This is to be symmetric with put_stream.
[ "Puts", "to", "only", "the", "first", "upstream", ".", "This", "is", "to", "be", "symmetric", "with", "put_stream", "." ]
0c699b6ba97ff164e9702504f0e1643dd4cd39e1
https://github.com/CivicSpleen/ckcache/blob/0c699b6ba97ff164e9702504f0e1643dd4cd39e1/ckcache/multi.py#L52-L54
242,714
CivicSpleen/ckcache
ckcache/multi.py
AltReadCache.list
def list(self, path=None, with_metadata=False, include_partitions=False): """Combine a listing of all of the upstreams, and add a metadata item for the repo_id""" l = {} for upstream in [self.alternate, self.upstream]: for k, v in upstream.list(path, with_metadata, include_partitions).items(): upstreams = (l[k]['caches'] if k in l else []) + \ v.get('caches', upstream.repo_id) l[k] = v l[k]['caches'] = upstreams return l
python
def list(self, path=None, with_metadata=False, include_partitions=False): """Combine a listing of all of the upstreams, and add a metadata item for the repo_id""" l = {} for upstream in [self.alternate, self.upstream]: for k, v in upstream.list(path, with_metadata, include_partitions).items(): upstreams = (l[k]['caches'] if k in l else []) + \ v.get('caches', upstream.repo_id) l[k] = v l[k]['caches'] = upstreams return l
[ "def", "list", "(", "self", ",", "path", "=", "None", ",", "with_metadata", "=", "False", ",", "include_partitions", "=", "False", ")", ":", "l", "=", "{", "}", "for", "upstream", "in", "[", "self", ".", "alternate", ",", "self", ".", "upstream", "]", ":", "for", "k", ",", "v", "in", "upstream", ".", "list", "(", "path", ",", "with_metadata", ",", "include_partitions", ")", ".", "items", "(", ")", ":", "upstreams", "=", "(", "l", "[", "k", "]", "[", "'caches'", "]", "if", "k", "in", "l", "else", "[", "]", ")", "+", "v", ".", "get", "(", "'caches'", ",", "upstream", ".", "repo_id", ")", "l", "[", "k", "]", "=", "v", "l", "[", "k", "]", "[", "'caches'", "]", "=", "upstreams", "return", "l" ]
Combine a listing of all of the upstreams, and add a metadata item for the repo_id
[ "Combine", "a", "listing", "of", "all", "of", "the", "upstreams", "and", "add", "a", "metadata", "item", "for", "the", "repo_id" ]
0c699b6ba97ff164e9702504f0e1643dd4cd39e1
https://github.com/CivicSpleen/ckcache/blob/0c699b6ba97ff164e9702504f0e1643dd4cd39e1/ckcache/multi.py#L132-L146
242,715
CivicSpleen/ckcache
ckcache/multi.py
AltReadCache._copy_across
def _copy_across(self, rel_path, cb=None): """If the upstream doesn't have the file, get it from the alternate and store it in the upstream""" from . import copy_file_or_flo if not self.upstream.has(rel_path): if not self.alternate.has(rel_path): return None source = self.alternate.get_stream(rel_path) sink = self.upstream.put_stream(rel_path, metadata=source.meta) try: copy_file_or_flo(source, sink, cb=cb) except: self.upstream.remove(rel_path, propagate=True) raise source.close() sink.close()
python
def _copy_across(self, rel_path, cb=None): """If the upstream doesn't have the file, get it from the alternate and store it in the upstream""" from . import copy_file_or_flo if not self.upstream.has(rel_path): if not self.alternate.has(rel_path): return None source = self.alternate.get_stream(rel_path) sink = self.upstream.put_stream(rel_path, metadata=source.meta) try: copy_file_or_flo(source, sink, cb=cb) except: self.upstream.remove(rel_path, propagate=True) raise source.close() sink.close()
[ "def", "_copy_across", "(", "self", ",", "rel_path", ",", "cb", "=", "None", ")", ":", "from", ".", "import", "copy_file_or_flo", "if", "not", "self", ".", "upstream", ".", "has", "(", "rel_path", ")", ":", "if", "not", "self", ".", "alternate", ".", "has", "(", "rel_path", ")", ":", "return", "None", "source", "=", "self", ".", "alternate", ".", "get_stream", "(", "rel_path", ")", "sink", "=", "self", ".", "upstream", ".", "put_stream", "(", "rel_path", ",", "metadata", "=", "source", ".", "meta", ")", "try", ":", "copy_file_or_flo", "(", "source", ",", "sink", ",", "cb", "=", "cb", ")", "except", ":", "self", ".", "upstream", ".", "remove", "(", "rel_path", ",", "propagate", "=", "True", ")", "raise", "source", ".", "close", "(", ")", "sink", ".", "close", "(", ")" ]
If the upstream doesn't have the file, get it from the alternate and store it in the upstream
[ "If", "the", "upstream", "doesn", "t", "have", "the", "file", "get", "it", "from", "the", "alternate", "and", "store", "it", "in", "the", "upstream" ]
0c699b6ba97ff164e9702504f0e1643dd4cd39e1
https://github.com/CivicSpleen/ckcache/blob/0c699b6ba97ff164e9702504f0e1643dd4cd39e1/ckcache/multi.py#L148-L170
242,716
CitrineInformatics/dftparse
dftparse/wien2k/sigmak_parser.py
_parse_sigmak
def _parse_sigmak(line, lines): """Parse Energy, Re sigma xx, Im sigma xx, Re sigma zz, Im sigma zz""" split_line = line.split() energy = float(split_line[0]) re_sigma_xx = float(split_line[1]) im_sigma_xx = float(split_line[2]) re_sigma_zz = float(split_line[3]) im_sigma_zz = float(split_line[4]) return {"energy": energy, "re_sigma_xx": re_sigma_xx, "im_sigma_xx": im_sigma_xx, "re_sigma_zz": re_sigma_zz, "im_sigma_zz": im_sigma_zz}
python
def _parse_sigmak(line, lines): """Parse Energy, Re sigma xx, Im sigma xx, Re sigma zz, Im sigma zz""" split_line = line.split() energy = float(split_line[0]) re_sigma_xx = float(split_line[1]) im_sigma_xx = float(split_line[2]) re_sigma_zz = float(split_line[3]) im_sigma_zz = float(split_line[4]) return {"energy": energy, "re_sigma_xx": re_sigma_xx, "im_sigma_xx": im_sigma_xx, "re_sigma_zz": re_sigma_zz, "im_sigma_zz": im_sigma_zz}
[ "def", "_parse_sigmak", "(", "line", ",", "lines", ")", ":", "split_line", "=", "line", ".", "split", "(", ")", "energy", "=", "float", "(", "split_line", "[", "0", "]", ")", "re_sigma_xx", "=", "float", "(", "split_line", "[", "1", "]", ")", "im_sigma_xx", "=", "float", "(", "split_line", "[", "2", "]", ")", "re_sigma_zz", "=", "float", "(", "split_line", "[", "3", "]", ")", "im_sigma_zz", "=", "float", "(", "split_line", "[", "4", "]", ")", "return", "{", "\"energy\"", ":", "energy", ",", "\"re_sigma_xx\"", ":", "re_sigma_xx", ",", "\"im_sigma_xx\"", ":", "im_sigma_xx", ",", "\"re_sigma_zz\"", ":", "re_sigma_zz", ",", "\"im_sigma_zz\"", ":", "im_sigma_zz", "}" ]
Parse Energy, Re sigma xx, Im sigma xx, Re sigma zz, Im sigma zz
[ "Parse", "Energy", "Re", "sigma", "xx", "Im", "sigma", "xx", "Re", "sigma", "zz", "Im", "sigma", "zz" ]
53a1bf19945cf1c195d6af9beccb3d1b7f4a4c1d
https://github.com/CitrineInformatics/dftparse/blob/53a1bf19945cf1c195d6af9beccb3d1b7f4a4c1d/dftparse/wien2k/sigmak_parser.py#L4-L16
242,717
armstrong/armstrong.dev
armstrong/dev/tasks.py
require_self
def require_self(func, *args, **kwargs): """Decorator to require that this component be installed""" try: __import__(package['name']) except ImportError: sys.stderr.write( "This component needs to be installed first. Run " + "`invoke install`\n") sys.exit(1) return func(*args, **kwargs)
python
def require_self(func, *args, **kwargs): """Decorator to require that this component be installed""" try: __import__(package['name']) except ImportError: sys.stderr.write( "This component needs to be installed first. Run " + "`invoke install`\n") sys.exit(1) return func(*args, **kwargs)
[ "def", "require_self", "(", "func", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "__import__", "(", "package", "[", "'name'", "]", ")", "except", "ImportError", ":", "sys", ".", "stderr", ".", "write", "(", "\"This component needs to be installed first. Run \"", "+", "\"`invoke install`\\n\"", ")", "sys", ".", "exit", "(", "1", ")", "return", "func", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
Decorator to require that this component be installed
[ "Decorator", "to", "require", "that", "this", "component", "be", "installed" ]
6fd8b863038d9e5ebfd52dfe5ce6c85fb441c267
https://github.com/armstrong/armstrong.dev/blob/6fd8b863038d9e5ebfd52dfe5ce6c85fb441c267/armstrong/dev/tasks.py#L35-L45
242,718
armstrong/armstrong.dev
armstrong/dev/tasks.py
require_pip_module
def require_pip_module(module): """Decorator to check for a module and helpfully exit if it's not found""" def wrapper(func, *args, **kwargs): try: __import__(module) except ImportError: sys.stderr.write( "`pip install %s` to enable this feature\n" % module) sys.exit(1) else: return func(*args, **kwargs) return decorator(wrapper)
python
def require_pip_module(module): """Decorator to check for a module and helpfully exit if it's not found""" def wrapper(func, *args, **kwargs): try: __import__(module) except ImportError: sys.stderr.write( "`pip install %s` to enable this feature\n" % module) sys.exit(1) else: return func(*args, **kwargs) return decorator(wrapper)
[ "def", "require_pip_module", "(", "module", ")", ":", "def", "wrapper", "(", "func", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "__import__", "(", "module", ")", "except", "ImportError", ":", "sys", ".", "stderr", ".", "write", "(", "\"`pip install %s` to enable this feature\\n\"", "%", "module", ")", "sys", ".", "exit", "(", "1", ")", "else", ":", "return", "func", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "decorator", "(", "wrapper", ")" ]
Decorator to check for a module and helpfully exit if it's not found
[ "Decorator", "to", "check", "for", "a", "module", "and", "helpfully", "exit", "if", "it", "s", "not", "found" ]
6fd8b863038d9e5ebfd52dfe5ce6c85fb441c267
https://github.com/armstrong/armstrong.dev/blob/6fd8b863038d9e5ebfd52dfe5ce6c85fb441c267/armstrong/dev/tasks.py#L48-L60
242,719
armstrong/armstrong.dev
armstrong/dev/tasks.py
replaced_by_django_migrations
def replaced_by_django_migrations(func, *args, **kwargs): """Decorator to preempt South requirement""" DjangoSettings() # trigger helpful messages if Django is missing import django if django.VERSION >= (1, 7): print("Django 1.7+ has its own migrations system.") print("Use this instead: `invoke managepy makemigrations`") sys.exit(1) return func(*args, **kwargs)
python
def replaced_by_django_migrations(func, *args, **kwargs): """Decorator to preempt South requirement""" DjangoSettings() # trigger helpful messages if Django is missing import django if django.VERSION >= (1, 7): print("Django 1.7+ has its own migrations system.") print("Use this instead: `invoke managepy makemigrations`") sys.exit(1) return func(*args, **kwargs)
[ "def", "replaced_by_django_migrations", "(", "func", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "DjangoSettings", "(", ")", "# trigger helpful messages if Django is missing", "import", "django", "if", "django", ".", "VERSION", ">=", "(", "1", ",", "7", ")", ":", "print", "(", "\"Django 1.7+ has its own migrations system.\"", ")", "print", "(", "\"Use this instead: `invoke managepy makemigrations`\"", ")", "sys", ".", "exit", "(", "1", ")", "return", "func", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
Decorator to preempt South requirement
[ "Decorator", "to", "preempt", "South", "requirement" ]
6fd8b863038d9e5ebfd52dfe5ce6c85fb441c267
https://github.com/armstrong/armstrong.dev/blob/6fd8b863038d9e5ebfd52dfe5ce6c85fb441c267/armstrong/dev/tasks.py#L64-L74
242,720
armstrong/armstrong.dev
armstrong/dev/tasks.py
create_migration
def create_migration(initial=False): """Create a South migration for this project""" settings = DjangoSettings() if 'south' not in (name.lower() for name in settings.INSTALLED_APPS): print("Temporarily adding 'south' into INSTALLED_APPS.") settings.INSTALLED_APPS.append('south') kwargs = dict(initial=True) if initial else dict(auto=True) run_django_cmd('schemamigration', package['name'], **kwargs)
python
def create_migration(initial=False): """Create a South migration for this project""" settings = DjangoSettings() if 'south' not in (name.lower() for name in settings.INSTALLED_APPS): print("Temporarily adding 'south' into INSTALLED_APPS.") settings.INSTALLED_APPS.append('south') kwargs = dict(initial=True) if initial else dict(auto=True) run_django_cmd('schemamigration', package['name'], **kwargs)
[ "def", "create_migration", "(", "initial", "=", "False", ")", ":", "settings", "=", "DjangoSettings", "(", ")", "if", "'south'", "not", "in", "(", "name", ".", "lower", "(", ")", "for", "name", "in", "settings", ".", "INSTALLED_APPS", ")", ":", "print", "(", "\"Temporarily adding 'south' into INSTALLED_APPS.\"", ")", "settings", ".", "INSTALLED_APPS", ".", "append", "(", "'south'", ")", "kwargs", "=", "dict", "(", "initial", "=", "True", ")", "if", "initial", "else", "dict", "(", "auto", "=", "True", ")", "run_django_cmd", "(", "'schemamigration'", ",", "package", "[", "'name'", "]", ",", "*", "*", "kwargs", ")" ]
Create a South migration for this project
[ "Create", "a", "South", "migration", "for", "this", "project" ]
6fd8b863038d9e5ebfd52dfe5ce6c85fb441c267
https://github.com/armstrong/armstrong.dev/blob/6fd8b863038d9e5ebfd52dfe5ce6c85fb441c267/armstrong/dev/tasks.py#L87-L96
242,721
armstrong/armstrong.dev
armstrong/dev/tasks.py
coverage
def coverage(reportdir=None, extra=None): """Test this project with coverage reports""" import coverage as coverage_api cov = coverage_api.coverage() opts = {'directory': reportdir} if reportdir else {} cov.start() test(extra) cov.stop() cov.html_report(**opts)
python
def coverage(reportdir=None, extra=None): """Test this project with coverage reports""" import coverage as coverage_api cov = coverage_api.coverage() opts = {'directory': reportdir} if reportdir else {} cov.start() test(extra) cov.stop() cov.html_report(**opts)
[ "def", "coverage", "(", "reportdir", "=", "None", ",", "extra", "=", "None", ")", ":", "import", "coverage", "as", "coverage_api", "cov", "=", "coverage_api", ".", "coverage", "(", ")", "opts", "=", "{", "'directory'", ":", "reportdir", "}", "if", "reportdir", "else", "{", "}", "cov", ".", "start", "(", ")", "test", "(", "extra", ")", "cov", ".", "stop", "(", ")", "cov", ".", "html_report", "(", "*", "*", "opts", ")" ]
Test this project with coverage reports
[ "Test", "this", "project", "with", "coverage", "reports" ]
6fd8b863038d9e5ebfd52dfe5ce6c85fb441c267
https://github.com/armstrong/armstrong.dev/blob/6fd8b863038d9e5ebfd52dfe5ce6c85fb441c267/armstrong/dev/tasks.py#L116-L126
242,722
armstrong/armstrong.dev
armstrong/dev/tasks.py
managepy
def managepy(cmd, extra=None): """Run manage.py using this component's specific Django settings""" extra = extra.split() if extra else [] run_django_cli(['invoke', cmd] + extra)
python
def managepy(cmd, extra=None): """Run manage.py using this component's specific Django settings""" extra = extra.split() if extra else [] run_django_cli(['invoke', cmd] + extra)
[ "def", "managepy", "(", "cmd", ",", "extra", "=", "None", ")", ":", "extra", "=", "extra", ".", "split", "(", ")", "if", "extra", "else", "[", "]", "run_django_cli", "(", "[", "'invoke'", ",", "cmd", "]", "+", "extra", ")" ]
Run manage.py using this component's specific Django settings
[ "Run", "manage", ".", "py", "using", "this", "component", "s", "specific", "Django", "settings" ]
6fd8b863038d9e5ebfd52dfe5ce6c85fb441c267
https://github.com/armstrong/armstrong.dev/blob/6fd8b863038d9e5ebfd52dfe5ce6c85fb441c267/armstrong/dev/tasks.py#L130-L134
242,723
CitrineInformatics/dftparse
dftparse/vasp/outcar_parser.py
_parse_total_magnetization
def _parse_total_magnetization(line, lines): """Parse the total magnetization, which is somewhat hidden""" toks = line.split() res = {"number of electrons": float(toks[3])} if len(toks) > 5: res["total magnetization"] = float(toks[5]) return res
python
def _parse_total_magnetization(line, lines): """Parse the total magnetization, which is somewhat hidden""" toks = line.split() res = {"number of electrons": float(toks[3])} if len(toks) > 5: res["total magnetization"] = float(toks[5]) return res
[ "def", "_parse_total_magnetization", "(", "line", ",", "lines", ")", ":", "toks", "=", "line", ".", "split", "(", ")", "res", "=", "{", "\"number of electrons\"", ":", "float", "(", "toks", "[", "3", "]", ")", "}", "if", "len", "(", "toks", ")", ">", "5", ":", "res", "[", "\"total magnetization\"", "]", "=", "float", "(", "toks", "[", "5", "]", ")", "return", "res" ]
Parse the total magnetization, which is somewhat hidden
[ "Parse", "the", "total", "magnetization", "which", "is", "somewhat", "hidden" ]
53a1bf19945cf1c195d6af9beccb3d1b7f4a4c1d
https://github.com/CitrineInformatics/dftparse/blob/53a1bf19945cf1c195d6af9beccb3d1b7f4a4c1d/dftparse/vasp/outcar_parser.py#L4-L10
242,724
bitlabstudio/django-server-guardian-api
server_guardian_api/processors/django_mailer.py
deferred_emails
def deferred_emails(): """Checks for deferred email, that otherwise fill up the queue.""" status = SERVER_STATUS['OK'] count = Message.objects.deferred().count() if DEFERRED_WARNING_THRESHOLD <= count < DEFERRED_DANGER_THRESHOLD: status = SERVER_STATUS['WARNING'] if count >= DEFERRED_DANGER_THRESHOLD: status = SERVER_STATUS['DANGER'] return { 'label': 'Deferred Email', 'status': status, 'info': 'There are currently {0} deferred messages.'.format(count) }
python
def deferred_emails(): """Checks for deferred email, that otherwise fill up the queue.""" status = SERVER_STATUS['OK'] count = Message.objects.deferred().count() if DEFERRED_WARNING_THRESHOLD <= count < DEFERRED_DANGER_THRESHOLD: status = SERVER_STATUS['WARNING'] if count >= DEFERRED_DANGER_THRESHOLD: status = SERVER_STATUS['DANGER'] return { 'label': 'Deferred Email', 'status': status, 'info': 'There are currently {0} deferred messages.'.format(count) }
[ "def", "deferred_emails", "(", ")", ":", "status", "=", "SERVER_STATUS", "[", "'OK'", "]", "count", "=", "Message", ".", "objects", ".", "deferred", "(", ")", ".", "count", "(", ")", "if", "DEFERRED_WARNING_THRESHOLD", "<=", "count", "<", "DEFERRED_DANGER_THRESHOLD", ":", "status", "=", "SERVER_STATUS", "[", "'WARNING'", "]", "if", "count", ">=", "DEFERRED_DANGER_THRESHOLD", ":", "status", "=", "SERVER_STATUS", "[", "'DANGER'", "]", "return", "{", "'label'", ":", "'Deferred Email'", ",", "'status'", ":", "status", ",", "'info'", ":", "'There are currently {0} deferred messages.'", ".", "format", "(", "count", ")", "}" ]
Checks for deferred email, that otherwise fill up the queue.
[ "Checks", "for", "deferred", "email", "that", "otherwise", "fill", "up", "the", "queue", "." ]
c996245b5a8e8f6f590251a8757adcca79d114e3
https://github.com/bitlabstudio/django-server-guardian-api/blob/c996245b5a8e8f6f590251a8757adcca79d114e3/server_guardian_api/processors/django_mailer.py#L22-L36
242,725
bitlabstudio/django-server-guardian-api
server_guardian_api/processors/django_mailer.py
email_queue
def email_queue(): """Checks for emails, that fill up the queue without getting sent.""" status = SERVER_STATUS['OK'] count = Message.objects.exclude(priority=PRIORITY_DEFERRED).filter( when_added__lte=now() - timedelta(minutes=QUEUE_TIMEOUT)).count() if QUEUE_WARNING_THRESHOLD <= count < QUEUE_DANGER_THRESHOLD: status = SERVER_STATUS['WARNING'] if count >= QUEUE_DANGER_THRESHOLD: status = SERVER_STATUS['DANGER'] return { 'label': 'Queued Email', 'status': status, 'info': 'There are currently {0} messages in the mail queue.'.format( count) }
python
def email_queue(): """Checks for emails, that fill up the queue without getting sent.""" status = SERVER_STATUS['OK'] count = Message.objects.exclude(priority=PRIORITY_DEFERRED).filter( when_added__lte=now() - timedelta(minutes=QUEUE_TIMEOUT)).count() if QUEUE_WARNING_THRESHOLD <= count < QUEUE_DANGER_THRESHOLD: status = SERVER_STATUS['WARNING'] if count >= QUEUE_DANGER_THRESHOLD: status = SERVER_STATUS['DANGER'] return { 'label': 'Queued Email', 'status': status, 'info': 'There are currently {0} messages in the mail queue.'.format( count) }
[ "def", "email_queue", "(", ")", ":", "status", "=", "SERVER_STATUS", "[", "'OK'", "]", "count", "=", "Message", ".", "objects", ".", "exclude", "(", "priority", "=", "PRIORITY_DEFERRED", ")", ".", "filter", "(", "when_added__lte", "=", "now", "(", ")", "-", "timedelta", "(", "minutes", "=", "QUEUE_TIMEOUT", ")", ")", ".", "count", "(", ")", "if", "QUEUE_WARNING_THRESHOLD", "<=", "count", "<", "QUEUE_DANGER_THRESHOLD", ":", "status", "=", "SERVER_STATUS", "[", "'WARNING'", "]", "if", "count", ">=", "QUEUE_DANGER_THRESHOLD", ":", "status", "=", "SERVER_STATUS", "[", "'DANGER'", "]", "return", "{", "'label'", ":", "'Queued Email'", ",", "'status'", ":", "status", ",", "'info'", ":", "'There are currently {0} messages in the mail queue.'", ".", "format", "(", "count", ")", "}" ]
Checks for emails, that fill up the queue without getting sent.
[ "Checks", "for", "emails", "that", "fill", "up", "the", "queue", "without", "getting", "sent", "." ]
c996245b5a8e8f6f590251a8757adcca79d114e3
https://github.com/bitlabstudio/django-server-guardian-api/blob/c996245b5a8e8f6f590251a8757adcca79d114e3/server_guardian_api/processors/django_mailer.py#L39-L55
242,726
AoiKuiyuyou/AoikI18n
src/aoiki18n/aoiki18n_.py
I18n.yaml_force_unicode
def yaml_force_unicode(): """ Force pyyaml to return unicode values. """ #/ ## modified from |http://stackoverflow.com/a/2967461| if sys.version_info[0] == 2: def construct_func(self, node): return self.construct_scalar(node) yaml.Loader.add_constructor(U('tag:yaml.org,2002:str'), construct_func) yaml.SafeLoader.add_constructor(U('tag:yaml.org,2002:str'), construct_func)
python
def yaml_force_unicode(): """ Force pyyaml to return unicode values. """ #/ ## modified from |http://stackoverflow.com/a/2967461| if sys.version_info[0] == 2: def construct_func(self, node): return self.construct_scalar(node) yaml.Loader.add_constructor(U('tag:yaml.org,2002:str'), construct_func) yaml.SafeLoader.add_constructor(U('tag:yaml.org,2002:str'), construct_func)
[ "def", "yaml_force_unicode", "(", ")", ":", "#/", "## modified from |http://stackoverflow.com/a/2967461|", "if", "sys", ".", "version_info", "[", "0", "]", "==", "2", ":", "def", "construct_func", "(", "self", ",", "node", ")", ":", "return", "self", ".", "construct_scalar", "(", "node", ")", "yaml", ".", "Loader", ".", "add_constructor", "(", "U", "(", "'tag:yaml.org,2002:str'", ")", ",", "construct_func", ")", "yaml", ".", "SafeLoader", ".", "add_constructor", "(", "U", "(", "'tag:yaml.org,2002:str'", ")", ",", "construct_func", ")" ]
Force pyyaml to return unicode values.
[ "Force", "pyyaml", "to", "return", "unicode", "values", "." ]
8d60ea6a2be24e533a9cf92b433a8cfdb67f813e
https://github.com/AoiKuiyuyou/AoikI18n/blob/8d60ea6a2be24e533a9cf92b433a8cfdb67f813e/src/aoiki18n/aoiki18n_.py#L78-L88
242,727
AoiKuiyuyou/AoikI18n
src/aoiki18n/aoiki18n_.py
I18n.get_locale_hints
def get_locale_hints(): """ Get a list of locale hints, guessed according to Python's default locale info. """ #/ lang, encoding = locale.getdefaultlocale() ## can both be None #/ if lang and '_' in lang: lang3, _, lang2 = lang.partition('_') else: lang3 = None lang2 = None #/ ll_s = [encoding, lang, lang2, lang3] ## Encoding comes before lang intentionally, e.g. ## lang |en_US| with encoding |cp936|, |cp936| takes priority. #/ ll_s_unique = [] for ll in ll_s: if ll: ll = ll.lower() if ll not in ll_s_unique: ll_s_unique.append(ll) #/ return ll_s_unique
python
def get_locale_hints(): """ Get a list of locale hints, guessed according to Python's default locale info. """ #/ lang, encoding = locale.getdefaultlocale() ## can both be None #/ if lang and '_' in lang: lang3, _, lang2 = lang.partition('_') else: lang3 = None lang2 = None #/ ll_s = [encoding, lang, lang2, lang3] ## Encoding comes before lang intentionally, e.g. ## lang |en_US| with encoding |cp936|, |cp936| takes priority. #/ ll_s_unique = [] for ll in ll_s: if ll: ll = ll.lower() if ll not in ll_s_unique: ll_s_unique.append(ll) #/ return ll_s_unique
[ "def", "get_locale_hints", "(", ")", ":", "#/", "lang", ",", "encoding", "=", "locale", ".", "getdefaultlocale", "(", ")", "## can both be None", "#/", "if", "lang", "and", "'_'", "in", "lang", ":", "lang3", ",", "_", ",", "lang2", "=", "lang", ".", "partition", "(", "'_'", ")", "else", ":", "lang3", "=", "None", "lang2", "=", "None", "#/", "ll_s", "=", "[", "encoding", ",", "lang", ",", "lang2", ",", "lang3", "]", "## Encoding comes before lang intentionally, e.g.", "## lang |en_US| with encoding |cp936|, |cp936| takes priority.", "#/", "ll_s_unique", "=", "[", "]", "for", "ll", "in", "ll_s", ":", "if", "ll", ":", "ll", "=", "ll", ".", "lower", "(", ")", "if", "ll", "not", "in", "ll_s_unique", ":", "ll_s_unique", ".", "append", "(", "ll", ")", "#/", "return", "ll_s_unique" ]
Get a list of locale hints, guessed according to Python's default locale info.
[ "Get", "a", "list", "of", "locale", "hints", "guessed", "according", "to", "Python", "s", "default", "locale", "info", "." ]
8d60ea6a2be24e533a9cf92b433a8cfdb67f813e
https://github.com/AoiKuiyuyou/AoikI18n/blob/8d60ea6a2be24e533a9cf92b433a8cfdb67f813e/src/aoiki18n/aoiki18n_.py#L91-L123
242,728
AoiKuiyuyou/AoikI18n
src/aoiki18n/aoiki18n_.py
I18n.get_locale_choices
def get_locale_choices(locale_dir): """ Get a list of locale file names in the given locale dir. """ #/ file_name_s = os.listdir(locale_dir) #/ choice_s = [] for file_name in file_name_s: if file_name.endswith(I18n.TT_FILE_EXT_STXT): file_name_noext, _ = os.path.splitext(file_name) if file_name_noext: choice_s.append(file_name_noext) #/ choice_s = sorted(choice_s) #/ return choice_s
python
def get_locale_choices(locale_dir): """ Get a list of locale file names in the given locale dir. """ #/ file_name_s = os.listdir(locale_dir) #/ choice_s = [] for file_name in file_name_s: if file_name.endswith(I18n.TT_FILE_EXT_STXT): file_name_noext, _ = os.path.splitext(file_name) if file_name_noext: choice_s.append(file_name_noext) #/ choice_s = sorted(choice_s) #/ return choice_s
[ "def", "get_locale_choices", "(", "locale_dir", ")", ":", "#/", "file_name_s", "=", "os", ".", "listdir", "(", "locale_dir", ")", "#/", "choice_s", "=", "[", "]", "for", "file_name", "in", "file_name_s", ":", "if", "file_name", ".", "endswith", "(", "I18n", ".", "TT_FILE_EXT_STXT", ")", ":", "file_name_noext", ",", "_", "=", "os", ".", "path", ".", "splitext", "(", "file_name", ")", "if", "file_name_noext", ":", "choice_s", ".", "append", "(", "file_name_noext", ")", "#/", "choice_s", "=", "sorted", "(", "choice_s", ")", "#/", "return", "choice_s" ]
Get a list of locale file names in the given locale dir.
[ "Get", "a", "list", "of", "locale", "file", "names", "in", "the", "given", "locale", "dir", "." ]
8d60ea6a2be24e533a9cf92b433a8cfdb67f813e
https://github.com/AoiKuiyuyou/AoikI18n/blob/8d60ea6a2be24e533a9cf92b433a8cfdb67f813e/src/aoiki18n/aoiki18n_.py#L126-L146
242,729
Infinidat/infi.recipe.console_scripts
src/infi/recipe/console_scripts/egg.py
Eggs.working_set
def working_set(self, extra=()): """Separate method to just get the working set This is intended for reuse by similar recipes. """ options = self.options b_options = self.buildout['buildout'] # Backward compat. :( options['executable'] = sys.executable distributions = [ r.strip() for r in options.get('eggs', self.name).split('\n') if r.strip()] orig_distributions = distributions[:] distributions.extend(extra) if self.buildout['buildout'].get('offline') == 'true': ws = zc.buildout.easy_install.working_set( distributions, [options['develop-eggs-directory'], options['eggs-directory']] ) else: ws = zc.buildout.easy_install.install( distributions, options['eggs-directory'], links=self.links, index=self.index, path=[options['develop-eggs-directory']], newest=self.buildout['buildout'].get('newest') == 'true', allow_hosts=self.allow_hosts) return orig_distributions, ws
python
def working_set(self, extra=()): """Separate method to just get the working set This is intended for reuse by similar recipes. """ options = self.options b_options = self.buildout['buildout'] # Backward compat. :( options['executable'] = sys.executable distributions = [ r.strip() for r in options.get('eggs', self.name).split('\n') if r.strip()] orig_distributions = distributions[:] distributions.extend(extra) if self.buildout['buildout'].get('offline') == 'true': ws = zc.buildout.easy_install.working_set( distributions, [options['develop-eggs-directory'], options['eggs-directory']] ) else: ws = zc.buildout.easy_install.install( distributions, options['eggs-directory'], links=self.links, index=self.index, path=[options['develop-eggs-directory']], newest=self.buildout['buildout'].get('newest') == 'true', allow_hosts=self.allow_hosts) return orig_distributions, ws
[ "def", "working_set", "(", "self", ",", "extra", "=", "(", ")", ")", ":", "options", "=", "self", ".", "options", "b_options", "=", "self", ".", "buildout", "[", "'buildout'", "]", "# Backward compat. :(", "options", "[", "'executable'", "]", "=", "sys", ".", "executable", "distributions", "=", "[", "r", ".", "strip", "(", ")", "for", "r", "in", "options", ".", "get", "(", "'eggs'", ",", "self", ".", "name", ")", ".", "split", "(", "'\\n'", ")", "if", "r", ".", "strip", "(", ")", "]", "orig_distributions", "=", "distributions", "[", ":", "]", "distributions", ".", "extend", "(", "extra", ")", "if", "self", ".", "buildout", "[", "'buildout'", "]", ".", "get", "(", "'offline'", ")", "==", "'true'", ":", "ws", "=", "zc", ".", "buildout", ".", "easy_install", ".", "working_set", "(", "distributions", ",", "[", "options", "[", "'develop-eggs-directory'", "]", ",", "options", "[", "'eggs-directory'", "]", "]", ")", "else", ":", "ws", "=", "zc", ".", "buildout", ".", "easy_install", ".", "install", "(", "distributions", ",", "options", "[", "'eggs-directory'", "]", ",", "links", "=", "self", ".", "links", ",", "index", "=", "self", ".", "index", ",", "path", "=", "[", "options", "[", "'develop-eggs-directory'", "]", "]", ",", "newest", "=", "self", ".", "buildout", "[", "'buildout'", "]", ".", "get", "(", "'newest'", ")", "==", "'true'", ",", "allow_hosts", "=", "self", ".", "allow_hosts", ")", "return", "orig_distributions", ",", "ws" ]
Separate method to just get the working set This is intended for reuse by similar recipes.
[ "Separate", "method", "to", "just", "get", "the", "working", "set" ]
7beab59537654ee475527dbbd59b0aa49348ebd3
https://github.com/Infinidat/infi.recipe.console_scripts/blob/7beab59537654ee475527dbbd59b0aa49348ebd3/src/infi/recipe/console_scripts/egg.py#L38-L70
242,730
storax/upme
src/upme/main.py
get_required
def get_required(dist): """Return a set with all distributions that are required of dist This also includes subdependencies and the given distribution. :param dist: the distribution to query. Can also be the name of the distribution :type dist: :class:`pkg_resources.Distribution` | str :returns: a list of distributions that are required including the given one :rtype: set of :class:`pkg_resources.Distribution` :raises: class:`pkg_resources.DistributionNotFound` """ d = pkg_resources.get_distribution(dist) reqs = set(d.requires()) allds = set([d]) while reqs: newreqs = set([]) for r in reqs: dr = pkg_resources.get_distribution(r) allds.add(dr) newreqs = newreqs & set(dr.requires()) reqs = newreqs - reqs return allds
python
def get_required(dist): """Return a set with all distributions that are required of dist This also includes subdependencies and the given distribution. :param dist: the distribution to query. Can also be the name of the distribution :type dist: :class:`pkg_resources.Distribution` | str :returns: a list of distributions that are required including the given one :rtype: set of :class:`pkg_resources.Distribution` :raises: class:`pkg_resources.DistributionNotFound` """ d = pkg_resources.get_distribution(dist) reqs = set(d.requires()) allds = set([d]) while reqs: newreqs = set([]) for r in reqs: dr = pkg_resources.get_distribution(r) allds.add(dr) newreqs = newreqs & set(dr.requires()) reqs = newreqs - reqs return allds
[ "def", "get_required", "(", "dist", ")", ":", "d", "=", "pkg_resources", ".", "get_distribution", "(", "dist", ")", "reqs", "=", "set", "(", "d", ".", "requires", "(", ")", ")", "allds", "=", "set", "(", "[", "d", "]", ")", "while", "reqs", ":", "newreqs", "=", "set", "(", "[", "]", ")", "for", "r", "in", "reqs", ":", "dr", "=", "pkg_resources", ".", "get_distribution", "(", "r", ")", "allds", ".", "add", "(", "dr", ")", "newreqs", "=", "newreqs", "&", "set", "(", "dr", ".", "requires", "(", ")", ")", "reqs", "=", "newreqs", "-", "reqs", "return", "allds" ]
Return a set with all distributions that are required of dist This also includes subdependencies and the given distribution. :param dist: the distribution to query. Can also be the name of the distribution :type dist: :class:`pkg_resources.Distribution` | str :returns: a list of distributions that are required including the given one :rtype: set of :class:`pkg_resources.Distribution` :raises: class:`pkg_resources.DistributionNotFound`
[ "Return", "a", "set", "with", "all", "distributions", "that", "are", "required", "of", "dist" ]
41c2d91f922691e31ff940f33b755d2cb64dfef8
https://github.com/storax/upme/blob/41c2d91f922691e31ff940f33b755d2cb64dfef8/src/upme/main.py#L8-L29
242,731
storax/upme
src/upme/main.py
is_outdated
def is_outdated(dist, dep=False): """Return a dict with outdated distributions If the given distribution has dependencies, they are checked as well. :param dist: a distribution to check :type dist: :class:`pkg_resources.Distribution` | str :param dep: If True, also return all outdated dependencies. If False, only check given dist. :type dep: :returns: dictionary of all distributions that are outdated and are either dependencies of the given distribution or the distribution itself. Keys are the outdated distributions and values are the newest parsed versions. :rtype: dict of :class:`pkg_resources.Distribution` :raises: class:`pkg_resources.DistributionNotFound` """ if dep: required = get_required(dist) else: required = set([dist]) ListCommand = pip.commands['list'] lc = ListCommand() options, args = lc.parse_args(['--outdated']) outdated = {} for d, raw_ver, parsed_ver in lc.find_packages_latests_versions(options): for r in required: if d.project_name == r.project_name and parsed_ver > r.parsed_version: outdated[r] = parsed_ver return outdated
python
def is_outdated(dist, dep=False): """Return a dict with outdated distributions If the given distribution has dependencies, they are checked as well. :param dist: a distribution to check :type dist: :class:`pkg_resources.Distribution` | str :param dep: If True, also return all outdated dependencies. If False, only check given dist. :type dep: :returns: dictionary of all distributions that are outdated and are either dependencies of the given distribution or the distribution itself. Keys are the outdated distributions and values are the newest parsed versions. :rtype: dict of :class:`pkg_resources.Distribution` :raises: class:`pkg_resources.DistributionNotFound` """ if dep: required = get_required(dist) else: required = set([dist]) ListCommand = pip.commands['list'] lc = ListCommand() options, args = lc.parse_args(['--outdated']) outdated = {} for d, raw_ver, parsed_ver in lc.find_packages_latests_versions(options): for r in required: if d.project_name == r.project_name and parsed_ver > r.parsed_version: outdated[r] = parsed_ver return outdated
[ "def", "is_outdated", "(", "dist", ",", "dep", "=", "False", ")", ":", "if", "dep", ":", "required", "=", "get_required", "(", "dist", ")", "else", ":", "required", "=", "set", "(", "[", "dist", "]", ")", "ListCommand", "=", "pip", ".", "commands", "[", "'list'", "]", "lc", "=", "ListCommand", "(", ")", "options", ",", "args", "=", "lc", ".", "parse_args", "(", "[", "'--outdated'", "]", ")", "outdated", "=", "{", "}", "for", "d", ",", "raw_ver", ",", "parsed_ver", "in", "lc", ".", "find_packages_latests_versions", "(", "options", ")", ":", "for", "r", "in", "required", ":", "if", "d", ".", "project_name", "==", "r", ".", "project_name", "and", "parsed_ver", ">", "r", ".", "parsed_version", ":", "outdated", "[", "r", "]", "=", "parsed_ver", "return", "outdated" ]
Return a dict with outdated distributions If the given distribution has dependencies, they are checked as well. :param dist: a distribution to check :type dist: :class:`pkg_resources.Distribution` | str :param dep: If True, also return all outdated dependencies. If False, only check given dist. :type dep: :returns: dictionary of all distributions that are outdated and are either dependencies of the given distribution or the distribution itself. Keys are the outdated distributions and values are the newest parsed versions. :rtype: dict of :class:`pkg_resources.Distribution` :raises: class:`pkg_resources.DistributionNotFound`
[ "Return", "a", "dict", "with", "outdated", "distributions" ]
41c2d91f922691e31ff940f33b755d2cb64dfef8
https://github.com/storax/upme/blob/41c2d91f922691e31ff940f33b755d2cb64dfef8/src/upme/main.py#L32-L60
242,732
storax/upme
src/upme/main.py
update
def update(dist, args=None): """Update the given distribution and all of its dependencies :param dist: the distribution to check :type dist: :class:`pkg_resources.Distribution` | str :param args: extra arguments for the install command. this is somewhat equivalent to: pip install -U <dist> args :type args: list :returns: None :rtype: None :raises: class:`pkg_resources.DistributionNotFound` """ dist = pkg_resources.get_distribution(dist) InstallCommand = pip.commands['install'] ic = InstallCommand() iargs = ['-U', dist.project_name] if args: iargs.extend(args) ic.main(iargs)
python
def update(dist, args=None): """Update the given distribution and all of its dependencies :param dist: the distribution to check :type dist: :class:`pkg_resources.Distribution` | str :param args: extra arguments for the install command. this is somewhat equivalent to: pip install -U <dist> args :type args: list :returns: None :rtype: None :raises: class:`pkg_resources.DistributionNotFound` """ dist = pkg_resources.get_distribution(dist) InstallCommand = pip.commands['install'] ic = InstallCommand() iargs = ['-U', dist.project_name] if args: iargs.extend(args) ic.main(iargs)
[ "def", "update", "(", "dist", ",", "args", "=", "None", ")", ":", "dist", "=", "pkg_resources", ".", "get_distribution", "(", "dist", ")", "InstallCommand", "=", "pip", ".", "commands", "[", "'install'", "]", "ic", "=", "InstallCommand", "(", ")", "iargs", "=", "[", "'-U'", ",", "dist", ".", "project_name", "]", "if", "args", ":", "iargs", ".", "extend", "(", "args", ")", "ic", ".", "main", "(", "iargs", ")" ]
Update the given distribution and all of its dependencies :param dist: the distribution to check :type dist: :class:`pkg_resources.Distribution` | str :param args: extra arguments for the install command. this is somewhat equivalent to: pip install -U <dist> args :type args: list :returns: None :rtype: None :raises: class:`pkg_resources.DistributionNotFound`
[ "Update", "the", "given", "distribution", "and", "all", "of", "its", "dependencies" ]
41c2d91f922691e31ff940f33b755d2cb64dfef8
https://github.com/storax/upme/blob/41c2d91f922691e31ff940f33b755d2cb64dfef8/src/upme/main.py#L63-L81
242,733
storax/upme
src/upme/main.py
restart
def restart(): """Restart the application the same way it was started :returns: None :rtype: None :raises: SystemExit """ python = sys.executable os.execl(python, python, * sys.argv)
python
def restart(): """Restart the application the same way it was started :returns: None :rtype: None :raises: SystemExit """ python = sys.executable os.execl(python, python, * sys.argv)
[ "def", "restart", "(", ")", ":", "python", "=", "sys", ".", "executable", "os", ".", "execl", "(", "python", ",", "python", ",", "*", "sys", ".", "argv", ")" ]
Restart the application the same way it was started :returns: None :rtype: None :raises: SystemExit
[ "Restart", "the", "application", "the", "same", "way", "it", "was", "started" ]
41c2d91f922691e31ff940f33b755d2cb64dfef8
https://github.com/storax/upme/blob/41c2d91f922691e31ff940f33b755d2cb64dfef8/src/upme/main.py#L84-L92
242,734
fr33jc/bang
bang/providers/openstack/__init__.py
authenticated
def authenticated(f): """Decorator that authenticates to Keystone automatically.""" @wraps(f) def new_f(self, *args, **kwargs): if not self.nova_client.client.auth_token: self.authenticate() return f(self, *args, **kwargs) return new_f
python
def authenticated(f): """Decorator that authenticates to Keystone automatically.""" @wraps(f) def new_f(self, *args, **kwargs): if not self.nova_client.client.auth_token: self.authenticate() return f(self, *args, **kwargs) return new_f
[ "def", "authenticated", "(", "f", ")", ":", "@", "wraps", "(", "f", ")", "def", "new_f", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "not", "self", ".", "nova_client", ".", "client", ".", "auth_token", ":", "self", ".", "authenticate", "(", ")", "return", "f", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", "return", "new_f" ]
Decorator that authenticates to Keystone automatically.
[ "Decorator", "that", "authenticates", "to", "Keystone", "automatically", "." ]
8f000713f88d2a9a8c1193b63ca10a6578560c16
https://github.com/fr33jc/bang/blob/8f000713f88d2a9a8c1193b63ca10a6578560c16/bang/providers/openstack/__init__.py#L438-L445
242,735
thisfred/val
val/tp.py
_translate_struct
def _translate_struct(inner_dict): """Translate a teleport Struct into a val subschema.""" try: optional = inner_dict['optional'].items() required = inner_dict['required'].items() except KeyError as ex: raise DeserializationError("Missing key: {}".format(ex)) except AttributeError as ex: raise DeserializationError( "Invalid Structure: {}".format(inner_dict)) val_dict = {k: _translate(v) for k, v in required} val_dict.update({Optional(k): _translate(v) for k, v in optional}) return val_dict
python
def _translate_struct(inner_dict): """Translate a teleport Struct into a val subschema.""" try: optional = inner_dict['optional'].items() required = inner_dict['required'].items() except KeyError as ex: raise DeserializationError("Missing key: {}".format(ex)) except AttributeError as ex: raise DeserializationError( "Invalid Structure: {}".format(inner_dict)) val_dict = {k: _translate(v) for k, v in required} val_dict.update({Optional(k): _translate(v) for k, v in optional}) return val_dict
[ "def", "_translate_struct", "(", "inner_dict", ")", ":", "try", ":", "optional", "=", "inner_dict", "[", "'optional'", "]", ".", "items", "(", ")", "required", "=", "inner_dict", "[", "'required'", "]", ".", "items", "(", ")", "except", "KeyError", "as", "ex", ":", "raise", "DeserializationError", "(", "\"Missing key: {}\"", ".", "format", "(", "ex", ")", ")", "except", "AttributeError", "as", "ex", ":", "raise", "DeserializationError", "(", "\"Invalid Structure: {}\"", ".", "format", "(", "inner_dict", ")", ")", "val_dict", "=", "{", "k", ":", "_translate", "(", "v", ")", "for", "k", ",", "v", "in", "required", "}", "val_dict", ".", "update", "(", "{", "Optional", "(", "k", ")", ":", "_translate", "(", "v", ")", "for", "k", ",", "v", "in", "optional", "}", ")", "return", "val_dict" ]
Translate a teleport Struct into a val subschema.
[ "Translate", "a", "teleport", "Struct", "into", "a", "val", "subschema", "." ]
ba022e0c6c47acb3b8a45e7c44c84cc0f495c41c
https://github.com/thisfred/val/blob/ba022e0c6c47acb3b8a45e7c44c84cc0f495c41c/val/tp.py#L76-L89
242,736
thisfred/val
val/tp.py
_translate_composite
def _translate_composite(teleport_value): """Translate a composite teleport value into a val subschema.""" for key in ("Array", "Map", "Struct"): value = teleport_value.get(key) if value is None: continue return COMPOSITES[key](value) raise DeserializationError( "Could not interpret %r as a teleport schema." % teleport_value)
python
def _translate_composite(teleport_value): """Translate a composite teleport value into a val subschema.""" for key in ("Array", "Map", "Struct"): value = teleport_value.get(key) if value is None: continue return COMPOSITES[key](value) raise DeserializationError( "Could not interpret %r as a teleport schema." % teleport_value)
[ "def", "_translate_composite", "(", "teleport_value", ")", ":", "for", "key", "in", "(", "\"Array\"", ",", "\"Map\"", ",", "\"Struct\"", ")", ":", "value", "=", "teleport_value", ".", "get", "(", "key", ")", "if", "value", "is", "None", ":", "continue", "return", "COMPOSITES", "[", "key", "]", "(", "value", ")", "raise", "DeserializationError", "(", "\"Could not interpret %r as a teleport schema.\"", "%", "teleport_value", ")" ]
Translate a composite teleport value into a val subschema.
[ "Translate", "a", "composite", "teleport", "value", "into", "a", "val", "subschema", "." ]
ba022e0c6c47acb3b8a45e7c44c84cc0f495c41c
https://github.com/thisfred/val/blob/ba022e0c6c47acb3b8a45e7c44c84cc0f495c41c/val/tp.py#L98-L107
242,737
thisfred/val
val/tp.py
_translate
def _translate(teleport_value): """Translate a teleport value in to a val subschema.""" if isinstance(teleport_value, dict): return _translate_composite(teleport_value) if teleport_value in PRIMITIVES: return PRIMITIVES[teleport_value] raise DeserializationError( "Could not interpret %r as a teleport schema." % teleport_value)
python
def _translate(teleport_value): """Translate a teleport value in to a val subschema.""" if isinstance(teleport_value, dict): return _translate_composite(teleport_value) if teleport_value in PRIMITIVES: return PRIMITIVES[teleport_value] raise DeserializationError( "Could not interpret %r as a teleport schema." % teleport_value)
[ "def", "_translate", "(", "teleport_value", ")", ":", "if", "isinstance", "(", "teleport_value", ",", "dict", ")", ":", "return", "_translate_composite", "(", "teleport_value", ")", "if", "teleport_value", "in", "PRIMITIVES", ":", "return", "PRIMITIVES", "[", "teleport_value", "]", "raise", "DeserializationError", "(", "\"Could not interpret %r as a teleport schema.\"", "%", "teleport_value", ")" ]
Translate a teleport value in to a val subschema.
[ "Translate", "a", "teleport", "value", "in", "to", "a", "val", "subschema", "." ]
ba022e0c6c47acb3b8a45e7c44c84cc0f495c41c
https://github.com/thisfred/val/blob/ba022e0c6c47acb3b8a45e7c44c84cc0f495c41c/val/tp.py#L110-L119
242,738
thisfred/val
val/tp.py
to_val
def to_val(teleport_schema): """Convert a parsed teleport schema to a val schema.""" translated = _translate(teleport_schema) if isinstance(translated, BaseSchema): return translated return Schema(translated)
python
def to_val(teleport_schema): """Convert a parsed teleport schema to a val schema.""" translated = _translate(teleport_schema) if isinstance(translated, BaseSchema): return translated return Schema(translated)
[ "def", "to_val", "(", "teleport_schema", ")", ":", "translated", "=", "_translate", "(", "teleport_schema", ")", "if", "isinstance", "(", "translated", ",", "BaseSchema", ")", ":", "return", "translated", "return", "Schema", "(", "translated", ")" ]
Convert a parsed teleport schema to a val schema.
[ "Convert", "a", "parsed", "teleport", "schema", "to", "a", "val", "schema", "." ]
ba022e0c6c47acb3b8a45e7c44c84cc0f495c41c
https://github.com/thisfred/val/blob/ba022e0c6c47acb3b8a45e7c44c84cc0f495c41c/val/tp.py#L122-L128
242,739
thisfred/val
val/tp.py
_dict_to_teleport
def _dict_to_teleport(dict_value): """Convert a val schema dictionary to teleport.""" if len(dict_value) == 1: for key, value in dict_value.items(): if key is str: return {"Map": from_val(value)} optional = {} required = {} for key, value in dict_value.items(): if isinstance(key, Optional): optional[key.value] = from_val(value) else: required[key] = from_val(value) return {"Struct": { "required": required, "optional": optional}}
python
def _dict_to_teleport(dict_value): """Convert a val schema dictionary to teleport.""" if len(dict_value) == 1: for key, value in dict_value.items(): if key is str: return {"Map": from_val(value)} optional = {} required = {} for key, value in dict_value.items(): if isinstance(key, Optional): optional[key.value] = from_val(value) else: required[key] = from_val(value) return {"Struct": { "required": required, "optional": optional}}
[ "def", "_dict_to_teleport", "(", "dict_value", ")", ":", "if", "len", "(", "dict_value", ")", "==", "1", ":", "for", "key", ",", "value", "in", "dict_value", ".", "items", "(", ")", ":", "if", "key", "is", "str", ":", "return", "{", "\"Map\"", ":", "from_val", "(", "value", ")", "}", "optional", "=", "{", "}", "required", "=", "{", "}", "for", "key", ",", "value", "in", "dict_value", ".", "items", "(", ")", ":", "if", "isinstance", "(", "key", ",", "Optional", ")", ":", "optional", "[", "key", ".", "value", "]", "=", "from_val", "(", "value", ")", "else", ":", "required", "[", "key", "]", "=", "from_val", "(", "value", ")", "return", "{", "\"Struct\"", ":", "{", "\"required\"", ":", "required", ",", "\"optional\"", ":", "optional", "}", "}" ]
Convert a val schema dictionary to teleport.
[ "Convert", "a", "val", "schema", "dictionary", "to", "teleport", "." ]
ba022e0c6c47acb3b8a45e7c44c84cc0f495c41c
https://github.com/thisfred/val/blob/ba022e0c6c47acb3b8a45e7c44c84cc0f495c41c/val/tp.py#L131-L148
242,740
thisfred/val
val/tp.py
from_val
def from_val(val_schema): """Serialize a val schema to teleport.""" definition = getattr(val_schema, "definition", val_schema) if isinstance( val_schema, BaseSchema) else val_schema if isinstance(definition, dict): return _dict_to_teleport(definition) if isinstance(definition, list): # teleport only supports a single type by default if len(definition) == 1: return {"Array": from_val(definition[0])} if definition in VAL_PRIMITIVES: return VAL_PRIMITIVES[definition] raise SerializationError( "Serializing %r not (yet) supported." % definition)
python
def from_val(val_schema): """Serialize a val schema to teleport.""" definition = getattr(val_schema, "definition", val_schema) if isinstance( val_schema, BaseSchema) else val_schema if isinstance(definition, dict): return _dict_to_teleport(definition) if isinstance(definition, list): # teleport only supports a single type by default if len(definition) == 1: return {"Array": from_val(definition[0])} if definition in VAL_PRIMITIVES: return VAL_PRIMITIVES[definition] raise SerializationError( "Serializing %r not (yet) supported." % definition)
[ "def", "from_val", "(", "val_schema", ")", ":", "definition", "=", "getattr", "(", "val_schema", ",", "\"definition\"", ",", "val_schema", ")", "if", "isinstance", "(", "val_schema", ",", "BaseSchema", ")", "else", "val_schema", "if", "isinstance", "(", "definition", ",", "dict", ")", ":", "return", "_dict_to_teleport", "(", "definition", ")", "if", "isinstance", "(", "definition", ",", "list", ")", ":", "# teleport only supports a single type by default", "if", "len", "(", "definition", ")", "==", "1", ":", "return", "{", "\"Array\"", ":", "from_val", "(", "definition", "[", "0", "]", ")", "}", "if", "definition", "in", "VAL_PRIMITIVES", ":", "return", "VAL_PRIMITIVES", "[", "definition", "]", "raise", "SerializationError", "(", "\"Serializing %r not (yet) supported.\"", "%", "definition", ")" ]
Serialize a val schema to teleport.
[ "Serialize", "a", "val", "schema", "to", "teleport", "." ]
ba022e0c6c47acb3b8a45e7c44c84cc0f495c41c
https://github.com/thisfred/val/blob/ba022e0c6c47acb3b8a45e7c44c84cc0f495c41c/val/tp.py#L151-L167
242,741
thisfred/val
val/tp.py
document
def document(schema): """Print a documented teleport version of the schema.""" teleport_schema = from_val(schema) return json.dumps(teleport_schema, sort_keys=True, indent=2)
python
def document(schema): """Print a documented teleport version of the schema.""" teleport_schema = from_val(schema) return json.dumps(teleport_schema, sort_keys=True, indent=2)
[ "def", "document", "(", "schema", ")", ":", "teleport_schema", "=", "from_val", "(", "schema", ")", "return", "json", ".", "dumps", "(", "teleport_schema", ",", "sort_keys", "=", "True", ",", "indent", "=", "2", ")" ]
Print a documented teleport version of the schema.
[ "Print", "a", "documented", "teleport", "version", "of", "the", "schema", "." ]
ba022e0c6c47acb3b8a45e7c44c84cc0f495c41c
https://github.com/thisfred/val/blob/ba022e0c6c47acb3b8a45e7c44c84cc0f495c41c/val/tp.py#L170-L173
242,742
diffeo/rejester
rejester/_registry.py
nice_identifier
def nice_identifier(): 'do not use uuid.uuid4, because it can block' big = reduce(mul, struct.unpack('<LLLL', os.urandom(16)), 1) big = big % 2**128 return uuid.UUID(int=big).hex
python
def nice_identifier(): 'do not use uuid.uuid4, because it can block' big = reduce(mul, struct.unpack('<LLLL', os.urandom(16)), 1) big = big % 2**128 return uuid.UUID(int=big).hex
[ "def", "nice_identifier", "(", ")", ":", "big", "=", "reduce", "(", "mul", ",", "struct", ".", "unpack", "(", "'<LLLL'", ",", "os", ".", "urandom", "(", "16", ")", ")", ",", "1", ")", "big", "=", "big", "%", "2", "**", "128", "return", "uuid", ".", "UUID", "(", "int", "=", "big", ")", ".", "hex" ]
do not use uuid.uuid4, because it can block
[ "do", "not", "use", "uuid", ".", "uuid4", "because", "it", "can", "block" ]
5438a4a18be2801d7826c46e2079ba9639d2ecb4
https://github.com/diffeo/rejester/blob/5438a4a18be2801d7826c46e2079ba9639d2ecb4/rejester/_registry.py#L30-L34
242,743
diffeo/rejester
rejester/_registry.py
Registry._acquire_lock
def _acquire_lock(self, identifier, atime=30, ltime=5): '''Acquire a lock for a given identifier. If the lock cannot be obtained immediately, keep trying at random intervals, up to 3 seconds, until `atime` has passed. Once the lock has been obtained, continue to hold it for `ltime`. :param str identifier: lock token to write :param int atime: maximum time (in seconds) to acquire lock :param int ltime: maximum time (in seconds) to own lock :return: `identifier` if the lock was obtained, :const:`False` otherwise ''' conn = redis.Redis(connection_pool=self.pool) end = time.time() + atime while end > time.time(): if conn.set(self._lock_name, identifier, ex=ltime, nx=True): # logger.debug("won lock %s" % self._lock_name) return identifier sleep_time = random.uniform(0, 3) time.sleep(sleep_time) logger.warn('failed to acquire lock %s for %f seconds', self._lock_name, atime) return False
python
def _acquire_lock(self, identifier, atime=30, ltime=5): '''Acquire a lock for a given identifier. If the lock cannot be obtained immediately, keep trying at random intervals, up to 3 seconds, until `atime` has passed. Once the lock has been obtained, continue to hold it for `ltime`. :param str identifier: lock token to write :param int atime: maximum time (in seconds) to acquire lock :param int ltime: maximum time (in seconds) to own lock :return: `identifier` if the lock was obtained, :const:`False` otherwise ''' conn = redis.Redis(connection_pool=self.pool) end = time.time() + atime while end > time.time(): if conn.set(self._lock_name, identifier, ex=ltime, nx=True): # logger.debug("won lock %s" % self._lock_name) return identifier sleep_time = random.uniform(0, 3) time.sleep(sleep_time) logger.warn('failed to acquire lock %s for %f seconds', self._lock_name, atime) return False
[ "def", "_acquire_lock", "(", "self", ",", "identifier", ",", "atime", "=", "30", ",", "ltime", "=", "5", ")", ":", "conn", "=", "redis", ".", "Redis", "(", "connection_pool", "=", "self", ".", "pool", ")", "end", "=", "time", ".", "time", "(", ")", "+", "atime", "while", "end", ">", "time", ".", "time", "(", ")", ":", "if", "conn", ".", "set", "(", "self", ".", "_lock_name", ",", "identifier", ",", "ex", "=", "ltime", ",", "nx", "=", "True", ")", ":", "# logger.debug(\"won lock %s\" % self._lock_name)", "return", "identifier", "sleep_time", "=", "random", ".", "uniform", "(", "0", ",", "3", ")", "time", ".", "sleep", "(", "sleep_time", ")", "logger", ".", "warn", "(", "'failed to acquire lock %s for %f seconds'", ",", "self", ".", "_lock_name", ",", "atime", ")", "return", "False" ]
Acquire a lock for a given identifier. If the lock cannot be obtained immediately, keep trying at random intervals, up to 3 seconds, until `atime` has passed. Once the lock has been obtained, continue to hold it for `ltime`. :param str identifier: lock token to write :param int atime: maximum time (in seconds) to acquire lock :param int ltime: maximum time (in seconds) to own lock :return: `identifier` if the lock was obtained, :const:`False` otherwise
[ "Acquire", "a", "lock", "for", "a", "given", "identifier", "." ]
5438a4a18be2801d7826c46e2079ba9639d2ecb4
https://github.com/diffeo/rejester/blob/5438a4a18be2801d7826c46e2079ba9639d2ecb4/rejester/_registry.py#L104-L129
242,744
diffeo/rejester
rejester/_registry.py
Registry.re_acquire_lock
def re_acquire_lock(self, ltime=5): '''Re-acquire the lock. You must already own the lock; this is best called from within a :meth:`lock` block. :param int ltime: maximum time (in seconds) to own lock :return: the session lock identifier :raise rejester.exceptions.EnvironmentError: if we didn't already own the lock ''' conn = redis.Redis(connection_pool=self.pool) script = conn.register_script(''' if redis.call("get", KEYS[1]) == ARGV[1] then return redis.call("expire", KEYS[1], ARGV[2]) else return -1 end ''') ret = script(keys=[self._lock_name], args=[self._session_lock_identifier, ltime]) if ret != 1: raise EnvironmentError('failed to re-acquire lock') # logger.debug('re-acquired lock %s', self._lock_name) return self._session_lock_identifier
python
def re_acquire_lock(self, ltime=5): '''Re-acquire the lock. You must already own the lock; this is best called from within a :meth:`lock` block. :param int ltime: maximum time (in seconds) to own lock :return: the session lock identifier :raise rejester.exceptions.EnvironmentError: if we didn't already own the lock ''' conn = redis.Redis(connection_pool=self.pool) script = conn.register_script(''' if redis.call("get", KEYS[1]) == ARGV[1] then return redis.call("expire", KEYS[1], ARGV[2]) else return -1 end ''') ret = script(keys=[self._lock_name], args=[self._session_lock_identifier, ltime]) if ret != 1: raise EnvironmentError('failed to re-acquire lock') # logger.debug('re-acquired lock %s', self._lock_name) return self._session_lock_identifier
[ "def", "re_acquire_lock", "(", "self", ",", "ltime", "=", "5", ")", ":", "conn", "=", "redis", ".", "Redis", "(", "connection_pool", "=", "self", ".", "pool", ")", "script", "=", "conn", ".", "register_script", "(", "'''\n if redis.call(\"get\", KEYS[1]) == ARGV[1]\n then\n return redis.call(\"expire\", KEYS[1], ARGV[2])\n else\n return -1\n end\n '''", ")", "ret", "=", "script", "(", "keys", "=", "[", "self", ".", "_lock_name", "]", ",", "args", "=", "[", "self", ".", "_session_lock_identifier", ",", "ltime", "]", ")", "if", "ret", "!=", "1", ":", "raise", "EnvironmentError", "(", "'failed to re-acquire lock'", ")", "# logger.debug('re-acquired lock %s', self._lock_name)", "return", "self", ".", "_session_lock_identifier" ]
Re-acquire the lock. You must already own the lock; this is best called from within a :meth:`lock` block. :param int ltime: maximum time (in seconds) to own lock :return: the session lock identifier :raise rejester.exceptions.EnvironmentError: if we didn't already own the lock
[ "Re", "-", "acquire", "the", "lock", "." ]
5438a4a18be2801d7826c46e2079ba9639d2ecb4
https://github.com/diffeo/rejester/blob/5438a4a18be2801d7826c46e2079ba9639d2ecb4/rejester/_registry.py#L131-L158
242,745
diffeo/rejester
rejester/_registry.py
Registry.lock
def lock(self, atime=30, ltime=5, identifier=None): '''Context manager to acquire the namespace global lock. This is typically used for multi-step registry operations, such as a read-modify-write sequence:: with registry.lock() as session: d = session.get('dict', 'key') del d['traceback'] session.set('dict', 'key', d) Callers may provide their own `identifier`; if they do, they must ensure that it is reasonably unique (e.g., a UUID). Using a stored worker ID that is traceable back to the lock holder is a good practice. :param int atime: maximum time (in seconds) to acquire lock :param int ltime: maximum time (in seconds) to own lock :param str identifier: worker-unique identifier for the lock ''' if identifier is None: identifier = nice_identifier() if self._acquire_lock(identifier, atime, ltime) != identifier: raise LockError("could not acquire lock") try: self._session_lock_identifier = identifier yield self finally: self._release_lock(identifier) self._session_lock_identifier = None
python
def lock(self, atime=30, ltime=5, identifier=None): '''Context manager to acquire the namespace global lock. This is typically used for multi-step registry operations, such as a read-modify-write sequence:: with registry.lock() as session: d = session.get('dict', 'key') del d['traceback'] session.set('dict', 'key', d) Callers may provide their own `identifier`; if they do, they must ensure that it is reasonably unique (e.g., a UUID). Using a stored worker ID that is traceable back to the lock holder is a good practice. :param int atime: maximum time (in seconds) to acquire lock :param int ltime: maximum time (in seconds) to own lock :param str identifier: worker-unique identifier for the lock ''' if identifier is None: identifier = nice_identifier() if self._acquire_lock(identifier, atime, ltime) != identifier: raise LockError("could not acquire lock") try: self._session_lock_identifier = identifier yield self finally: self._release_lock(identifier) self._session_lock_identifier = None
[ "def", "lock", "(", "self", ",", "atime", "=", "30", ",", "ltime", "=", "5", ",", "identifier", "=", "None", ")", ":", "if", "identifier", "is", "None", ":", "identifier", "=", "nice_identifier", "(", ")", "if", "self", ".", "_acquire_lock", "(", "identifier", ",", "atime", ",", "ltime", ")", "!=", "identifier", ":", "raise", "LockError", "(", "\"could not acquire lock\"", ")", "try", ":", "self", ".", "_session_lock_identifier", "=", "identifier", "yield", "self", "finally", ":", "self", ".", "_release_lock", "(", "identifier", ")", "self", ".", "_session_lock_identifier", "=", "None" ]
Context manager to acquire the namespace global lock. This is typically used for multi-step registry operations, such as a read-modify-write sequence:: with registry.lock() as session: d = session.get('dict', 'key') del d['traceback'] session.set('dict', 'key', d) Callers may provide their own `identifier`; if they do, they must ensure that it is reasonably unique (e.g., a UUID). Using a stored worker ID that is traceable back to the lock holder is a good practice. :param int atime: maximum time (in seconds) to acquire lock :param int ltime: maximum time (in seconds) to own lock :param str identifier: worker-unique identifier for the lock
[ "Context", "manager", "to", "acquire", "the", "namespace", "global", "lock", "." ]
5438a4a18be2801d7826c46e2079ba9639d2ecb4
https://github.com/diffeo/rejester/blob/5438a4a18be2801d7826c46e2079ba9639d2ecb4/rejester/_registry.py#L186-L216
242,746
diffeo/rejester
rejester/_registry.py
Registry.read_lock
def read_lock(self): '''Find out who currently owns the namespace global lock. This is purely a diagnostic tool. If you are trying to get the global lock, it is better to just call :meth:`lock`, which will atomically get the lock if possible and retry. :return: session identifier of the lock holder, or :const:`None` ''' return redis.Redis(connection_pool=self.pool).get(self._lock_name)
python
def read_lock(self): '''Find out who currently owns the namespace global lock. This is purely a diagnostic tool. If you are trying to get the global lock, it is better to just call :meth:`lock`, which will atomically get the lock if possible and retry. :return: session identifier of the lock holder, or :const:`None` ''' return redis.Redis(connection_pool=self.pool).get(self._lock_name)
[ "def", "read_lock", "(", "self", ")", ":", "return", "redis", ".", "Redis", "(", "connection_pool", "=", "self", ".", "pool", ")", ".", "get", "(", "self", ".", "_lock_name", ")" ]
Find out who currently owns the namespace global lock. This is purely a diagnostic tool. If you are trying to get the global lock, it is better to just call :meth:`lock`, which will atomically get the lock if possible and retry. :return: session identifier of the lock holder, or :const:`None`
[ "Find", "out", "who", "currently", "owns", "the", "namespace", "global", "lock", "." ]
5438a4a18be2801d7826c46e2079ba9639d2ecb4
https://github.com/diffeo/rejester/blob/5438a4a18be2801d7826c46e2079ba9639d2ecb4/rejester/_registry.py#L218-L228
242,747
diffeo/rejester
rejester/_registry.py
Registry.force_clear_lock
def force_clear_lock(self): '''Kick out whoever currently owns the namespace global lock. This is intended as purely a last-resort tool. If another process has managed to get the global lock for a very long time, or if it requested the lock with a long expiration and then crashed, this can make the system functional again. If the original lock holder is still alive, its session calls may fail with exceptions. ''' return redis.Redis(connection_pool=self.pool).delete(self._lock_name)
python
def force_clear_lock(self): '''Kick out whoever currently owns the namespace global lock. This is intended as purely a last-resort tool. If another process has managed to get the global lock for a very long time, or if it requested the lock with a long expiration and then crashed, this can make the system functional again. If the original lock holder is still alive, its session calls may fail with exceptions. ''' return redis.Redis(connection_pool=self.pool).delete(self._lock_name)
[ "def", "force_clear_lock", "(", "self", ")", ":", "return", "redis", ".", "Redis", "(", "connection_pool", "=", "self", ".", "pool", ")", ".", "delete", "(", "self", ".", "_lock_name", ")" ]
Kick out whoever currently owns the namespace global lock. This is intended as purely a last-resort tool. If another process has managed to get the global lock for a very long time, or if it requested the lock with a long expiration and then crashed, this can make the system functional again. If the original lock holder is still alive, its session calls may fail with exceptions.
[ "Kick", "out", "whoever", "currently", "owns", "the", "namespace", "global", "lock", "." ]
5438a4a18be2801d7826c46e2079ba9639d2ecb4
https://github.com/diffeo/rejester/blob/5438a4a18be2801d7826c46e2079ba9639d2ecb4/rejester/_registry.py#L230-L241
242,748
diffeo/rejester
rejester/_registry.py
Registry.update
def update(self, dict_name, mapping=None, priorities=None, expire=None, locks=None): '''Add mapping to a dictionary, replacing previous values Can be called with only dict_name and expire to refresh the expiration time. NB: locks are only enforced if present, so nothing prevents another caller from coming in an modifying data without using locks. :param mapping: a dict of keys and values to update in dict_name. Must be specified if priorities is specified. :param priorities: a dict with the same keys as those in mapping that provides a numerical value indicating the priority to assign to that key. Default sets 0 for all keys. :param int expire: if specified, then dict_name will be set to expire in that many seconds. :param locks: a dict with the same keys as those in the mapping. Before making any particular update, this function checks if a key is present in a 'locks' table for this dict, and if so, then its value must match the value provided in the input locks dict for that key. If not, then the value provided in the locks dict is inserted into the 'locks' table. If the locks parameter is None, then no lock checking is performed. ''' if self._session_lock_identifier is None: raise ProgrammerError('must acquire lock first') if priorities is None: ## set all priorities to zero priorities = defaultdict(int) if locks is None: ## set all locks to None locks = defaultdict(lambda: '') if not (expire is None or isinstance(expire, int)): raise ProgrammerError('expire must be int or unspecified') conn = redis.Redis(connection_pool=self.pool) script = conn.register_script(''' if redis.call("get", KEYS[1]) == ARGV[1] then for i = 3, #ARGV, 4 do if ARGV[i+3] ~= 'j:""' then local curr_lock = redis.call("hget", KEYS[4], ARGV[i]) if curr_lock and curr_lock ~= ARGV[i+3] then return {-1, ARGV[i], curr_lock, ARGV[i+3]} end redis.call("hset", KEYS[4], ARGV[i], ARGV[i+3]) end end for i = 3, #ARGV, 4 do redis.call("hset", KEYS[2], ARGV[i], ARGV[i+1]) redis.call("zadd", KEYS[3], ARGV[i+2], ARGV[i]) end if tonumber(ARGV[2]) ~= nil then redis.call("expire", KEYS[2], ARGV[2]) redis.call("expire", KEYS[3], ARGV[2]) end return {1, 0} else -- ERROR: No longer own the lock return {0, 0} end ''') dict_name = self._namespace(dict_name) if mapping is None: mapping = {} items = [] ## This flattens the dictionary into a list for key, value in mapping.iteritems(): items.append(self._encode(key)) items.append(self._encode(value)) items.append(priorities[key]) items.append(self._encode(locks[key])) #logger.debug('update %r %r', dict_name, items) res = script(keys=[self._lock_name, dict_name, dict_name + 'keys', dict_name + '_locks'], args=[self._session_lock_identifier, expire] + items) if res[0] == 0: raise EnvironmentError( 'Unable to add items to %s in registry' % dict_name) elif res[0] == -1: raise EnvironmentError( 'lost lock on key=%r owned by %r not %r in %s' % (self._decode(res[1]), res[2], res[3], dict_name))
python
def update(self, dict_name, mapping=None, priorities=None, expire=None, locks=None): '''Add mapping to a dictionary, replacing previous values Can be called with only dict_name and expire to refresh the expiration time. NB: locks are only enforced if present, so nothing prevents another caller from coming in an modifying data without using locks. :param mapping: a dict of keys and values to update in dict_name. Must be specified if priorities is specified. :param priorities: a dict with the same keys as those in mapping that provides a numerical value indicating the priority to assign to that key. Default sets 0 for all keys. :param int expire: if specified, then dict_name will be set to expire in that many seconds. :param locks: a dict with the same keys as those in the mapping. Before making any particular update, this function checks if a key is present in a 'locks' table for this dict, and if so, then its value must match the value provided in the input locks dict for that key. If not, then the value provided in the locks dict is inserted into the 'locks' table. If the locks parameter is None, then no lock checking is performed. ''' if self._session_lock_identifier is None: raise ProgrammerError('must acquire lock first') if priorities is None: ## set all priorities to zero priorities = defaultdict(int) if locks is None: ## set all locks to None locks = defaultdict(lambda: '') if not (expire is None or isinstance(expire, int)): raise ProgrammerError('expire must be int or unspecified') conn = redis.Redis(connection_pool=self.pool) script = conn.register_script(''' if redis.call("get", KEYS[1]) == ARGV[1] then for i = 3, #ARGV, 4 do if ARGV[i+3] ~= 'j:""' then local curr_lock = redis.call("hget", KEYS[4], ARGV[i]) if curr_lock and curr_lock ~= ARGV[i+3] then return {-1, ARGV[i], curr_lock, ARGV[i+3]} end redis.call("hset", KEYS[4], ARGV[i], ARGV[i+3]) end end for i = 3, #ARGV, 4 do redis.call("hset", KEYS[2], ARGV[i], ARGV[i+1]) redis.call("zadd", KEYS[3], ARGV[i+2], ARGV[i]) end if tonumber(ARGV[2]) ~= nil then redis.call("expire", KEYS[2], ARGV[2]) redis.call("expire", KEYS[3], ARGV[2]) end return {1, 0} else -- ERROR: No longer own the lock return {0, 0} end ''') dict_name = self._namespace(dict_name) if mapping is None: mapping = {} items = [] ## This flattens the dictionary into a list for key, value in mapping.iteritems(): items.append(self._encode(key)) items.append(self._encode(value)) items.append(priorities[key]) items.append(self._encode(locks[key])) #logger.debug('update %r %r', dict_name, items) res = script(keys=[self._lock_name, dict_name, dict_name + 'keys', dict_name + '_locks'], args=[self._session_lock_identifier, expire] + items) if res[0] == 0: raise EnvironmentError( 'Unable to add items to %s in registry' % dict_name) elif res[0] == -1: raise EnvironmentError( 'lost lock on key=%r owned by %r not %r in %s' % (self._decode(res[1]), res[2], res[3], dict_name))
[ "def", "update", "(", "self", ",", "dict_name", ",", "mapping", "=", "None", ",", "priorities", "=", "None", ",", "expire", "=", "None", ",", "locks", "=", "None", ")", ":", "if", "self", ".", "_session_lock_identifier", "is", "None", ":", "raise", "ProgrammerError", "(", "'must acquire lock first'", ")", "if", "priorities", "is", "None", ":", "## set all priorities to zero", "priorities", "=", "defaultdict", "(", "int", ")", "if", "locks", "is", "None", ":", "## set all locks to None", "locks", "=", "defaultdict", "(", "lambda", ":", "''", ")", "if", "not", "(", "expire", "is", "None", "or", "isinstance", "(", "expire", ",", "int", ")", ")", ":", "raise", "ProgrammerError", "(", "'expire must be int or unspecified'", ")", "conn", "=", "redis", ".", "Redis", "(", "connection_pool", "=", "self", ".", "pool", ")", "script", "=", "conn", ".", "register_script", "(", "'''\n if redis.call(\"get\", KEYS[1]) == ARGV[1]\n then\n for i = 3, #ARGV, 4 do\n if ARGV[i+3] ~= 'j:\"\"' then\n local curr_lock = redis.call(\"hget\", KEYS[4], ARGV[i])\n if curr_lock and curr_lock ~= ARGV[i+3] then\n return {-1, ARGV[i], curr_lock, ARGV[i+3]}\n end\n redis.call(\"hset\", KEYS[4], ARGV[i], ARGV[i+3])\n end\n end\n for i = 3, #ARGV, 4 do\n redis.call(\"hset\", KEYS[2], ARGV[i], ARGV[i+1])\n redis.call(\"zadd\", KEYS[3], ARGV[i+2], ARGV[i])\n end\n if tonumber(ARGV[2]) ~= nil then\n redis.call(\"expire\", KEYS[2], ARGV[2])\n redis.call(\"expire\", KEYS[3], ARGV[2])\n end\n return {1, 0}\n else\n -- ERROR: No longer own the lock\n return {0, 0}\n end\n '''", ")", "dict_name", "=", "self", ".", "_namespace", "(", "dict_name", ")", "if", "mapping", "is", "None", ":", "mapping", "=", "{", "}", "items", "=", "[", "]", "## This flattens the dictionary into a list", "for", "key", ",", "value", "in", "mapping", ".", "iteritems", "(", ")", ":", "items", ".", "append", "(", "self", ".", "_encode", "(", "key", ")", ")", "items", ".", "append", "(", "self", ".", "_encode", "(", "value", ")", ")", "items", ".", "append", "(", "priorities", "[", "key", "]", ")", "items", ".", "append", "(", "self", ".", "_encode", "(", "locks", "[", "key", "]", ")", ")", "#logger.debug('update %r %r', dict_name, items)", "res", "=", "script", "(", "keys", "=", "[", "self", ".", "_lock_name", ",", "dict_name", ",", "dict_name", "+", "'keys'", ",", "dict_name", "+", "'_locks'", "]", ",", "args", "=", "[", "self", ".", "_session_lock_identifier", ",", "expire", "]", "+", "items", ")", "if", "res", "[", "0", "]", "==", "0", ":", "raise", "EnvironmentError", "(", "'Unable to add items to %s in registry'", "%", "dict_name", ")", "elif", "res", "[", "0", "]", "==", "-", "1", ":", "raise", "EnvironmentError", "(", "'lost lock on key=%r owned by %r not %r in %s'", "%", "(", "self", ".", "_decode", "(", "res", "[", "1", "]", ")", ",", "res", "[", "2", "]", ",", "res", "[", "3", "]", ",", "dict_name", ")", ")" ]
Add mapping to a dictionary, replacing previous values Can be called with only dict_name and expire to refresh the expiration time. NB: locks are only enforced if present, so nothing prevents another caller from coming in an modifying data without using locks. :param mapping: a dict of keys and values to update in dict_name. Must be specified if priorities is specified. :param priorities: a dict with the same keys as those in mapping that provides a numerical value indicating the priority to assign to that key. Default sets 0 for all keys. :param int expire: if specified, then dict_name will be set to expire in that many seconds. :param locks: a dict with the same keys as those in the mapping. Before making any particular update, this function checks if a key is present in a 'locks' table for this dict, and if so, then its value must match the value provided in the input locks dict for that key. If not, then the value provided in the locks dict is inserted into the 'locks' table. If the locks parameter is None, then no lock checking is performed.
[ "Add", "mapping", "to", "a", "dictionary", "replacing", "previous", "values" ]
5438a4a18be2801d7826c46e2079ba9639d2ecb4
https://github.com/diffeo/rejester/blob/5438a4a18be2801d7826c46e2079ba9639d2ecb4/rejester/_registry.py#L263-L350
242,749
diffeo/rejester
rejester/_registry.py
Registry.reset_priorities
def reset_priorities(self, dict_name, priority): '''set all priorities in dict_name to priority :type priority: float or int ''' if self._session_lock_identifier is None: raise ProgrammerError('must acquire lock first') ## see comment above for script in update conn = redis.Redis(connection_pool=self.pool) script = conn.register_script(''' if redis.call("get", KEYS[1]) == ARGV[1] then local keys = redis.call('ZRANGE', KEYS[2], 0, -1) for i, next_key in ipairs(keys) do redis.call("zadd", KEYS[2], ARGV[2], next_key) end return 1 else -- ERROR: No longer own the lock return 0 end ''') dict_name = self._namespace(dict_name) res = script(keys=[self._lock_name, dict_name + 'keys'], args=[self._session_lock_identifier, priority]) if not res: # We either lost the lock or something else went wrong raise EnvironmentError( 'Unable to add items to %s in registry' % dict_name)
python
def reset_priorities(self, dict_name, priority): '''set all priorities in dict_name to priority :type priority: float or int ''' if self._session_lock_identifier is None: raise ProgrammerError('must acquire lock first') ## see comment above for script in update conn = redis.Redis(connection_pool=self.pool) script = conn.register_script(''' if redis.call("get", KEYS[1]) == ARGV[1] then local keys = redis.call('ZRANGE', KEYS[2], 0, -1) for i, next_key in ipairs(keys) do redis.call("zadd", KEYS[2], ARGV[2], next_key) end return 1 else -- ERROR: No longer own the lock return 0 end ''') dict_name = self._namespace(dict_name) res = script(keys=[self._lock_name, dict_name + 'keys'], args=[self._session_lock_identifier, priority]) if not res: # We either lost the lock or something else went wrong raise EnvironmentError( 'Unable to add items to %s in registry' % dict_name)
[ "def", "reset_priorities", "(", "self", ",", "dict_name", ",", "priority", ")", ":", "if", "self", ".", "_session_lock_identifier", "is", "None", ":", "raise", "ProgrammerError", "(", "'must acquire lock first'", ")", "## see comment above for script in update", "conn", "=", "redis", ".", "Redis", "(", "connection_pool", "=", "self", ".", "pool", ")", "script", "=", "conn", ".", "register_script", "(", "'''\n if redis.call(\"get\", KEYS[1]) == ARGV[1]\n then\n local keys = redis.call('ZRANGE', KEYS[2], 0, -1)\n for i, next_key in ipairs(keys) do\n redis.call(\"zadd\", KEYS[2], ARGV[2], next_key)\n end\n return 1\n else\n -- ERROR: No longer own the lock\n return 0\n end\n '''", ")", "dict_name", "=", "self", ".", "_namespace", "(", "dict_name", ")", "res", "=", "script", "(", "keys", "=", "[", "self", ".", "_lock_name", ",", "dict_name", "+", "'keys'", "]", ",", "args", "=", "[", "self", ".", "_session_lock_identifier", ",", "priority", "]", ")", "if", "not", "res", ":", "# We either lost the lock or something else went wrong", "raise", "EnvironmentError", "(", "'Unable to add items to %s in registry'", "%", "dict_name", ")" ]
set all priorities in dict_name to priority :type priority: float or int
[ "set", "all", "priorities", "in", "dict_name", "to", "priority" ]
5438a4a18be2801d7826c46e2079ba9639d2ecb4
https://github.com/diffeo/rejester/blob/5438a4a18be2801d7826c46e2079ba9639d2ecb4/rejester/_registry.py#L353-L383
242,750
diffeo/rejester
rejester/_registry.py
Registry.popitem
def popitem(self, dict_name, priority_min='-inf', priority_max='+inf'): '''Select an item and remove it. The item comes from `dict_name`, and has the lowest score at least `priority_min` and at most `priority_max`. If some item is found, remove it from `dict_name` and return it. This runs as a single atomic operation but still requires a session lock. :param str dict_name: source dictionary :param float priority_min: lowest score :param float priority_max: highest score :return: pair of (key, value) if an item was popped, or :const:`None` ''' if self._session_lock_identifier is None: raise ProgrammerError('must acquire lock first') conn = redis.Redis(connection_pool=self.pool) script = conn.register_script(''' if redis.call("get", KEYS[1]) == ARGV[1] then -- remove next item of dict_name local next_key, next_priority = redis.call("zrangebyscore", KEYS[3], ARGV[2], ARGV[3], "WITHSCORES", "LIMIT", 0, 1)[1] if not next_key then return {} end redis.call("zrem", KEYS[3], next_key) local next_val = redis.call("hget", KEYS[2], next_key) -- zrem removed it from list, so also remove from hash redis.call("hdel", KEYS[2], next_key) return {next_key, next_val} else -- ERROR: No longer own the lock return -1 end ''') dict_name = self._namespace(dict_name) key_value = script(keys=[self._lock_name, dict_name, dict_name + "keys"], args=[self._session_lock_identifier, priority_min, priority_max]) if key_value == -1: raise KeyError( 'Registry failed to return an item from %s' % dict_name) if key_value == []: return None return self._decode(key_value[0]), self._decode(key_value[1])
python
def popitem(self, dict_name, priority_min='-inf', priority_max='+inf'): '''Select an item and remove it. The item comes from `dict_name`, and has the lowest score at least `priority_min` and at most `priority_max`. If some item is found, remove it from `dict_name` and return it. This runs as a single atomic operation but still requires a session lock. :param str dict_name: source dictionary :param float priority_min: lowest score :param float priority_max: highest score :return: pair of (key, value) if an item was popped, or :const:`None` ''' if self._session_lock_identifier is None: raise ProgrammerError('must acquire lock first') conn = redis.Redis(connection_pool=self.pool) script = conn.register_script(''' if redis.call("get", KEYS[1]) == ARGV[1] then -- remove next item of dict_name local next_key, next_priority = redis.call("zrangebyscore", KEYS[3], ARGV[2], ARGV[3], "WITHSCORES", "LIMIT", 0, 1)[1] if not next_key then return {} end redis.call("zrem", KEYS[3], next_key) local next_val = redis.call("hget", KEYS[2], next_key) -- zrem removed it from list, so also remove from hash redis.call("hdel", KEYS[2], next_key) return {next_key, next_val} else -- ERROR: No longer own the lock return -1 end ''') dict_name = self._namespace(dict_name) key_value = script(keys=[self._lock_name, dict_name, dict_name + "keys"], args=[self._session_lock_identifier, priority_min, priority_max]) if key_value == -1: raise KeyError( 'Registry failed to return an item from %s' % dict_name) if key_value == []: return None return self._decode(key_value[0]), self._decode(key_value[1])
[ "def", "popitem", "(", "self", ",", "dict_name", ",", "priority_min", "=", "'-inf'", ",", "priority_max", "=", "'+inf'", ")", ":", "if", "self", ".", "_session_lock_identifier", "is", "None", ":", "raise", "ProgrammerError", "(", "'must acquire lock first'", ")", "conn", "=", "redis", ".", "Redis", "(", "connection_pool", "=", "self", ".", "pool", ")", "script", "=", "conn", ".", "register_script", "(", "'''\n if redis.call(\"get\", KEYS[1]) == ARGV[1]\n then\n -- remove next item of dict_name\n local next_key, next_priority = redis.call(\"zrangebyscore\",\n KEYS[3], ARGV[2], ARGV[3], \"WITHSCORES\", \"LIMIT\", 0, 1)[1]\n\n if not next_key then\n return {}\n end\n \n redis.call(\"zrem\", KEYS[3], next_key)\n local next_val = redis.call(\"hget\", KEYS[2], next_key)\n -- zrem removed it from list, so also remove from hash\n redis.call(\"hdel\", KEYS[2], next_key)\n return {next_key, next_val}\n else\n -- ERROR: No longer own the lock\n return -1\n end\n '''", ")", "dict_name", "=", "self", ".", "_namespace", "(", "dict_name", ")", "key_value", "=", "script", "(", "keys", "=", "[", "self", ".", "_lock_name", ",", "dict_name", ",", "dict_name", "+", "\"keys\"", "]", ",", "args", "=", "[", "self", ".", "_session_lock_identifier", ",", "priority_min", ",", "priority_max", "]", ")", "if", "key_value", "==", "-", "1", ":", "raise", "KeyError", "(", "'Registry failed to return an item from %s'", "%", "dict_name", ")", "if", "key_value", "==", "[", "]", ":", "return", "None", "return", "self", ".", "_decode", "(", "key_value", "[", "0", "]", ")", ",", "self", ".", "_decode", "(", "key_value", "[", "1", "]", ")" ]
Select an item and remove it. The item comes from `dict_name`, and has the lowest score at least `priority_min` and at most `priority_max`. If some item is found, remove it from `dict_name` and return it. This runs as a single atomic operation but still requires a session lock. :param str dict_name: source dictionary :param float priority_min: lowest score :param float priority_max: highest score :return: pair of (key, value) if an item was popped, or :const:`None`
[ "Select", "an", "item", "and", "remove", "it", "." ]
5438a4a18be2801d7826c46e2079ba9639d2ecb4
https://github.com/diffeo/rejester/blob/5438a4a18be2801d7826c46e2079ba9639d2ecb4/rejester/_registry.py#L524-L579
242,751
diffeo/rejester
rejester/_registry.py
Registry.popitem_move
def popitem_move(self, from_dict, to_dict, priority_min='-inf', priority_max='+inf'): '''Select an item and move it to another dictionary. The item comes from `from_dict`, and has the lowest score at least `priority_min` and at most `priority_max`. If some item is found, remove it from `from_dict`, add it to `to_dict`, and return it. This runs as a single atomic operation but still requires a session lock. :param str from_dict: source dictionary :param str to_dict: destination dictionary :param float priority_min: lowest score :param float priority_max: highest score :return: pair of (key, value) if an item was moved, or :const:`None` ''' if self._session_lock_identifier is None: raise ProgrammerError('must acquire lock first') conn = redis.Redis(connection_pool=self.pool) script = conn.register_script(''' if redis.call("get", KEYS[1]) == ARGV[1] then -- find the next key and priority local next_items = redis.call("zrangebyscore", KEYS[3], ARGV[2], ARGV[3], "WITHSCORES", "LIMIT", 0, 1) local next_key = next_items[1] local next_priority = next_items[2] if not next_key then return {} end -- remove next item of from_dict redis.call("zrem", KEYS[3], next_key) local next_val = redis.call("hget", KEYS[2], next_key) -- zrem removed it from list, so also remove from hash redis.call("hdel", KEYS[2], next_key) -- put it in to_dict redis.call("hset", KEYS[4], next_key, next_val) redis.call("zadd", KEYS[5], next_priority, next_key) return {next_key, next_val, next_priority} else -- ERROR: No longer own the lock return -1 end ''') key_value = script(keys=[self._lock_name, self._namespace(from_dict), self._namespace(from_dict) + 'keys', self._namespace(to_dict), self._namespace(to_dict) + 'keys'], args=[self._session_lock_identifier, priority_min, priority_max]) if key_value == []: return None if None in key_value or key_value == -1: raise KeyError( 'Registry.popitem_move(%r, %r) --> %r' % (from_dict, to_dict, key_value)) return self._decode(key_value[0]), self._decode(key_value[1])
python
def popitem_move(self, from_dict, to_dict, priority_min='-inf', priority_max='+inf'): '''Select an item and move it to another dictionary. The item comes from `from_dict`, and has the lowest score at least `priority_min` and at most `priority_max`. If some item is found, remove it from `from_dict`, add it to `to_dict`, and return it. This runs as a single atomic operation but still requires a session lock. :param str from_dict: source dictionary :param str to_dict: destination dictionary :param float priority_min: lowest score :param float priority_max: highest score :return: pair of (key, value) if an item was moved, or :const:`None` ''' if self._session_lock_identifier is None: raise ProgrammerError('must acquire lock first') conn = redis.Redis(connection_pool=self.pool) script = conn.register_script(''' if redis.call("get", KEYS[1]) == ARGV[1] then -- find the next key and priority local next_items = redis.call("zrangebyscore", KEYS[3], ARGV[2], ARGV[3], "WITHSCORES", "LIMIT", 0, 1) local next_key = next_items[1] local next_priority = next_items[2] if not next_key then return {} end -- remove next item of from_dict redis.call("zrem", KEYS[3], next_key) local next_val = redis.call("hget", KEYS[2], next_key) -- zrem removed it from list, so also remove from hash redis.call("hdel", KEYS[2], next_key) -- put it in to_dict redis.call("hset", KEYS[4], next_key, next_val) redis.call("zadd", KEYS[5], next_priority, next_key) return {next_key, next_val, next_priority} else -- ERROR: No longer own the lock return -1 end ''') key_value = script(keys=[self._lock_name, self._namespace(from_dict), self._namespace(from_dict) + 'keys', self._namespace(to_dict), self._namespace(to_dict) + 'keys'], args=[self._session_lock_identifier, priority_min, priority_max]) if key_value == []: return None if None in key_value or key_value == -1: raise KeyError( 'Registry.popitem_move(%r, %r) --> %r' % (from_dict, to_dict, key_value)) return self._decode(key_value[0]), self._decode(key_value[1])
[ "def", "popitem_move", "(", "self", ",", "from_dict", ",", "to_dict", ",", "priority_min", "=", "'-inf'", ",", "priority_max", "=", "'+inf'", ")", ":", "if", "self", ".", "_session_lock_identifier", "is", "None", ":", "raise", "ProgrammerError", "(", "'must acquire lock first'", ")", "conn", "=", "redis", ".", "Redis", "(", "connection_pool", "=", "self", ".", "pool", ")", "script", "=", "conn", ".", "register_script", "(", "'''\n if redis.call(\"get\", KEYS[1]) == ARGV[1]\n then\n -- find the next key and priority\n local next_items = redis.call(\"zrangebyscore\", KEYS[3],\n ARGV[2], ARGV[3], \"WITHSCORES\", \"LIMIT\", 0, 1)\n local next_key = next_items[1]\n local next_priority = next_items[2]\n \n if not next_key then\n return {}\n end\n\n -- remove next item of from_dict\n redis.call(\"zrem\", KEYS[3], next_key)\n\n local next_val = redis.call(\"hget\", KEYS[2], next_key)\n -- zrem removed it from list, so also remove from hash\n redis.call(\"hdel\", KEYS[2], next_key)\n\n -- put it in to_dict\n redis.call(\"hset\", KEYS[4], next_key, next_val)\n redis.call(\"zadd\", KEYS[5], next_priority, next_key)\n\n return {next_key, next_val, next_priority}\n else\n -- ERROR: No longer own the lock\n return -1\n end\n '''", ")", "key_value", "=", "script", "(", "keys", "=", "[", "self", ".", "_lock_name", ",", "self", ".", "_namespace", "(", "from_dict", ")", ",", "self", ".", "_namespace", "(", "from_dict", ")", "+", "'keys'", ",", "self", ".", "_namespace", "(", "to_dict", ")", ",", "self", ".", "_namespace", "(", "to_dict", ")", "+", "'keys'", "]", ",", "args", "=", "[", "self", ".", "_session_lock_identifier", ",", "priority_min", ",", "priority_max", "]", ")", "if", "key_value", "==", "[", "]", ":", "return", "None", "if", "None", "in", "key_value", "or", "key_value", "==", "-", "1", ":", "raise", "KeyError", "(", "'Registry.popitem_move(%r, %r) --> %r'", "%", "(", "from_dict", ",", "to_dict", ",", "key_value", ")", ")", "return", "self", ".", "_decode", "(", "key_value", "[", "0", "]", ")", ",", "self", ".", "_decode", "(", "key_value", "[", "1", "]", ")" ]
Select an item and move it to another dictionary. The item comes from `from_dict`, and has the lowest score at least `priority_min` and at most `priority_max`. If some item is found, remove it from `from_dict`, add it to `to_dict`, and return it. This runs as a single atomic operation but still requires a session lock. :param str from_dict: source dictionary :param str to_dict: destination dictionary :param float priority_min: lowest score :param float priority_max: highest score :return: pair of (key, value) if an item was moved, or :const:`None`
[ "Select", "an", "item", "and", "move", "it", "to", "another", "dictionary", "." ]
5438a4a18be2801d7826c46e2079ba9639d2ecb4
https://github.com/diffeo/rejester/blob/5438a4a18be2801d7826c46e2079ba9639d2ecb4/rejester/_registry.py#L581-L650
242,752
diffeo/rejester
rejester/_registry.py
Registry.move
def move(self, from_dict, to_dict, mapping, priority=None): '''Move keys between dictionaries, possibly with changes. Every key in `mapping` is removed from `from_dict`, and added to `to_dict` with its corresponding value. The priority will be `priority`, if specified, or else its current priority. This operation on its own is atomic and does not require a session lock; however, it does require you to pass in the values, which probably came from a previous query call. If you do not call this with a session lock but some other caller has one, you will get :class:`rejester.LockError`. If you do have a session lock, this will check that you still have it. :param str from_dict: name of original dictionary :param str to_dict: name of target dictionary :param dict mapping: keys to move with new values :param int priority: target priority, or :const:`None` to use existing :raise rejester.LockError: if the session lock timed out :raise rejester.EnvironmentError: if some items didn't move ''' items = [] ## This flattens the dictionary into a list for key, value in mapping.iteritems(): key = self._encode(key) items.append(key) value = self._encode(value) items.append(value) conn = redis.Redis(connection_pool=self.pool) script = conn.register_script(''' local lock_holder = redis.call("get", KEYS[1]) if (not lock_holder) or (lock_holder == ARGV[1]) then local count = 0 for i = 3, #ARGV, 2 do -- find the priority of the item local next_priority = ARGV[2] if next_priority == "" then next_priority = redis.call("zscore", KEYS[3], ARGV[i]) end -- remove item from the sorted set and the real data redis.call("hdel", KEYS[2], ARGV[i]) redis.call("zrem", KEYS[3], ARGV[i]) -- put it in to_dict redis.call("hset", KEYS[4], ARGV[i], ARGV[i+1]) redis.call("zadd", KEYS[5], next_priority, ARGV[i]) count = count + 1 end return count else -- ERROR: No longer own the lock return -1 end ''') # Experimental evidence suggests that redis-py passes # *every* value as a string, maybe unless it's obviously # a number. Empty string is an easy "odd" value to test for. if priority is None: priority = '' num_moved = script(keys=[self._lock_name, self._namespace(from_dict), self._namespace(from_dict) + "keys", self._namespace(to_dict), self._namespace(to_dict) + "keys"], args=[self._session_lock_identifier, priority] + items) if num_moved == -1: raise LockError() if num_moved != len(items) / 2: raise EnvironmentError( 'Registry failed to move all: num_moved = %d != %d len(items)' % (num_moved, len(items)))
python
def move(self, from_dict, to_dict, mapping, priority=None): '''Move keys between dictionaries, possibly with changes. Every key in `mapping` is removed from `from_dict`, and added to `to_dict` with its corresponding value. The priority will be `priority`, if specified, or else its current priority. This operation on its own is atomic and does not require a session lock; however, it does require you to pass in the values, which probably came from a previous query call. If you do not call this with a session lock but some other caller has one, you will get :class:`rejester.LockError`. If you do have a session lock, this will check that you still have it. :param str from_dict: name of original dictionary :param str to_dict: name of target dictionary :param dict mapping: keys to move with new values :param int priority: target priority, or :const:`None` to use existing :raise rejester.LockError: if the session lock timed out :raise rejester.EnvironmentError: if some items didn't move ''' items = [] ## This flattens the dictionary into a list for key, value in mapping.iteritems(): key = self._encode(key) items.append(key) value = self._encode(value) items.append(value) conn = redis.Redis(connection_pool=self.pool) script = conn.register_script(''' local lock_holder = redis.call("get", KEYS[1]) if (not lock_holder) or (lock_holder == ARGV[1]) then local count = 0 for i = 3, #ARGV, 2 do -- find the priority of the item local next_priority = ARGV[2] if next_priority == "" then next_priority = redis.call("zscore", KEYS[3], ARGV[i]) end -- remove item from the sorted set and the real data redis.call("hdel", KEYS[2], ARGV[i]) redis.call("zrem", KEYS[3], ARGV[i]) -- put it in to_dict redis.call("hset", KEYS[4], ARGV[i], ARGV[i+1]) redis.call("zadd", KEYS[5], next_priority, ARGV[i]) count = count + 1 end return count else -- ERROR: No longer own the lock return -1 end ''') # Experimental evidence suggests that redis-py passes # *every* value as a string, maybe unless it's obviously # a number. Empty string is an easy "odd" value to test for. if priority is None: priority = '' num_moved = script(keys=[self._lock_name, self._namespace(from_dict), self._namespace(from_dict) + "keys", self._namespace(to_dict), self._namespace(to_dict) + "keys"], args=[self._session_lock_identifier, priority] + items) if num_moved == -1: raise LockError() if num_moved != len(items) / 2: raise EnvironmentError( 'Registry failed to move all: num_moved = %d != %d len(items)' % (num_moved, len(items)))
[ "def", "move", "(", "self", ",", "from_dict", ",", "to_dict", ",", "mapping", ",", "priority", "=", "None", ")", ":", "items", "=", "[", "]", "## This flattens the dictionary into a list", "for", "key", ",", "value", "in", "mapping", ".", "iteritems", "(", ")", ":", "key", "=", "self", ".", "_encode", "(", "key", ")", "items", ".", "append", "(", "key", ")", "value", "=", "self", ".", "_encode", "(", "value", ")", "items", ".", "append", "(", "value", ")", "conn", "=", "redis", ".", "Redis", "(", "connection_pool", "=", "self", ".", "pool", ")", "script", "=", "conn", ".", "register_script", "(", "'''\n local lock_holder = redis.call(\"get\", KEYS[1])\n if (not lock_holder) or (lock_holder == ARGV[1])\n then\n local count = 0\n for i = 3, #ARGV, 2 do\n -- find the priority of the item\n local next_priority = ARGV[2]\n if next_priority == \"\" then\n next_priority = redis.call(\"zscore\", KEYS[3], ARGV[i])\n end\n -- remove item from the sorted set and the real data\n redis.call(\"hdel\", KEYS[2], ARGV[i])\n redis.call(\"zrem\", KEYS[3], ARGV[i])\n -- put it in to_dict\n redis.call(\"hset\", KEYS[4], ARGV[i], ARGV[i+1])\n redis.call(\"zadd\", KEYS[5], next_priority, ARGV[i])\n count = count + 1\n end\n return count\n else\n -- ERROR: No longer own the lock\n return -1\n end\n '''", ")", "# Experimental evidence suggests that redis-py passes", "# *every* value as a string, maybe unless it's obviously", "# a number. Empty string is an easy \"odd\" value to test for.", "if", "priority", "is", "None", ":", "priority", "=", "''", "num_moved", "=", "script", "(", "keys", "=", "[", "self", ".", "_lock_name", ",", "self", ".", "_namespace", "(", "from_dict", ")", ",", "self", ".", "_namespace", "(", "from_dict", ")", "+", "\"keys\"", ",", "self", ".", "_namespace", "(", "to_dict", ")", ",", "self", ".", "_namespace", "(", "to_dict", ")", "+", "\"keys\"", "]", ",", "args", "=", "[", "self", ".", "_session_lock_identifier", ",", "priority", "]", "+", "items", ")", "if", "num_moved", "==", "-", "1", ":", "raise", "LockError", "(", ")", "if", "num_moved", "!=", "len", "(", "items", ")", "/", "2", ":", "raise", "EnvironmentError", "(", "'Registry failed to move all: num_moved = %d != %d len(items)'", "%", "(", "num_moved", ",", "len", "(", "items", ")", ")", ")" ]
Move keys between dictionaries, possibly with changes. Every key in `mapping` is removed from `from_dict`, and added to `to_dict` with its corresponding value. The priority will be `priority`, if specified, or else its current priority. This operation on its own is atomic and does not require a session lock; however, it does require you to pass in the values, which probably came from a previous query call. If you do not call this with a session lock but some other caller has one, you will get :class:`rejester.LockError`. If you do have a session lock, this will check that you still have it. :param str from_dict: name of original dictionary :param str to_dict: name of target dictionary :param dict mapping: keys to move with new values :param int priority: target priority, or :const:`None` to use existing :raise rejester.LockError: if the session lock timed out :raise rejester.EnvironmentError: if some items didn't move
[ "Move", "keys", "between", "dictionaries", "possibly", "with", "changes", "." ]
5438a4a18be2801d7826c46e2079ba9639d2ecb4
https://github.com/diffeo/rejester/blob/5438a4a18be2801d7826c46e2079ba9639d2ecb4/rejester/_registry.py#L652-L725
242,753
diffeo/rejester
rejester/_registry.py
Registry.move_all
def move_all(self, from_dict, to_dict): '''Move everything from one dictionary to another. This can be expensive if the source dictionary is large. This always requires a session lock. :param str from_dict: source dictionary :param str to_dict: destination dictionary ''' if self._session_lock_identifier is None: raise ProgrammerError('must acquire lock first') conn = redis.Redis(connection_pool=self.pool) script = conn.register_script(''' if redis.call("get", KEYS[1]) == ARGV[1] then local count = 0 local keys = redis.call('ZRANGE', KEYS[3], 0, -1) for i, next_key in ipairs(keys) do -- get the value and priority for this key local next_val = redis.call("hget", KEYS[2], next_key) local next_priority = redis.call("zscore", KEYS[3], next_key) -- remove item of from_dict redis.call("zrem", KEYS[3], next_key) -- also remove from hash redis.call("hdel", KEYS[2], next_key) -- put it in to_dict redis.call("hset", KEYS[4], next_key, next_val) redis.call("zadd", KEYS[5], next_priority, next_key) count = count + 1 end return count else -- ERROR: No longer own the lock return 0 end ''') num_moved = script(keys=[self._lock_name, self._namespace(from_dict), self._namespace(from_dict) + 'keys', self._namespace(to_dict), self._namespace(to_dict) + 'keys'], args=[self._session_lock_identifier]) return num_moved
python
def move_all(self, from_dict, to_dict): '''Move everything from one dictionary to another. This can be expensive if the source dictionary is large. This always requires a session lock. :param str from_dict: source dictionary :param str to_dict: destination dictionary ''' if self._session_lock_identifier is None: raise ProgrammerError('must acquire lock first') conn = redis.Redis(connection_pool=self.pool) script = conn.register_script(''' if redis.call("get", KEYS[1]) == ARGV[1] then local count = 0 local keys = redis.call('ZRANGE', KEYS[3], 0, -1) for i, next_key in ipairs(keys) do -- get the value and priority for this key local next_val = redis.call("hget", KEYS[2], next_key) local next_priority = redis.call("zscore", KEYS[3], next_key) -- remove item of from_dict redis.call("zrem", KEYS[3], next_key) -- also remove from hash redis.call("hdel", KEYS[2], next_key) -- put it in to_dict redis.call("hset", KEYS[4], next_key, next_val) redis.call("zadd", KEYS[5], next_priority, next_key) count = count + 1 end return count else -- ERROR: No longer own the lock return 0 end ''') num_moved = script(keys=[self._lock_name, self._namespace(from_dict), self._namespace(from_dict) + 'keys', self._namespace(to_dict), self._namespace(to_dict) + 'keys'], args=[self._session_lock_identifier]) return num_moved
[ "def", "move_all", "(", "self", ",", "from_dict", ",", "to_dict", ")", ":", "if", "self", ".", "_session_lock_identifier", "is", "None", ":", "raise", "ProgrammerError", "(", "'must acquire lock first'", ")", "conn", "=", "redis", ".", "Redis", "(", "connection_pool", "=", "self", ".", "pool", ")", "script", "=", "conn", ".", "register_script", "(", "'''\n if redis.call(\"get\", KEYS[1]) == ARGV[1]\n then\n local count = 0\n local keys = redis.call('ZRANGE', KEYS[3], 0, -1)\n for i, next_key in ipairs(keys) do\n -- get the value and priority for this key\n local next_val = redis.call(\"hget\", KEYS[2], next_key)\n local next_priority = redis.call(\"zscore\", KEYS[3], next_key)\n -- remove item of from_dict\n redis.call(\"zrem\", KEYS[3], next_key)\n -- also remove from hash\n redis.call(\"hdel\", KEYS[2], next_key)\n -- put it in to_dict\n redis.call(\"hset\", KEYS[4], next_key, next_val)\n redis.call(\"zadd\", KEYS[5], next_priority, next_key)\n count = count + 1\n end\n return count\n else\n -- ERROR: No longer own the lock\n return 0\n end\n '''", ")", "num_moved", "=", "script", "(", "keys", "=", "[", "self", ".", "_lock_name", ",", "self", ".", "_namespace", "(", "from_dict", ")", ",", "self", ".", "_namespace", "(", "from_dict", ")", "+", "'keys'", ",", "self", ".", "_namespace", "(", "to_dict", ")", ",", "self", ".", "_namespace", "(", "to_dict", ")", "+", "'keys'", "]", ",", "args", "=", "[", "self", ".", "_session_lock_identifier", "]", ")", "return", "num_moved" ]
Move everything from one dictionary to another. This can be expensive if the source dictionary is large. This always requires a session lock. :param str from_dict: source dictionary :param str to_dict: destination dictionary
[ "Move", "everything", "from", "one", "dictionary", "to", "another", "." ]
5438a4a18be2801d7826c46e2079ba9639d2ecb4
https://github.com/diffeo/rejester/blob/5438a4a18be2801d7826c46e2079ba9639d2ecb4/rejester/_registry.py#L728-L772
242,754
diffeo/rejester
rejester/_registry.py
Registry.pull
def pull(self, dict_name): '''Get the entire contents of a single dictionary. This operates without a session lock, but is still atomic. In particular this will run even if someone else holds a session lock and you do not. This is only suitable for "small" dictionaries; if you have hundreds of thousands of items or more, consider :meth:`filter` instead to get a subset of a dictionary. :param str dict_name: name of the dictionary to retrieve :return: corresponding Python dictionary ''' dict_name = self._namespace(dict_name) conn = redis.Redis(connection_pool=self.pool) res = conn.hgetall(dict_name) split_res = dict([(self._decode(key), self._decode(value)) for key, value in res.iteritems()]) return split_res
python
def pull(self, dict_name): '''Get the entire contents of a single dictionary. This operates without a session lock, but is still atomic. In particular this will run even if someone else holds a session lock and you do not. This is only suitable for "small" dictionaries; if you have hundreds of thousands of items or more, consider :meth:`filter` instead to get a subset of a dictionary. :param str dict_name: name of the dictionary to retrieve :return: corresponding Python dictionary ''' dict_name = self._namespace(dict_name) conn = redis.Redis(connection_pool=self.pool) res = conn.hgetall(dict_name) split_res = dict([(self._decode(key), self._decode(value)) for key, value in res.iteritems()]) return split_res
[ "def", "pull", "(", "self", ",", "dict_name", ")", ":", "dict_name", "=", "self", ".", "_namespace", "(", "dict_name", ")", "conn", "=", "redis", ".", "Redis", "(", "connection_pool", "=", "self", ".", "pool", ")", "res", "=", "conn", ".", "hgetall", "(", "dict_name", ")", "split_res", "=", "dict", "(", "[", "(", "self", ".", "_decode", "(", "key", ")", ",", "self", ".", "_decode", "(", "value", ")", ")", "for", "key", ",", "value", "in", "res", ".", "iteritems", "(", ")", "]", ")", "return", "split_res" ]
Get the entire contents of a single dictionary. This operates without a session lock, but is still atomic. In particular this will run even if someone else holds a session lock and you do not. This is only suitable for "small" dictionaries; if you have hundreds of thousands of items or more, consider :meth:`filter` instead to get a subset of a dictionary. :param str dict_name: name of the dictionary to retrieve :return: corresponding Python dictionary
[ "Get", "the", "entire", "contents", "of", "a", "single", "dictionary", "." ]
5438a4a18be2801d7826c46e2079ba9639d2ecb4
https://github.com/diffeo/rejester/blob/5438a4a18be2801d7826c46e2079ba9639d2ecb4/rejester/_registry.py#L775-L796
242,755
diffeo/rejester
rejester/_registry.py
Registry.filter
def filter(self, dict_name, priority_min='-inf', priority_max='+inf', start=0, limit=None): '''Get a subset of a dictionary. This retrieves only keys with priority scores greater than or equal to `priority_min` and less than or equal to `priority_max`. Of those keys, it skips the first `start` ones, and then returns at most `limit` keys. With default parameters, this retrieves the entire dictionary, making it a more expensive version of :meth:`pull`. This can be used to limit the dictionary by priority score, for instance using the score as a time stamp and only retrieving values before or after a specific time; or it can be used to get slices of the dictionary if there are too many items to use :meth:`pull`. This is a read-only operation and does not require a session lock, but if this is run in a session context, the lock will be honored. :param str dict_name: name of the dictionary to retrieve :param float priority_min: lowest score to retrieve :param float priority_max: highest score to retrieve :param int start: number of items to skip :param int limit: number of items to retrieve :return: corresponding (partial) Python dictionary :raise rejester.LockError: if the session lock timed out ''' conn = redis.Redis(connection_pool=self.pool) script = conn.register_script(''' if (ARGV[1] == "") or (redis.call("get", KEYS[1]) == ARGV[1]) then -- find all the keys and priorities within range local next_keys = redis.call("zrangebyscore", KEYS[3], ARGV[2], ARGV[3], "limit", ARGV[4], ARGV[5]) if not next_keys[1] then return {} end local t = {} for i = 1, #next_keys do local next_val = redis.call("hget", KEYS[2], next_keys[i]) table.insert(t, next_keys[i]) table.insert(t, next_val) end return t else -- ERROR: No longer own the lock return -1 end ''') if limit is None: limit = -1 res = script(keys=[self._lock_name, self._namespace(dict_name), self._namespace(dict_name) + 'keys'], args=[self._session_lock_identifier or '', priority_min, priority_max, start, limit]) if res == -1: raise LockError() split_res = dict([(self._decode(res[i]), self._decode(res[i+1])) for i in xrange(0, len(res)-1, 2)]) return split_res
python
def filter(self, dict_name, priority_min='-inf', priority_max='+inf', start=0, limit=None): '''Get a subset of a dictionary. This retrieves only keys with priority scores greater than or equal to `priority_min` and less than or equal to `priority_max`. Of those keys, it skips the first `start` ones, and then returns at most `limit` keys. With default parameters, this retrieves the entire dictionary, making it a more expensive version of :meth:`pull`. This can be used to limit the dictionary by priority score, for instance using the score as a time stamp and only retrieving values before or after a specific time; or it can be used to get slices of the dictionary if there are too many items to use :meth:`pull`. This is a read-only operation and does not require a session lock, but if this is run in a session context, the lock will be honored. :param str dict_name: name of the dictionary to retrieve :param float priority_min: lowest score to retrieve :param float priority_max: highest score to retrieve :param int start: number of items to skip :param int limit: number of items to retrieve :return: corresponding (partial) Python dictionary :raise rejester.LockError: if the session lock timed out ''' conn = redis.Redis(connection_pool=self.pool) script = conn.register_script(''' if (ARGV[1] == "") or (redis.call("get", KEYS[1]) == ARGV[1]) then -- find all the keys and priorities within range local next_keys = redis.call("zrangebyscore", KEYS[3], ARGV[2], ARGV[3], "limit", ARGV[4], ARGV[5]) if not next_keys[1] then return {} end local t = {} for i = 1, #next_keys do local next_val = redis.call("hget", KEYS[2], next_keys[i]) table.insert(t, next_keys[i]) table.insert(t, next_val) end return t else -- ERROR: No longer own the lock return -1 end ''') if limit is None: limit = -1 res = script(keys=[self._lock_name, self._namespace(dict_name), self._namespace(dict_name) + 'keys'], args=[self._session_lock_identifier or '', priority_min, priority_max, start, limit]) if res == -1: raise LockError() split_res = dict([(self._decode(res[i]), self._decode(res[i+1])) for i in xrange(0, len(res)-1, 2)]) return split_res
[ "def", "filter", "(", "self", ",", "dict_name", ",", "priority_min", "=", "'-inf'", ",", "priority_max", "=", "'+inf'", ",", "start", "=", "0", ",", "limit", "=", "None", ")", ":", "conn", "=", "redis", ".", "Redis", "(", "connection_pool", "=", "self", ".", "pool", ")", "script", "=", "conn", ".", "register_script", "(", "'''\n if (ARGV[1] == \"\") or (redis.call(\"get\", KEYS[1]) == ARGV[1])\n then\n -- find all the keys and priorities within range\n local next_keys = redis.call(\"zrangebyscore\", KEYS[3],\n ARGV[2], ARGV[3],\n \"limit\", ARGV[4], ARGV[5])\n \n if not next_keys[1] then\n return {}\n end\n\n local t = {}\n for i = 1, #next_keys do\n local next_val = redis.call(\"hget\", KEYS[2], next_keys[i])\n table.insert(t, next_keys[i])\n table.insert(t, next_val)\n end\n\n return t\n else\n -- ERROR: No longer own the lock\n return -1\n end\n '''", ")", "if", "limit", "is", "None", ":", "limit", "=", "-", "1", "res", "=", "script", "(", "keys", "=", "[", "self", ".", "_lock_name", ",", "self", ".", "_namespace", "(", "dict_name", ")", ",", "self", ".", "_namespace", "(", "dict_name", ")", "+", "'keys'", "]", ",", "args", "=", "[", "self", ".", "_session_lock_identifier", "or", "''", ",", "priority_min", ",", "priority_max", ",", "start", ",", "limit", "]", ")", "if", "res", "==", "-", "1", ":", "raise", "LockError", "(", ")", "split_res", "=", "dict", "(", "[", "(", "self", ".", "_decode", "(", "res", "[", "i", "]", ")", ",", "self", ".", "_decode", "(", "res", "[", "i", "+", "1", "]", ")", ")", "for", "i", "in", "xrange", "(", "0", ",", "len", "(", "res", ")", "-", "1", ",", "2", ")", "]", ")", "return", "split_res" ]
Get a subset of a dictionary. This retrieves only keys with priority scores greater than or equal to `priority_min` and less than or equal to `priority_max`. Of those keys, it skips the first `start` ones, and then returns at most `limit` keys. With default parameters, this retrieves the entire dictionary, making it a more expensive version of :meth:`pull`. This can be used to limit the dictionary by priority score, for instance using the score as a time stamp and only retrieving values before or after a specific time; or it can be used to get slices of the dictionary if there are too many items to use :meth:`pull`. This is a read-only operation and does not require a session lock, but if this is run in a session context, the lock will be honored. :param str dict_name: name of the dictionary to retrieve :param float priority_min: lowest score to retrieve :param float priority_max: highest score to retrieve :param int start: number of items to skip :param int limit: number of items to retrieve :return: corresponding (partial) Python dictionary :raise rejester.LockError: if the session lock timed out
[ "Get", "a", "subset", "of", "a", "dictionary", "." ]
5438a4a18be2801d7826c46e2079ba9639d2ecb4
https://github.com/diffeo/rejester/blob/5438a4a18be2801d7826c46e2079ba9639d2ecb4/rejester/_registry.py#L798-L865
242,756
diffeo/rejester
rejester/_registry.py
Registry.set_1to1
def set_1to1(self, dict_name, key1, key2): '''Set two keys to be equal in a 1-to-1 mapping. Within `dict_name`, `key1` is set to `key2`, and `key2` is set to `key1`. This always requires a session lock. :param str dict_name: dictionary to update :param str key1: first key/value :param str key2: second key/value ''' if self._session_lock_identifier is None: raise ProgrammerError('must acquire lock first') conn = redis.Redis(connection_pool=self.pool) script = conn.register_script(''' if redis.call("get", KEYS[1]) == ARGV[1] then redis.call("hset", KEYS[2], ARGV[2], ARGV[3]) redis.call("hset", KEYS[2], ARGV[3], ARGV[2]) else -- ERROR: No longer own the lock return -1 end ''') res = script(keys=[self._lock_name, self._namespace(dict_name)], args=[self._session_lock_identifier, self._encode(key1), self._encode(key2)]) if res == -1: raise EnvironmentError()
python
def set_1to1(self, dict_name, key1, key2): '''Set two keys to be equal in a 1-to-1 mapping. Within `dict_name`, `key1` is set to `key2`, and `key2` is set to `key1`. This always requires a session lock. :param str dict_name: dictionary to update :param str key1: first key/value :param str key2: second key/value ''' if self._session_lock_identifier is None: raise ProgrammerError('must acquire lock first') conn = redis.Redis(connection_pool=self.pool) script = conn.register_script(''' if redis.call("get", KEYS[1]) == ARGV[1] then redis.call("hset", KEYS[2], ARGV[2], ARGV[3]) redis.call("hset", KEYS[2], ARGV[3], ARGV[2]) else -- ERROR: No longer own the lock return -1 end ''') res = script(keys=[self._lock_name, self._namespace(dict_name)], args=[self._session_lock_identifier, self._encode(key1), self._encode(key2)]) if res == -1: raise EnvironmentError()
[ "def", "set_1to1", "(", "self", ",", "dict_name", ",", "key1", ",", "key2", ")", ":", "if", "self", ".", "_session_lock_identifier", "is", "None", ":", "raise", "ProgrammerError", "(", "'must acquire lock first'", ")", "conn", "=", "redis", ".", "Redis", "(", "connection_pool", "=", "self", ".", "pool", ")", "script", "=", "conn", ".", "register_script", "(", "'''\n if redis.call(\"get\", KEYS[1]) == ARGV[1]\n then\n redis.call(\"hset\", KEYS[2], ARGV[2], ARGV[3])\n redis.call(\"hset\", KEYS[2], ARGV[3], ARGV[2])\n else\n -- ERROR: No longer own the lock\n return -1\n end\n '''", ")", "res", "=", "script", "(", "keys", "=", "[", "self", ".", "_lock_name", ",", "self", ".", "_namespace", "(", "dict_name", ")", "]", ",", "args", "=", "[", "self", ".", "_session_lock_identifier", ",", "self", ".", "_encode", "(", "key1", ")", ",", "self", ".", "_encode", "(", "key2", ")", "]", ")", "if", "res", "==", "-", "1", ":", "raise", "EnvironmentError", "(", ")" ]
Set two keys to be equal in a 1-to-1 mapping. Within `dict_name`, `key1` is set to `key2`, and `key2` is set to `key1`. This always requires a session lock. :param str dict_name: dictionary to update :param str key1: first key/value :param str key2: second key/value
[ "Set", "two", "keys", "to", "be", "equal", "in", "a", "1", "-", "to", "-", "1", "mapping", "." ]
5438a4a18be2801d7826c46e2079ba9639d2ecb4
https://github.com/diffeo/rejester/blob/5438a4a18be2801d7826c46e2079ba9639d2ecb4/rejester/_registry.py#L867-L899
242,757
diffeo/rejester
rejester/_registry.py
Registry.get
def get(self, dict_name, key, default=None, include_priority=False): '''Get the value for a specific key in a specific dictionary. If `include_priority` is false (default), returns the value for that key, or `default` (defaults to :const:`None`) if it is absent. If `include_priority` is true, returns a pair of the value and its priority, or of `default` and :const:`None`. This does not use or enforce the session lock, and is read-only, but inconsistent results are conceivably possible if the caller does not hold the lock and `include_priority` is set. :param str dict_name: name of dictionary to query :param str key: key in dictionary to query :param default: default value if `key` is absent :param bool include_priority: include score in results :return: value from dictionary, or pair of value and priority ''' dict_name = self._namespace(dict_name) key = self._encode(key) conn = redis.Redis(connection_pool=self.pool) val = conn.hget(dict_name, key) if val is None: _val = default else: _val = self._decode(val) if include_priority: if val is not None: priority = conn.zscore(dict_name + 'keys', key) return _val, priority else: return _val, None return _val
python
def get(self, dict_name, key, default=None, include_priority=False): '''Get the value for a specific key in a specific dictionary. If `include_priority` is false (default), returns the value for that key, or `default` (defaults to :const:`None`) if it is absent. If `include_priority` is true, returns a pair of the value and its priority, or of `default` and :const:`None`. This does not use or enforce the session lock, and is read-only, but inconsistent results are conceivably possible if the caller does not hold the lock and `include_priority` is set. :param str dict_name: name of dictionary to query :param str key: key in dictionary to query :param default: default value if `key` is absent :param bool include_priority: include score in results :return: value from dictionary, or pair of value and priority ''' dict_name = self._namespace(dict_name) key = self._encode(key) conn = redis.Redis(connection_pool=self.pool) val = conn.hget(dict_name, key) if val is None: _val = default else: _val = self._decode(val) if include_priority: if val is not None: priority = conn.zscore(dict_name + 'keys', key) return _val, priority else: return _val, None return _val
[ "def", "get", "(", "self", ",", "dict_name", ",", "key", ",", "default", "=", "None", ",", "include_priority", "=", "False", ")", ":", "dict_name", "=", "self", ".", "_namespace", "(", "dict_name", ")", "key", "=", "self", ".", "_encode", "(", "key", ")", "conn", "=", "redis", ".", "Redis", "(", "connection_pool", "=", "self", ".", "pool", ")", "val", "=", "conn", ".", "hget", "(", "dict_name", ",", "key", ")", "if", "val", "is", "None", ":", "_val", "=", "default", "else", ":", "_val", "=", "self", ".", "_decode", "(", "val", ")", "if", "include_priority", ":", "if", "val", "is", "not", "None", ":", "priority", "=", "conn", ".", "zscore", "(", "dict_name", "+", "'keys'", ",", "key", ")", "return", "_val", ",", "priority", "else", ":", "return", "_val", ",", "None", "return", "_val" ]
Get the value for a specific key in a specific dictionary. If `include_priority` is false (default), returns the value for that key, or `default` (defaults to :const:`None`) if it is absent. If `include_priority` is true, returns a pair of the value and its priority, or of `default` and :const:`None`. This does not use or enforce the session lock, and is read-only, but inconsistent results are conceivably possible if the caller does not hold the lock and `include_priority` is set. :param str dict_name: name of dictionary to query :param str key: key in dictionary to query :param default: default value if `key` is absent :param bool include_priority: include score in results :return: value from dictionary, or pair of value and priority
[ "Get", "the", "value", "for", "a", "specific", "key", "in", "a", "specific", "dictionary", "." ]
5438a4a18be2801d7826c46e2079ba9639d2ecb4
https://github.com/diffeo/rejester/blob/5438a4a18be2801d7826c46e2079ba9639d2ecb4/rejester/_registry.py#L901-L934
242,758
diffeo/rejester
rejester/_registry.py
Registry.set
def set(self, dict_name, key, value, priority=None): '''Set a single value for a single key. This requires a session lock. :param str dict_name: name of the dictionary to update :param str key: key to update :param str value: value to assign to `key` :param int priority: priority score for the value (if any) ''' if priority is not None: priorities = {key: priority} else: priorities = None self.update(dict_name, {key: value}, priorities=priorities)
python
def set(self, dict_name, key, value, priority=None): '''Set a single value for a single key. This requires a session lock. :param str dict_name: name of the dictionary to update :param str key: key to update :param str value: value to assign to `key` :param int priority: priority score for the value (if any) ''' if priority is not None: priorities = {key: priority} else: priorities = None self.update(dict_name, {key: value}, priorities=priorities)
[ "def", "set", "(", "self", ",", "dict_name", ",", "key", ",", "value", ",", "priority", "=", "None", ")", ":", "if", "priority", "is", "not", "None", ":", "priorities", "=", "{", "key", ":", "priority", "}", "else", ":", "priorities", "=", "None", "self", ".", "update", "(", "dict_name", ",", "{", "key", ":", "value", "}", ",", "priorities", "=", "priorities", ")" ]
Set a single value for a single key. This requires a session lock. :param str dict_name: name of the dictionary to update :param str key: key to update :param str value: value to assign to `key` :param int priority: priority score for the value (if any)
[ "Set", "a", "single", "value", "for", "a", "single", "key", "." ]
5438a4a18be2801d7826c46e2079ba9639d2ecb4
https://github.com/diffeo/rejester/blob/5438a4a18be2801d7826c46e2079ba9639d2ecb4/rejester/_registry.py#L936-L951
242,759
diffeo/rejester
rejester/_registry.py
Registry.delete
def delete(self, dict_name): '''Delete an entire dictionary. This operation on its own is atomic and does not require a session lock, but a session lock is honored. :param str dict_name: name of the dictionary to delete :raises rejester.exceptions.LockError: if called with a session lock, but the system does not currently have that lock; or if called without a session lock but something else holds it ''' conn = redis.Redis(connection_pool=self.pool) script = conn.register_script(''' if redis.call("get", KEYS[1]) == ARGV[1] then redis.call("del", KEYS[2], KEYS[3]) return 0 else return -1 end ''') res = script(keys=[self._lock_name, self._namespace(dict_name), self._namespace(dict_name) + 'keys'], args=[self._session_lock_identifier]) if res == -1: raise LockError()
python
def delete(self, dict_name): '''Delete an entire dictionary. This operation on its own is atomic and does not require a session lock, but a session lock is honored. :param str dict_name: name of the dictionary to delete :raises rejester.exceptions.LockError: if called with a session lock, but the system does not currently have that lock; or if called without a session lock but something else holds it ''' conn = redis.Redis(connection_pool=self.pool) script = conn.register_script(''' if redis.call("get", KEYS[1]) == ARGV[1] then redis.call("del", KEYS[2], KEYS[3]) return 0 else return -1 end ''') res = script(keys=[self._lock_name, self._namespace(dict_name), self._namespace(dict_name) + 'keys'], args=[self._session_lock_identifier]) if res == -1: raise LockError()
[ "def", "delete", "(", "self", ",", "dict_name", ")", ":", "conn", "=", "redis", ".", "Redis", "(", "connection_pool", "=", "self", ".", "pool", ")", "script", "=", "conn", ".", "register_script", "(", "'''\n if redis.call(\"get\", KEYS[1]) == ARGV[1]\n then\n redis.call(\"del\", KEYS[2], KEYS[3])\n return 0\n else\n return -1\n end\n '''", ")", "res", "=", "script", "(", "keys", "=", "[", "self", ".", "_lock_name", ",", "self", ".", "_namespace", "(", "dict_name", ")", ",", "self", ".", "_namespace", "(", "dict_name", ")", "+", "'keys'", "]", ",", "args", "=", "[", "self", ".", "_session_lock_identifier", "]", ")", "if", "res", "==", "-", "1", ":", "raise", "LockError", "(", ")" ]
Delete an entire dictionary. This operation on its own is atomic and does not require a session lock, but a session lock is honored. :param str dict_name: name of the dictionary to delete :raises rejester.exceptions.LockError: if called with a session lock, but the system does not currently have that lock; or if called without a session lock but something else holds it
[ "Delete", "an", "entire", "dictionary", "." ]
5438a4a18be2801d7826c46e2079ba9639d2ecb4
https://github.com/diffeo/rejester/blob/5438a4a18be2801d7826c46e2079ba9639d2ecb4/rejester/_registry.py#L953-L979
242,760
diffeo/rejester
rejester/_registry.py
Registry.direct_call
def direct_call(self, *args): '''execute a direct redis call against this Registry instances namespaced keys. This is low level is should only be used for prototyping. arg[0] = redis function arg[1] = key --- will be namespaced before execution args[2:] = args to function :returns raw return value of function: Neither args nor return values are encoded/decoded ''' conn = redis.Redis(connection_pool=self.pool) command = args[0] key = self._namespace(args[1]) args = args[2:] func = getattr(conn, command) return func(key, *args)
python
def direct_call(self, *args): '''execute a direct redis call against this Registry instances namespaced keys. This is low level is should only be used for prototyping. arg[0] = redis function arg[1] = key --- will be namespaced before execution args[2:] = args to function :returns raw return value of function: Neither args nor return values are encoded/decoded ''' conn = redis.Redis(connection_pool=self.pool) command = args[0] key = self._namespace(args[1]) args = args[2:] func = getattr(conn, command) return func(key, *args)
[ "def", "direct_call", "(", "self", ",", "*", "args", ")", ":", "conn", "=", "redis", ".", "Redis", "(", "connection_pool", "=", "self", ".", "pool", ")", "command", "=", "args", "[", "0", "]", "key", "=", "self", ".", "_namespace", "(", "args", "[", "1", "]", ")", "args", "=", "args", "[", "2", ":", "]", "func", "=", "getattr", "(", "conn", ",", "command", ")", "return", "func", "(", "key", ",", "*", "args", ")" ]
execute a direct redis call against this Registry instances namespaced keys. This is low level is should only be used for prototyping. arg[0] = redis function arg[1] = key --- will be namespaced before execution args[2:] = args to function :returns raw return value of function: Neither args nor return values are encoded/decoded
[ "execute", "a", "direct", "redis", "call", "against", "this", "Registry", "instances", "namespaced", "keys", ".", "This", "is", "low", "level", "is", "should", "only", "be", "used", "for", "prototyping", "." ]
5438a4a18be2801d7826c46e2079ba9639d2ecb4
https://github.com/diffeo/rejester/blob/5438a4a18be2801d7826c46e2079ba9639d2ecb4/rejester/_registry.py#L981-L999
242,761
tslight/yorn
yorn/ask.py
ask
def ask(question): ''' Infinite loop to get yes or no answer or quit the script. ''' while True: ans = input(question) al = ans.lower() if match('^y(es)?$', al): return True elif match('^n(o)?$', al): return False elif match('^q(uit)?$', al): stdout.write(CYAN) print("\nGoodbye.\n") stdout.write(RESET) quit() else: stdout.write(RED) print("%s is invalid. Enter (y)es, (n)o or (q)uit." % ans) stdout.write(RESET)
python
def ask(question): ''' Infinite loop to get yes or no answer or quit the script. ''' while True: ans = input(question) al = ans.lower() if match('^y(es)?$', al): return True elif match('^n(o)?$', al): return False elif match('^q(uit)?$', al): stdout.write(CYAN) print("\nGoodbye.\n") stdout.write(RESET) quit() else: stdout.write(RED) print("%s is invalid. Enter (y)es, (n)o or (q)uit." % ans) stdout.write(RESET)
[ "def", "ask", "(", "question", ")", ":", "while", "True", ":", "ans", "=", "input", "(", "question", ")", "al", "=", "ans", ".", "lower", "(", ")", "if", "match", "(", "'^y(es)?$'", ",", "al", ")", ":", "return", "True", "elif", "match", "(", "'^n(o)?$'", ",", "al", ")", ":", "return", "False", "elif", "match", "(", "'^q(uit)?$'", ",", "al", ")", ":", "stdout", ".", "write", "(", "CYAN", ")", "print", "(", "\"\\nGoodbye.\\n\"", ")", "stdout", ".", "write", "(", "RESET", ")", "quit", "(", ")", "else", ":", "stdout", ".", "write", "(", "RED", ")", "print", "(", "\"%s is invalid. Enter (y)es, (n)o or (q)uit.\"", "%", "ans", ")", "stdout", ".", "write", "(", "RESET", ")" ]
Infinite loop to get yes or no answer or quit the script.
[ "Infinite", "loop", "to", "get", "yes", "or", "no", "answer", "or", "quit", "the", "script", "." ]
be577261065a53d3f4a585038c597c72950aa5ce
https://github.com/tslight/yorn/blob/be577261065a53d3f4a585038c597c72950aa5ce/yorn/ask.py#L13-L32
242,762
fangpenlin/pyramid-handy
pyramid_handy/tweens/basic_auth.py
get_remote_user
def get_remote_user(request): """Parse basic HTTP_AUTHORIZATION and return user name """ if 'HTTP_AUTHORIZATION' not in request.environ: return authorization = request.environ['HTTP_AUTHORIZATION'] try: authmeth, auth = authorization.split(' ', 1) except ValueError: # not enough values to unpack return if authmeth.lower() != 'basic': return try: auth = base64.b64decode(auth.strip().encode('latin1')).decode('latin1') except (binascii.Error, TypeError): # can't decode return try: login, password = auth.split(':', 1) except ValueError: # not enough values to unpack return return login, password
python
def get_remote_user(request): """Parse basic HTTP_AUTHORIZATION and return user name """ if 'HTTP_AUTHORIZATION' not in request.environ: return authorization = request.environ['HTTP_AUTHORIZATION'] try: authmeth, auth = authorization.split(' ', 1) except ValueError: # not enough values to unpack return if authmeth.lower() != 'basic': return try: auth = base64.b64decode(auth.strip().encode('latin1')).decode('latin1') except (binascii.Error, TypeError): # can't decode return try: login, password = auth.split(':', 1) except ValueError: # not enough values to unpack return return login, password
[ "def", "get_remote_user", "(", "request", ")", ":", "if", "'HTTP_AUTHORIZATION'", "not", "in", "request", ".", "environ", ":", "return", "authorization", "=", "request", ".", "environ", "[", "'HTTP_AUTHORIZATION'", "]", "try", ":", "authmeth", ",", "auth", "=", "authorization", ".", "split", "(", "' '", ",", "1", ")", "except", "ValueError", ":", "# not enough values to unpack", "return", "if", "authmeth", ".", "lower", "(", ")", "!=", "'basic'", ":", "return", "try", ":", "auth", "=", "base64", ".", "b64decode", "(", "auth", ".", "strip", "(", ")", ".", "encode", "(", "'latin1'", ")", ")", ".", "decode", "(", "'latin1'", ")", "except", "(", "binascii", ".", "Error", ",", "TypeError", ")", ":", "# can't decode", "return", "try", ":", "login", ",", "password", "=", "auth", ".", "split", "(", "':'", ",", "1", ")", "except", "ValueError", ":", "# not enough values to unpack", "return", "return", "login", ",", "password" ]
Parse basic HTTP_AUTHORIZATION and return user name
[ "Parse", "basic", "HTTP_AUTHORIZATION", "and", "return", "user", "name" ]
e3cbc19224ab1f0a14aab556990bceabd2d1f658
https://github.com/fangpenlin/pyramid-handy/blob/e3cbc19224ab1f0a14aab556990bceabd2d1f658/pyramid_handy/tweens/basic_auth.py#L7-L28
242,763
fangpenlin/pyramid-handy
pyramid_handy/tweens/basic_auth.py
basic_auth_tween_factory
def basic_auth_tween_factory(handler, registry): """Do basic authentication, parse HTTP_AUTHORIZATION and set remote_user variable to request """ def basic_auth_tween(request): remote_user = get_remote_user(request) if remote_user is not None: request.environ['REMOTE_USER'] = remote_user[0] return handler(request) return basic_auth_tween
python
def basic_auth_tween_factory(handler, registry): """Do basic authentication, parse HTTP_AUTHORIZATION and set remote_user variable to request """ def basic_auth_tween(request): remote_user = get_remote_user(request) if remote_user is not None: request.environ['REMOTE_USER'] = remote_user[0] return handler(request) return basic_auth_tween
[ "def", "basic_auth_tween_factory", "(", "handler", ",", "registry", ")", ":", "def", "basic_auth_tween", "(", "request", ")", ":", "remote_user", "=", "get_remote_user", "(", "request", ")", "if", "remote_user", "is", "not", "None", ":", "request", ".", "environ", "[", "'REMOTE_USER'", "]", "=", "remote_user", "[", "0", "]", "return", "handler", "(", "request", ")", "return", "basic_auth_tween" ]
Do basic authentication, parse HTTP_AUTHORIZATION and set remote_user variable to request
[ "Do", "basic", "authentication", "parse", "HTTP_AUTHORIZATION", "and", "set", "remote_user", "variable", "to", "request" ]
e3cbc19224ab1f0a14aab556990bceabd2d1f658
https://github.com/fangpenlin/pyramid-handy/blob/e3cbc19224ab1f0a14aab556990bceabd2d1f658/pyramid_handy/tweens/basic_auth.py#L31-L41
242,764
ryanjdillon/pylleo
pylleo/calapp/main.py
plot_triaxial
def plot_triaxial(height, width, tools): '''Plot pandas dataframe containing an x, y, and z column''' import bokeh.plotting p = bokeh.plotting.figure(x_axis_type='datetime', plot_height=height, plot_width=width, title=' ', toolbar_sticky=False, tools=tools, active_drag=BoxZoomTool(), output_backend='webgl') p.yaxis.axis_label = 'Acceleration (count)' p.xaxis.axis_label = 'Time (timezone as programmed)' # Plot accelerometry data as lines and scatter (for BoxSelectTool) colors = ['#1b9e77', '#d95f02', '#7570b3'] axes = ['x', 'y', 'z'] lines = [None,]*3 scats = [None,]*3 for i, (ax, c) in enumerate(zip(axes, colors)): lines[i] = p.line(y=ax, x='dt', color=c, legend=False, source=source) scats[i] = p.scatter(y=ax, x='dt', color=c, legend=False, size=1, source=source) return p, lines, scats
python
def plot_triaxial(height, width, tools): '''Plot pandas dataframe containing an x, y, and z column''' import bokeh.plotting p = bokeh.plotting.figure(x_axis_type='datetime', plot_height=height, plot_width=width, title=' ', toolbar_sticky=False, tools=tools, active_drag=BoxZoomTool(), output_backend='webgl') p.yaxis.axis_label = 'Acceleration (count)' p.xaxis.axis_label = 'Time (timezone as programmed)' # Plot accelerometry data as lines and scatter (for BoxSelectTool) colors = ['#1b9e77', '#d95f02', '#7570b3'] axes = ['x', 'y', 'z'] lines = [None,]*3 scats = [None,]*3 for i, (ax, c) in enumerate(zip(axes, colors)): lines[i] = p.line(y=ax, x='dt', color=c, legend=False, source=source) scats[i] = p.scatter(y=ax, x='dt', color=c, legend=False, size=1, source=source) return p, lines, scats
[ "def", "plot_triaxial", "(", "height", ",", "width", ",", "tools", ")", ":", "import", "bokeh", ".", "plotting", "p", "=", "bokeh", ".", "plotting", ".", "figure", "(", "x_axis_type", "=", "'datetime'", ",", "plot_height", "=", "height", ",", "plot_width", "=", "width", ",", "title", "=", "' '", ",", "toolbar_sticky", "=", "False", ",", "tools", "=", "tools", ",", "active_drag", "=", "BoxZoomTool", "(", ")", ",", "output_backend", "=", "'webgl'", ")", "p", ".", "yaxis", ".", "axis_label", "=", "'Acceleration (count)'", "p", ".", "xaxis", ".", "axis_label", "=", "'Time (timezone as programmed)'", "# Plot accelerometry data as lines and scatter (for BoxSelectTool)", "colors", "=", "[", "'#1b9e77'", ",", "'#d95f02'", ",", "'#7570b3'", "]", "axes", "=", "[", "'x'", ",", "'y'", ",", "'z'", "]", "lines", "=", "[", "None", ",", "]", "*", "3", "scats", "=", "[", "None", ",", "]", "*", "3", "for", "i", ",", "(", "ax", ",", "c", ")", "in", "enumerate", "(", "zip", "(", "axes", ",", "colors", ")", ")", ":", "lines", "[", "i", "]", "=", "p", ".", "line", "(", "y", "=", "ax", ",", "x", "=", "'dt'", ",", "color", "=", "c", ",", "legend", "=", "False", ",", "source", "=", "source", ")", "scats", "[", "i", "]", "=", "p", ".", "scatter", "(", "y", "=", "ax", ",", "x", "=", "'dt'", ",", "color", "=", "c", ",", "legend", "=", "False", ",", "size", "=", "1", ",", "source", "=", "source", ")", "return", "p", ",", "lines", ",", "scats" ]
Plot pandas dataframe containing an x, y, and z column
[ "Plot", "pandas", "dataframe", "containing", "an", "x", "y", "and", "z", "column" ]
b9b999fef19eaeccce4f207ab1b6198287c1bfec
https://github.com/ryanjdillon/pylleo/blob/b9b999fef19eaeccce4f207ab1b6198287c1bfec/pylleo/calapp/main.py#L18-L43
242,765
ryanjdillon/pylleo
pylleo/calapp/main.py
load_data
def load_data(path_dir): '''Load data, directory parameters, and accelerometer parameter names Args ---- path_dir: str Path to the data directory Returns ------- data: pandas.DataFrame Experiment data params_tag: dict A dictionary of parameters parsed from the directory name params_data: list A list of the accelerometer parameter names ''' import os import pylleo exp_name = os.path.split(path_dir)[1] params_tag = pylleo.utils.parse_experiment_params(exp_name) # Load the Little Leonardo tag data meta = pylleo.lleoio.read_meta(path_dir, params_tag['tag_model'], params_tag['tag_id']) data = pylleo.lleoio.read_data(meta, path_dir, sample_f=sample_f) # Get and curate the parameter names of the loaded dataframe params_data = pylleo.utils.get_tag_params(params_tag['tag_model']) params_data = [pylleo.utils.posix_string(p) for p in params_data] params_data = [p for p in params_data if p.startswith('acc')] return data, params_tag, params_data
python
def load_data(path_dir): '''Load data, directory parameters, and accelerometer parameter names Args ---- path_dir: str Path to the data directory Returns ------- data: pandas.DataFrame Experiment data params_tag: dict A dictionary of parameters parsed from the directory name params_data: list A list of the accelerometer parameter names ''' import os import pylleo exp_name = os.path.split(path_dir)[1] params_tag = pylleo.utils.parse_experiment_params(exp_name) # Load the Little Leonardo tag data meta = pylleo.lleoio.read_meta(path_dir, params_tag['tag_model'], params_tag['tag_id']) data = pylleo.lleoio.read_data(meta, path_dir, sample_f=sample_f) # Get and curate the parameter names of the loaded dataframe params_data = pylleo.utils.get_tag_params(params_tag['tag_model']) params_data = [pylleo.utils.posix_string(p) for p in params_data] params_data = [p for p in params_data if p.startswith('acc')] return data, params_tag, params_data
[ "def", "load_data", "(", "path_dir", ")", ":", "import", "os", "import", "pylleo", "exp_name", "=", "os", ".", "path", ".", "split", "(", "path_dir", ")", "[", "1", "]", "params_tag", "=", "pylleo", ".", "utils", ".", "parse_experiment_params", "(", "exp_name", ")", "# Load the Little Leonardo tag data", "meta", "=", "pylleo", ".", "lleoio", ".", "read_meta", "(", "path_dir", ",", "params_tag", "[", "'tag_model'", "]", ",", "params_tag", "[", "'tag_id'", "]", ")", "data", "=", "pylleo", ".", "lleoio", ".", "read_data", "(", "meta", ",", "path_dir", ",", "sample_f", "=", "sample_f", ")", "# Get and curate the parameter names of the loaded dataframe", "params_data", "=", "pylleo", ".", "utils", ".", "get_tag_params", "(", "params_tag", "[", "'tag_model'", "]", ")", "params_data", "=", "[", "pylleo", ".", "utils", ".", "posix_string", "(", "p", ")", "for", "p", "in", "params_data", "]", "params_data", "=", "[", "p", "for", "p", "in", "params_data", "if", "p", ".", "startswith", "(", "'acc'", ")", "]", "return", "data", ",", "params_tag", ",", "params_data" ]
Load data, directory parameters, and accelerometer parameter names Args ---- path_dir: str Path to the data directory Returns ------- data: pandas.DataFrame Experiment data params_tag: dict A dictionary of parameters parsed from the directory name params_data: list A list of the accelerometer parameter names
[ "Load", "data", "directory", "parameters", "and", "accelerometer", "parameter", "names" ]
b9b999fef19eaeccce4f207ab1b6198287c1bfec
https://github.com/ryanjdillon/pylleo/blob/b9b999fef19eaeccce4f207ab1b6198287c1bfec/pylleo/calapp/main.py#L46-L79
242,766
ryanjdillon/pylleo
pylleo/calapp/main.py
callback_checkbox
def callback_checkbox(attr, old, new): '''Update visible data from parameters selectin in the CheckboxSelect''' import numpy for i in range(len(lines)): lines[i].visible = i in param_checkbox.active scats[i].visible = i in param_checkbox.active return None
python
def callback_checkbox(attr, old, new): '''Update visible data from parameters selectin in the CheckboxSelect''' import numpy for i in range(len(lines)): lines[i].visible = i in param_checkbox.active scats[i].visible = i in param_checkbox.active return None
[ "def", "callback_checkbox", "(", "attr", ",", "old", ",", "new", ")", ":", "import", "numpy", "for", "i", "in", "range", "(", "len", "(", "lines", ")", ")", ":", "lines", "[", "i", "]", ".", "visible", "=", "i", "in", "param_checkbox", ".", "active", "scats", "[", "i", "]", ".", "visible", "=", "i", "in", "param_checkbox", ".", "active", "return", "None" ]
Update visible data from parameters selectin in the CheckboxSelect
[ "Update", "visible", "data", "from", "parameters", "selectin", "in", "the", "CheckboxSelect" ]
b9b999fef19eaeccce4f207ab1b6198287c1bfec
https://github.com/ryanjdillon/pylleo/blob/b9b999fef19eaeccce4f207ab1b6198287c1bfec/pylleo/calapp/main.py#L179-L187
242,767
pablorecio/Cobaya
src/cobaya/password.py
get_password
def get_password(config): """Returns the password for a remote server It tries to fetch the password from the following locations in this order: 1. config file [remote] section, password option 2. GNOME keyring 3. interactively, from the user """ password = config.get_option('remote.password') if password == '': user = config.get_option('remote.user') url = config.get_option('remote.url') url_obj = urlparse.urlparse(url) server = url_obj.hostname protocol = url_obj.scheme if HAS_GNOME_KEYRING_SUPPORT: password = get_password_from_gnome_keyring(user, server, protocol) else: prompt = 'Enter %s password for %s at %s: ' % (get_app(), user, server) password = getpass.getpass(prompt) return password
python
def get_password(config): """Returns the password for a remote server It tries to fetch the password from the following locations in this order: 1. config file [remote] section, password option 2. GNOME keyring 3. interactively, from the user """ password = config.get_option('remote.password') if password == '': user = config.get_option('remote.user') url = config.get_option('remote.url') url_obj = urlparse.urlparse(url) server = url_obj.hostname protocol = url_obj.scheme if HAS_GNOME_KEYRING_SUPPORT: password = get_password_from_gnome_keyring(user, server, protocol) else: prompt = 'Enter %s password for %s at %s: ' % (get_app(), user, server) password = getpass.getpass(prompt) return password
[ "def", "get_password", "(", "config", ")", ":", "password", "=", "config", ".", "get_option", "(", "'remote.password'", ")", "if", "password", "==", "''", ":", "user", "=", "config", ".", "get_option", "(", "'remote.user'", ")", "url", "=", "config", ".", "get_option", "(", "'remote.url'", ")", "url_obj", "=", "urlparse", ".", "urlparse", "(", "url", ")", "server", "=", "url_obj", ".", "hostname", "protocol", "=", "url_obj", ".", "scheme", "if", "HAS_GNOME_KEYRING_SUPPORT", ":", "password", "=", "get_password_from_gnome_keyring", "(", "user", ",", "server", ",", "protocol", ")", "else", ":", "prompt", "=", "'Enter %s password for %s at %s: '", "%", "(", "get_app", "(", ")", ",", "user", ",", "server", ")", "password", "=", "getpass", ".", "getpass", "(", "prompt", ")", "return", "password" ]
Returns the password for a remote server It tries to fetch the password from the following locations in this order: 1. config file [remote] section, password option 2. GNOME keyring 3. interactively, from the user
[ "Returns", "the", "password", "for", "a", "remote", "server" ]
70b107dea5f31f51e7b6738da3c2a1df5b9f3f20
https://github.com/pablorecio/Cobaya/blob/70b107dea5f31f51e7b6738da3c2a1df5b9f3f20/src/cobaya/password.py#L34-L61
242,768
gear11/pypelogs
pypelogs.py
process
def process(specs): """ Executes the passed in list of specs """ pout, pin = chain_specs(specs) LOG.info("Processing") sw = StopWatch().start() r = pout.process(pin) if r: print(r) LOG.info("Finished in %s", sw.read())
python
def process(specs): """ Executes the passed in list of specs """ pout, pin = chain_specs(specs) LOG.info("Processing") sw = StopWatch().start() r = pout.process(pin) if r: print(r) LOG.info("Finished in %s", sw.read())
[ "def", "process", "(", "specs", ")", ":", "pout", ",", "pin", "=", "chain_specs", "(", "specs", ")", "LOG", ".", "info", "(", "\"Processing\"", ")", "sw", "=", "StopWatch", "(", ")", ".", "start", "(", ")", "r", "=", "pout", ".", "process", "(", "pin", ")", "if", "r", ":", "print", "(", "r", ")", "LOG", ".", "info", "(", "\"Finished in %s\"", ",", "sw", ".", "read", "(", ")", ")" ]
Executes the passed in list of specs
[ "Executes", "the", "passed", "in", "list", "of", "specs" ]
da5dc0fee5373a4be294798b5e32cd0a803d8bbe
https://github.com/gear11/pypelogs/blob/da5dc0fee5373a4be294798b5e32cd0a803d8bbe/pypelogs.py#L33-L43
242,769
unfoldingWord-dev/tx-shared-tools
general_tools/smartquotes.py
smartquotes
def smartquotes(text): """ Runs text through pandoc for smartquote correction. """ command = shlex.split('pandoc --smart -t plain') com = Popen(command, shell=False, stdin=PIPE, stdout=PIPE, stderr=PIPE) out, err = com.communicate(text.encode('utf-8')) com_out = out.decode('utf-8') text = com_out.replace(u'\n', u' ').strip() return text
python
def smartquotes(text): """ Runs text through pandoc for smartquote correction. """ command = shlex.split('pandoc --smart -t plain') com = Popen(command, shell=False, stdin=PIPE, stdout=PIPE, stderr=PIPE) out, err = com.communicate(text.encode('utf-8')) com_out = out.decode('utf-8') text = com_out.replace(u'\n', u' ').strip() return text
[ "def", "smartquotes", "(", "text", ")", ":", "command", "=", "shlex", ".", "split", "(", "'pandoc --smart -t plain'", ")", "com", "=", "Popen", "(", "command", ",", "shell", "=", "False", ",", "stdin", "=", "PIPE", ",", "stdout", "=", "PIPE", ",", "stderr", "=", "PIPE", ")", "out", ",", "err", "=", "com", ".", "communicate", "(", "text", ".", "encode", "(", "'utf-8'", ")", ")", "com_out", "=", "out", ".", "decode", "(", "'utf-8'", ")", "text", "=", "com_out", ".", "replace", "(", "u'\\n'", ",", "u' '", ")", ".", "strip", "(", ")", "return", "text" ]
Runs text through pandoc for smartquote correction.
[ "Runs", "text", "through", "pandoc", "for", "smartquote", "correction", "." ]
6ff5cd024e1ab54c53dd1bc788bbc78e2358772e
https://github.com/unfoldingWord-dev/tx-shared-tools/blob/6ff5cd024e1ab54c53dd1bc788bbc78e2358772e/general_tools/smartquotes.py#L22-L31
242,770
GreenBankObservatory/django-resetdb
django_resetdb/util.py
shell
def shell(cmd, **kwargs): """Execute cmd, check exit code, return stdout""" logger.debug("$ %s", cmd) return subprocess.check_output(cmd, shell=True, **kwargs)
python
def shell(cmd, **kwargs): """Execute cmd, check exit code, return stdout""" logger.debug("$ %s", cmd) return subprocess.check_output(cmd, shell=True, **kwargs)
[ "def", "shell", "(", "cmd", ",", "*", "*", "kwargs", ")", ":", "logger", ".", "debug", "(", "\"$ %s\"", ",", "cmd", ")", "return", "subprocess", ".", "check_output", "(", "cmd", ",", "shell", "=", "True", ",", "*", "*", "kwargs", ")" ]
Execute cmd, check exit code, return stdout
[ "Execute", "cmd", "check", "exit", "code", "return", "stdout" ]
767bddacb53823bb003e2abebfe8139a14b843f7
https://github.com/GreenBankObservatory/django-resetdb/blob/767bddacb53823bb003e2abebfe8139a14b843f7/django_resetdb/util.py#L16-L19
242,771
vinu76jsr/pipsort
deploy.py
main
def main(argv=None): """ Script execution. The project repo will be cloned to a temporary directory, and the desired branch, tag, or commit will be checked out. Then, the application will be installed into a self-contained virtualenv environment. """ @contextmanager def tmpdir(): """ Create a self-deleting temporary directory. """ path = mkdtemp() try: yield path finally: rmtree(path) return def test(): """ Execute the test suite. """ install = "{:s} install -r requirements-test.txt" check_call(install.format(pip).split()) pytest = join(path, "bin", "py.test") test = "{:s} test/".format(pytest) check_call(test.split()) uninstall = "{:s} uninstall -y -r requirements-test.txt" check_call(uninstall.format(pip).split()) return args = _cmdline(argv) path = join(abspath(args.root), args.name) with tmpdir() as tmp: clone = "git clone {:s} {:s}".format(args.repo, tmp) check_call(clone.split()) chdir(tmp) checkout = "git checkout {:s}".format(args.checkout) check_call(checkout.split()) virtualenv = "virtualenv {:s}".format(path) check_call(virtualenv.split()) pip = join(path, "bin", "pip") install = "{:s} install -U -r requirements.txt .".format(pip) check_call(install.split()) if args.test: test() return 0
python
def main(argv=None): """ Script execution. The project repo will be cloned to a temporary directory, and the desired branch, tag, or commit will be checked out. Then, the application will be installed into a self-contained virtualenv environment. """ @contextmanager def tmpdir(): """ Create a self-deleting temporary directory. """ path = mkdtemp() try: yield path finally: rmtree(path) return def test(): """ Execute the test suite. """ install = "{:s} install -r requirements-test.txt" check_call(install.format(pip).split()) pytest = join(path, "bin", "py.test") test = "{:s} test/".format(pytest) check_call(test.split()) uninstall = "{:s} uninstall -y -r requirements-test.txt" check_call(uninstall.format(pip).split()) return args = _cmdline(argv) path = join(abspath(args.root), args.name) with tmpdir() as tmp: clone = "git clone {:s} {:s}".format(args.repo, tmp) check_call(clone.split()) chdir(tmp) checkout = "git checkout {:s}".format(args.checkout) check_call(checkout.split()) virtualenv = "virtualenv {:s}".format(path) check_call(virtualenv.split()) pip = join(path, "bin", "pip") install = "{:s} install -U -r requirements.txt .".format(pip) check_call(install.split()) if args.test: test() return 0
[ "def", "main", "(", "argv", "=", "None", ")", ":", "@", "contextmanager", "def", "tmpdir", "(", ")", ":", "\"\"\" Create a self-deleting temporary directory. \"\"\"", "path", "=", "mkdtemp", "(", ")", "try", ":", "yield", "path", "finally", ":", "rmtree", "(", "path", ")", "return", "def", "test", "(", ")", ":", "\"\"\" Execute the test suite. \"\"\"", "install", "=", "\"{:s} install -r requirements-test.txt\"", "check_call", "(", "install", ".", "format", "(", "pip", ")", ".", "split", "(", ")", ")", "pytest", "=", "join", "(", "path", ",", "\"bin\"", ",", "\"py.test\"", ")", "test", "=", "\"{:s} test/\"", ".", "format", "(", "pytest", ")", "check_call", "(", "test", ".", "split", "(", ")", ")", "uninstall", "=", "\"{:s} uninstall -y -r requirements-test.txt\"", "check_call", "(", "uninstall", ".", "format", "(", "pip", ")", ".", "split", "(", ")", ")", "return", "args", "=", "_cmdline", "(", "argv", ")", "path", "=", "join", "(", "abspath", "(", "args", ".", "root", ")", ",", "args", ".", "name", ")", "with", "tmpdir", "(", ")", "as", "tmp", ":", "clone", "=", "\"git clone {:s} {:s}\"", ".", "format", "(", "args", ".", "repo", ",", "tmp", ")", "check_call", "(", "clone", ".", "split", "(", ")", ")", "chdir", "(", "tmp", ")", "checkout", "=", "\"git checkout {:s}\"", ".", "format", "(", "args", ".", "checkout", ")", "check_call", "(", "checkout", ".", "split", "(", ")", ")", "virtualenv", "=", "\"virtualenv {:s}\"", ".", "format", "(", "path", ")", "check_call", "(", "virtualenv", ".", "split", "(", ")", ")", "pip", "=", "join", "(", "path", ",", "\"bin\"", ",", "\"pip\"", ")", "install", "=", "\"{:s} install -U -r requirements.txt .\"", ".", "format", "(", "pip", ")", "check_call", "(", "install", ".", "split", "(", ")", ")", "if", "args", ".", "test", ":", "test", "(", ")", "return", "0" ]
Script execution. The project repo will be cloned to a temporary directory, and the desired branch, tag, or commit will be checked out. Then, the application will be installed into a self-contained virtualenv environment.
[ "Script", "execution", "." ]
71ead1269de85ee0255741390bf1da85d81b7d16
https://github.com/vinu76jsr/pipsort/blob/71ead1269de85ee0255741390bf1da85d81b7d16/deploy.py#L44-L88
242,772
krukas/Trionyx
trionyx/trionyx/models.py
UserManager._create_user
def _create_user(self, email, password, is_superuser, **extra_fields): """Create new user""" now = timezone.now() if not email: raise ValueError('The given email must be set') email = self.normalize_email(email) user = self.model( email=email, password=password, is_active=True, is_superuser=is_superuser, last_login=now, date_joined=now, **extra_fields) user.set_password(password) user.save(using=self._db) return user
python
def _create_user(self, email, password, is_superuser, **extra_fields): """Create new user""" now = timezone.now() if not email: raise ValueError('The given email must be set') email = self.normalize_email(email) user = self.model( email=email, password=password, is_active=True, is_superuser=is_superuser, last_login=now, date_joined=now, **extra_fields) user.set_password(password) user.save(using=self._db) return user
[ "def", "_create_user", "(", "self", ",", "email", ",", "password", ",", "is_superuser", ",", "*", "*", "extra_fields", ")", ":", "now", "=", "timezone", ".", "now", "(", ")", "if", "not", "email", ":", "raise", "ValueError", "(", "'The given email must be set'", ")", "email", "=", "self", ".", "normalize_email", "(", "email", ")", "user", "=", "self", ".", "model", "(", "email", "=", "email", ",", "password", "=", "password", ",", "is_active", "=", "True", ",", "is_superuser", "=", "is_superuser", ",", "last_login", "=", "now", ",", "date_joined", "=", "now", ",", "*", "*", "extra_fields", ")", "user", ".", "set_password", "(", "password", ")", "user", ".", "save", "(", "using", "=", "self", ".", "_db", ")", "return", "user" ]
Create new user
[ "Create", "new", "user" ]
edac132cc0797190153f2e60bc7e88cb50e80da6
https://github.com/krukas/Trionyx/blob/edac132cc0797190153f2e60bc7e88cb50e80da6/trionyx/trionyx/models.py#L19-L35
242,773
krukas/Trionyx
trionyx/trionyx/models.py
User.get_full_name
def get_full_name(self): """Get full username if no name is set email is given""" if self.first_name and self.last_name: return "{} {}".format(self.first_name, self.last_name) return self.email
python
def get_full_name(self): """Get full username if no name is set email is given""" if self.first_name and self.last_name: return "{} {}".format(self.first_name, self.last_name) return self.email
[ "def", "get_full_name", "(", "self", ")", ":", "if", "self", ".", "first_name", "and", "self", ".", "last_name", ":", "return", "\"{} {}\"", ".", "format", "(", "self", ".", "first_name", ",", "self", ".", "last_name", ")", "return", "self", ".", "email" ]
Get full username if no name is set email is given
[ "Get", "full", "username", "if", "no", "name", "is", "set", "email", "is", "given" ]
edac132cc0797190153f2e60bc7e88cb50e80da6
https://github.com/krukas/Trionyx/blob/edac132cc0797190153f2e60bc7e88cb50e80da6/trionyx/trionyx/models.py#L64-L68
242,774
krukas/Trionyx
trionyx/trionyx/models.py
UserAttributeManager.set_attribute
def set_attribute(self, code, value): """Set attribute for user""" attr, _ = self.get_or_create(code=code) attr.value = value attr.save()
python
def set_attribute(self, code, value): """Set attribute for user""" attr, _ = self.get_or_create(code=code) attr.value = value attr.save()
[ "def", "set_attribute", "(", "self", ",", "code", ",", "value", ")", ":", "attr", ",", "_", "=", "self", ".", "get_or_create", "(", "code", "=", "code", ")", "attr", ".", "value", "=", "value", "attr", ".", "save", "(", ")" ]
Set attribute for user
[ "Set", "attribute", "for", "user" ]
edac132cc0797190153f2e60bc7e88cb50e80da6
https://github.com/krukas/Trionyx/blob/edac132cc0797190153f2e60bc7e88cb50e80da6/trionyx/trionyx/models.py#L84-L88
242,775
krukas/Trionyx
trionyx/trionyx/models.py
UserAttributeManager.get_attribute
def get_attribute(self, code, default=None): """Get attribute for user""" try: return self.get(code=code).value except models.ObjectDoesNotExist: return default
python
def get_attribute(self, code, default=None): """Get attribute for user""" try: return self.get(code=code).value except models.ObjectDoesNotExist: return default
[ "def", "get_attribute", "(", "self", ",", "code", ",", "default", "=", "None", ")", ":", "try", ":", "return", "self", ".", "get", "(", "code", "=", "code", ")", ".", "value", "except", "models", ".", "ObjectDoesNotExist", ":", "return", "default" ]
Get attribute for user
[ "Get", "attribute", "for", "user" ]
edac132cc0797190153f2e60bc7e88cb50e80da6
https://github.com/krukas/Trionyx/blob/edac132cc0797190153f2e60bc7e88cb50e80da6/trionyx/trionyx/models.py#L90-L95
242,776
musicmetric/mmpy
src/chart.py
Chart.next
def next(self): """ fetch the chart identified by this chart's next_id attribute if the next_id is either null or not present for this chart return None returns the new chart instance on sucess""" try: if self.next_id: return Chart(self.next_id) else: log.debug('attempted to get next chart, but none was found') return except AttributeError: #chart does not implement next pointer log.debug('attempted to get next chart from a chart without a next attribute') return None
python
def next(self): """ fetch the chart identified by this chart's next_id attribute if the next_id is either null or not present for this chart return None returns the new chart instance on sucess""" try: if self.next_id: return Chart(self.next_id) else: log.debug('attempted to get next chart, but none was found') return except AttributeError: #chart does not implement next pointer log.debug('attempted to get next chart from a chart without a next attribute') return None
[ "def", "next", "(", "self", ")", ":", "try", ":", "if", "self", ".", "next_id", ":", "return", "Chart", "(", "self", ".", "next_id", ")", "else", ":", "log", ".", "debug", "(", "'attempted to get next chart, but none was found'", ")", "return", "except", "AttributeError", ":", "#chart does not implement next pointer", "log", ".", "debug", "(", "'attempted to get next chart from a chart without a next attribute'", ")", "return", "None" ]
fetch the chart identified by this chart's next_id attribute if the next_id is either null or not present for this chart return None returns the new chart instance on sucess
[ "fetch", "the", "chart", "identified", "by", "this", "chart", "s", "next_id", "attribute", "if", "the", "next_id", "is", "either", "null", "or", "not", "present", "for", "this", "chart", "return", "None", "returns", "the", "new", "chart", "instance", "on", "sucess" ]
2b5d975c61f9ea8c7f19f76a90b59771833ef881
https://github.com/musicmetric/mmpy/blob/2b5d975c61f9ea8c7f19f76a90b59771833ef881/src/chart.py#L69-L83
242,777
musicmetric/mmpy
src/chart.py
Chart.previous
def previous(self): """ fetch the chart identified by this chart's previous_id attribute if the previous_id is either null or not present for this chart return None returns the new chart instance on sucess""" try: if self.previous_id: return Chart(self.previous_id) else: log.debug('attempted to get previous chart, but none was found') return except AttributeError: #chart does not implement next pointer log.debug('attempted to get previous chart from a chart without a previous attribute') return None
python
def previous(self): """ fetch the chart identified by this chart's previous_id attribute if the previous_id is either null or not present for this chart return None returns the new chart instance on sucess""" try: if self.previous_id: return Chart(self.previous_id) else: log.debug('attempted to get previous chart, but none was found') return except AttributeError: #chart does not implement next pointer log.debug('attempted to get previous chart from a chart without a previous attribute') return None
[ "def", "previous", "(", "self", ")", ":", "try", ":", "if", "self", ".", "previous_id", ":", "return", "Chart", "(", "self", ".", "previous_id", ")", "else", ":", "log", ".", "debug", "(", "'attempted to get previous chart, but none was found'", ")", "return", "except", "AttributeError", ":", "#chart does not implement next pointer", "log", ".", "debug", "(", "'attempted to get previous chart from a chart without a previous attribute'", ")", "return", "None" ]
fetch the chart identified by this chart's previous_id attribute if the previous_id is either null or not present for this chart return None returns the new chart instance on sucess
[ "fetch", "the", "chart", "identified", "by", "this", "chart", "s", "previous_id", "attribute", "if", "the", "previous_id", "is", "either", "null", "or", "not", "present", "for", "this", "chart", "return", "None", "returns", "the", "new", "chart", "instance", "on", "sucess" ]
2b5d975c61f9ea8c7f19f76a90b59771833ef881
https://github.com/musicmetric/mmpy/blob/2b5d975c61f9ea8c7f19f76a90b59771833ef881/src/chart.py#L85-L99
242,778
musicmetric/mmpy
src/chart.py
Chart.now
def now(self): """ fetch the chart identified by this chart's now_id attribute if the now_id is either null or not present for this chart return None returns the new chart instance on sucess""" try: if self.now_id: return Chart(self.now_id) else: log.debug('attempted to get current chart, but none was found') return except AttributeError: #chart does not implement next pointer log.debug('attempted to get current ("now") chart from a chart without a now attribute') return None
python
def now(self): """ fetch the chart identified by this chart's now_id attribute if the now_id is either null or not present for this chart return None returns the new chart instance on sucess""" try: if self.now_id: return Chart(self.now_id) else: log.debug('attempted to get current chart, but none was found') return except AttributeError: #chart does not implement next pointer log.debug('attempted to get current ("now") chart from a chart without a now attribute') return None
[ "def", "now", "(", "self", ")", ":", "try", ":", "if", "self", ".", "now_id", ":", "return", "Chart", "(", "self", ".", "now_id", ")", "else", ":", "log", ".", "debug", "(", "'attempted to get current chart, but none was found'", ")", "return", "except", "AttributeError", ":", "#chart does not implement next pointer", "log", ".", "debug", "(", "'attempted to get current (\"now\") chart from a chart without a now attribute'", ")", "return", "None" ]
fetch the chart identified by this chart's now_id attribute if the now_id is either null or not present for this chart return None returns the new chart instance on sucess
[ "fetch", "the", "chart", "identified", "by", "this", "chart", "s", "now_id", "attribute", "if", "the", "now_id", "is", "either", "null", "or", "not", "present", "for", "this", "chart", "return", "None", "returns", "the", "new", "chart", "instance", "on", "sucess" ]
2b5d975c61f9ea8c7f19f76a90b59771833ef881
https://github.com/musicmetric/mmpy/blob/2b5d975c61f9ea8c7f19f76a90b59771833ef881/src/chart.py#L101-L115
242,779
MacHu-GWU/angora-project
angora/dtypes/dicttree.py
DictTree.initial
def initial(key, **kwarg): """Create an empty dicttree. The root node has a special attribute "_rootname". Because root node is the only dictionary doesn't have key. So we assign the key as a special attribute. Usage:: >>> from weatherlab.lib.dtypes.dicttree import DictTree as DT >>> d = DT.initial("US) >>> d {'_meta': {'_rootname': 'US'}} """ d = dict() DictTree.setattr(d, _rootname = key, **kwarg) return d
python
def initial(key, **kwarg): """Create an empty dicttree. The root node has a special attribute "_rootname". Because root node is the only dictionary doesn't have key. So we assign the key as a special attribute. Usage:: >>> from weatherlab.lib.dtypes.dicttree import DictTree as DT >>> d = DT.initial("US) >>> d {'_meta': {'_rootname': 'US'}} """ d = dict() DictTree.setattr(d, _rootname = key, **kwarg) return d
[ "def", "initial", "(", "key", ",", "*", "*", "kwarg", ")", ":", "d", "=", "dict", "(", ")", "DictTree", ".", "setattr", "(", "d", ",", "_rootname", "=", "key", ",", "*", "*", "kwarg", ")", "return", "d" ]
Create an empty dicttree. The root node has a special attribute "_rootname". Because root node is the only dictionary doesn't have key. So we assign the key as a special attribute. Usage:: >>> from weatherlab.lib.dtypes.dicttree import DictTree as DT >>> d = DT.initial("US) >>> d {'_meta': {'_rootname': 'US'}}
[ "Create", "an", "empty", "dicttree", "." ]
689a60da51cd88680ddbe26e28dbe81e6b01d275
https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/dtypes/dicttree.py#L149-L165
242,780
MacHu-GWU/angora-project
angora/dtypes/dicttree.py
DictTree.setattr
def setattr(d, **kwarg): """Set an attribute. set attributes is actually add a special key, value pair in this dict under key = "_meta". Usage:: >>> DT.setattr(d, population=27800000) >>> d {'_meta': {'population': 27800000, '_rootname': 'US'}} """ if _meta not in d: d[_meta] = dict() for k, v in kwarg.items(): d[_meta][k] = v
python
def setattr(d, **kwarg): """Set an attribute. set attributes is actually add a special key, value pair in this dict under key = "_meta". Usage:: >>> DT.setattr(d, population=27800000) >>> d {'_meta': {'population': 27800000, '_rootname': 'US'}} """ if _meta not in d: d[_meta] = dict() for k, v in kwarg.items(): d[_meta][k] = v
[ "def", "setattr", "(", "d", ",", "*", "*", "kwarg", ")", ":", "if", "_meta", "not", "in", "d", ":", "d", "[", "_meta", "]", "=", "dict", "(", ")", "for", "k", ",", "v", "in", "kwarg", ".", "items", "(", ")", ":", "d", "[", "_meta", "]", "[", "k", "]", "=", "v" ]
Set an attribute. set attributes is actually add a special key, value pair in this dict under key = "_meta". Usage:: >>> DT.setattr(d, population=27800000) >>> d {'_meta': {'population': 27800000, '_rootname': 'US'}}
[ "Set", "an", "attribute", "." ]
689a60da51cd88680ddbe26e28dbe81e6b01d275
https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/dtypes/dicttree.py#L168-L183
242,781
MacHu-GWU/angora-project
angora/dtypes/dicttree.py
DictTree.add_children
def add_children(d, key, **kwarg): """Add a children with key and attributes. If children already EXISTS, OVERWRITE it. Usage:: >>> from pprint import pprint as ppt >>> DT.add_children(d, "VA", name="virginia", population=100*1000) >>> DT.add_children(d, "MD", name="maryland", population=200*1000) >>> ppt(d) {'_meta': {'population': 27800000, '_rootname': 'US'}, 'MD': {'_meta': {'name': 'maryland', 'population': 200000}}, 'VA': {'_meta': {'name': 'virginia', 'population': 100000}}} >>> DT.add_children(d["VA"], "arlington", name="arlington county", population=5000) >>> DT.add_children(d["VA"], "vienna", name="vienna county", population=5000) >>> DT.add_children(d["MD"], "bethesta", name="montgomery country", population=5800) >>> DT.add_children(d["MD"], "germentown", name="fredrick country", population=1400) >>> DT.add_children(d["VA"]["arlington"], "riverhouse", name="RiverHouse 1400", population=437) >>> DT.add_children(d["VA"]["arlington"], "crystal plaza", name="Crystal plaza South", population=681) >>> DT.add_children(d["VA"]["arlington"], "loft", name="loft hotel", population=216) >>> ppt(d) {'MD': {'_meta': {'name': 'maryland', 'population': 200000}, 'bethesta': {'_meta': {'name': 'montgomery country', 'population': 5800}}, 'germentown': {'_meta': {'name': 'fredrick country', 'population': 1400}}}, 'VA': {'_meta': {'name': 'virginia', 'population': 100000}, 'arlington': {'_meta': {'name': 'arlington county', 'population': 5000}, 'crystal plaza': {'_meta': {'name': 'Crystal plaza South', 'population': 681}}, 'loft': {'_meta': {'name': 'loft hotel', 'population': 216}}, 'riverhouse': {'_meta': {'name': 'RiverHouse 1400', 'population': 437}}}, 'vienna': {'_meta': {'name': 'vienna county', 'population': 1500}}}, '_meta': {'_rootname': 'US', 'population': 27800000.0}} """ if kwarg: d[key] = {_meta: kwarg} else: d[key] = dict()
python
def add_children(d, key, **kwarg): """Add a children with key and attributes. If children already EXISTS, OVERWRITE it. Usage:: >>> from pprint import pprint as ppt >>> DT.add_children(d, "VA", name="virginia", population=100*1000) >>> DT.add_children(d, "MD", name="maryland", population=200*1000) >>> ppt(d) {'_meta': {'population': 27800000, '_rootname': 'US'}, 'MD': {'_meta': {'name': 'maryland', 'population': 200000}}, 'VA': {'_meta': {'name': 'virginia', 'population': 100000}}} >>> DT.add_children(d["VA"], "arlington", name="arlington county", population=5000) >>> DT.add_children(d["VA"], "vienna", name="vienna county", population=5000) >>> DT.add_children(d["MD"], "bethesta", name="montgomery country", population=5800) >>> DT.add_children(d["MD"], "germentown", name="fredrick country", population=1400) >>> DT.add_children(d["VA"]["arlington"], "riverhouse", name="RiverHouse 1400", population=437) >>> DT.add_children(d["VA"]["arlington"], "crystal plaza", name="Crystal plaza South", population=681) >>> DT.add_children(d["VA"]["arlington"], "loft", name="loft hotel", population=216) >>> ppt(d) {'MD': {'_meta': {'name': 'maryland', 'population': 200000}, 'bethesta': {'_meta': {'name': 'montgomery country', 'population': 5800}}, 'germentown': {'_meta': {'name': 'fredrick country', 'population': 1400}}}, 'VA': {'_meta': {'name': 'virginia', 'population': 100000}, 'arlington': {'_meta': {'name': 'arlington county', 'population': 5000}, 'crystal plaza': {'_meta': {'name': 'Crystal plaza South', 'population': 681}}, 'loft': {'_meta': {'name': 'loft hotel', 'population': 216}}, 'riverhouse': {'_meta': {'name': 'RiverHouse 1400', 'population': 437}}}, 'vienna': {'_meta': {'name': 'vienna county', 'population': 1500}}}, '_meta': {'_rootname': 'US', 'population': 27800000.0}} """ if kwarg: d[key] = {_meta: kwarg} else: d[key] = dict()
[ "def", "add_children", "(", "d", ",", "key", ",", "*", "*", "kwarg", ")", ":", "if", "kwarg", ":", "d", "[", "key", "]", "=", "{", "_meta", ":", "kwarg", "}", "else", ":", "d", "[", "key", "]", "=", "dict", "(", ")" ]
Add a children with key and attributes. If children already EXISTS, OVERWRITE it. Usage:: >>> from pprint import pprint as ppt >>> DT.add_children(d, "VA", name="virginia", population=100*1000) >>> DT.add_children(d, "MD", name="maryland", population=200*1000) >>> ppt(d) {'_meta': {'population': 27800000, '_rootname': 'US'}, 'MD': {'_meta': {'name': 'maryland', 'population': 200000}}, 'VA': {'_meta': {'name': 'virginia', 'population': 100000}}} >>> DT.add_children(d["VA"], "arlington", name="arlington county", population=5000) >>> DT.add_children(d["VA"], "vienna", name="vienna county", population=5000) >>> DT.add_children(d["MD"], "bethesta", name="montgomery country", population=5800) >>> DT.add_children(d["MD"], "germentown", name="fredrick country", population=1400) >>> DT.add_children(d["VA"]["arlington"], "riverhouse", name="RiverHouse 1400", population=437) >>> DT.add_children(d["VA"]["arlington"], "crystal plaza", name="Crystal plaza South", population=681) >>> DT.add_children(d["VA"]["arlington"], "loft", name="loft hotel", population=216) >>> ppt(d) {'MD': {'_meta': {'name': 'maryland', 'population': 200000}, 'bethesta': {'_meta': {'name': 'montgomery country', 'population': 5800}}, 'germentown': {'_meta': {'name': 'fredrick country', 'population': 1400}}}, 'VA': {'_meta': {'name': 'virginia', 'population': 100000}, 'arlington': {'_meta': {'name': 'arlington county', 'population': 5000}, 'crystal plaza': {'_meta': {'name': 'Crystal plaza South', 'population': 681}}, 'loft': {'_meta': {'name': 'loft hotel', 'population': 216}}, 'riverhouse': {'_meta': {'name': 'RiverHouse 1400', 'population': 437}}}, 'vienna': {'_meta': {'name': 'vienna county', 'population': 1500}}}, '_meta': {'_rootname': 'US', 'population': 27800000.0}}
[ "Add", "a", "children", "with", "key", "and", "attributes", ".", "If", "children", "already", "EXISTS", "OVERWRITE", "it", "." ]
689a60da51cd88680ddbe26e28dbe81e6b01d275
https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/dtypes/dicttree.py#L197-L248
242,782
MacHu-GWU/angora-project
angora/dtypes/dicttree.py
DictTree.del_depth
def del_depth(d, depth): """Delete all the nodes on specific depth in this dict """ for node in DictTree.v_depth(d, depth-1): for key in [key for key in DictTree.k(node)]: del node[key]
python
def del_depth(d, depth): """Delete all the nodes on specific depth in this dict """ for node in DictTree.v_depth(d, depth-1): for key in [key for key in DictTree.k(node)]: del node[key]
[ "def", "del_depth", "(", "d", ",", "depth", ")", ":", "for", "node", "in", "DictTree", ".", "v_depth", "(", "d", ",", "depth", "-", "1", ")", ":", "for", "key", "in", "[", "key", "for", "key", "in", "DictTree", ".", "k", "(", "node", ")", "]", ":", "del", "node", "[", "key", "]" ]
Delete all the nodes on specific depth in this dict
[ "Delete", "all", "the", "nodes", "on", "specific", "depth", "in", "this", "dict" ]
689a60da51cd88680ddbe26e28dbe81e6b01d275
https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/dtypes/dicttree.py#L370-L375
242,783
MacHu-GWU/angora-project
angora/dtypes/dicttree.py
DictTree.prettyprint
def prettyprint(d): """Print dicttree in Json-like format. keys are sorted """ print(json.dumps(d, sort_keys=True, indent=4, separators=("," , ": ")))
python
def prettyprint(d): """Print dicttree in Json-like format. keys are sorted """ print(json.dumps(d, sort_keys=True, indent=4, separators=("," , ": ")))
[ "def", "prettyprint", "(", "d", ")", ":", "print", "(", "json", ".", "dumps", "(", "d", ",", "sort_keys", "=", "True", ",", "indent", "=", "4", ",", "separators", "=", "(", "\",\"", ",", "\": \"", ")", ")", ")" ]
Print dicttree in Json-like format. keys are sorted
[ "Print", "dicttree", "in", "Json", "-", "like", "format", ".", "keys", "are", "sorted" ]
689a60da51cd88680ddbe26e28dbe81e6b01d275
https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/dtypes/dicttree.py#L378-L382
242,784
MacHu-GWU/angora-project
angora/dtypes/dicttree.py
DictTree.stats_on_depth
def stats_on_depth(d, depth): """Display the node stats info on specific depth in this dict """ root_nodes, leaf_nodes = 0, 0 for _, node in DictTree.kv_depth(d, depth): if DictTree.length(node) == 0: leaf_nodes += 1 else: root_nodes += 1 total = root_nodes + leaf_nodes print("On depth %s, having %s root nodes, %s leaf nodes. " "%s nodes in total." % (depth, root_nodes, leaf_nodes, total))
python
def stats_on_depth(d, depth): """Display the node stats info on specific depth in this dict """ root_nodes, leaf_nodes = 0, 0 for _, node in DictTree.kv_depth(d, depth): if DictTree.length(node) == 0: leaf_nodes += 1 else: root_nodes += 1 total = root_nodes + leaf_nodes print("On depth %s, having %s root nodes, %s leaf nodes. " "%s nodes in total." % (depth, root_nodes, leaf_nodes, total))
[ "def", "stats_on_depth", "(", "d", ",", "depth", ")", ":", "root_nodes", ",", "leaf_nodes", "=", "0", ",", "0", "for", "_", ",", "node", "in", "DictTree", ".", "kv_depth", "(", "d", ",", "depth", ")", ":", "if", "DictTree", ".", "length", "(", "node", ")", "==", "0", ":", "leaf_nodes", "+=", "1", "else", ":", "root_nodes", "+=", "1", "total", "=", "root_nodes", "+", "leaf_nodes", "print", "(", "\"On depth %s, having %s root nodes, %s leaf nodes. \"", "\"%s nodes in total.\"", "%", "(", "depth", ",", "root_nodes", ",", "leaf_nodes", ",", "total", ")", ")" ]
Display the node stats info on specific depth in this dict
[ "Display", "the", "node", "stats", "info", "on", "specific", "depth", "in", "this", "dict" ]
689a60da51cd88680ddbe26e28dbe81e6b01d275
https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/dtypes/dicttree.py#L385-L396
242,785
hobson/pug-dj
pug/dj/db_routers.py
AppRouter.db_for_read
def db_for_read(self, model, **hints): """ If the app has its own database, use it for reads """ if model._meta.app_label in self._apps: return getattr(model, '_db_alias', model._meta.app_label) return None
python
def db_for_read(self, model, **hints): """ If the app has its own database, use it for reads """ if model._meta.app_label in self._apps: return getattr(model, '_db_alias', model._meta.app_label) return None
[ "def", "db_for_read", "(", "self", ",", "model", ",", "*", "*", "hints", ")", ":", "if", "model", ".", "_meta", ".", "app_label", "in", "self", ".", "_apps", ":", "return", "getattr", "(", "model", ",", "'_db_alias'", ",", "model", ".", "_meta", ".", "app_label", ")", "return", "None" ]
If the app has its own database, use it for reads
[ "If", "the", "app", "has", "its", "own", "database", "use", "it", "for", "reads" ]
55678b08755a55366ce18e7d3b8ea8fa4491ab04
https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/db_routers.py#L20-L26
242,786
hobson/pug-dj
pug/dj/db_routers.py
AppRouter.db_for_write
def db_for_write(self, model, **hints): """ If the app has its own database, use it for writes """ if model._meta.app_label in self._apps: return getattr(model, '_db_alias', model._meta.app_label) return None
python
def db_for_write(self, model, **hints): """ If the app has its own database, use it for writes """ if model._meta.app_label in self._apps: return getattr(model, '_db_alias', model._meta.app_label) return None
[ "def", "db_for_write", "(", "self", ",", "model", ",", "*", "*", "hints", ")", ":", "if", "model", ".", "_meta", ".", "app_label", "in", "self", ".", "_apps", ":", "return", "getattr", "(", "model", ",", "'_db_alias'", ",", "model", ".", "_meta", ".", "app_label", ")", "return", "None" ]
If the app has its own database, use it for writes
[ "If", "the", "app", "has", "its", "own", "database", "use", "it", "for", "writes" ]
55678b08755a55366ce18e7d3b8ea8fa4491ab04
https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/db_routers.py#L28-L34
242,787
hobson/pug-dj
pug/dj/db_routers.py
AppRouter.allow_migrate
def allow_migrate(self, db, model): """ Make sure self._apps go to their own db """ if model._meta.app_label in self._apps: return getattr(model, '_db_alias', model._meta.app_label) == db return None
python
def allow_migrate(self, db, model): """ Make sure self._apps go to their own db """ if model._meta.app_label in self._apps: return getattr(model, '_db_alias', model._meta.app_label) == db return None
[ "def", "allow_migrate", "(", "self", ",", "db", ",", "model", ")", ":", "if", "model", ".", "_meta", ".", "app_label", "in", "self", ".", "_apps", ":", "return", "getattr", "(", "model", ",", "'_db_alias'", ",", "model", ".", "_meta", ".", "app_label", ")", "==", "db", "return", "None" ]
Make sure self._apps go to their own db
[ "Make", "sure", "self", ".", "_apps", "go", "to", "their", "own", "db" ]
55678b08755a55366ce18e7d3b8ea8fa4491ab04
https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/db_routers.py#L44-L50
242,788
joaopcanario/imports
imports/imports.py
check
def check(path_dir, requirements_name='requirements.txt'): '''Look for unused packages listed on project requirements''' requirements = _load_requirements(requirements_name, path_dir) imported_modules = _iter_modules(path_dir) installed_packages = _list_installed_packages() imported_modules.update(_excluded_imports()) diff = {lib for lib in installed_packages if lib not in imported_modules} with_dependencies, _ = _list_dependencies(diff) unused_dependencies = sorted([d for d in diff if d in requirements]) for unused_dependency in unused_dependencies: if with_dependencies.get(unused_dependency): print(' - {}'.format(unused_dependency)) for dependency in with_dependencies.get(unused_dependency): print('\t - {}'.format(dependency)) else: print(' - {}'.format(unused_dependency))
python
def check(path_dir, requirements_name='requirements.txt'): '''Look for unused packages listed on project requirements''' requirements = _load_requirements(requirements_name, path_dir) imported_modules = _iter_modules(path_dir) installed_packages = _list_installed_packages() imported_modules.update(_excluded_imports()) diff = {lib for lib in installed_packages if lib not in imported_modules} with_dependencies, _ = _list_dependencies(diff) unused_dependencies = sorted([d for d in diff if d in requirements]) for unused_dependency in unused_dependencies: if with_dependencies.get(unused_dependency): print(' - {}'.format(unused_dependency)) for dependency in with_dependencies.get(unused_dependency): print('\t - {}'.format(dependency)) else: print(' - {}'.format(unused_dependency))
[ "def", "check", "(", "path_dir", ",", "requirements_name", "=", "'requirements.txt'", ")", ":", "requirements", "=", "_load_requirements", "(", "requirements_name", ",", "path_dir", ")", "imported_modules", "=", "_iter_modules", "(", "path_dir", ")", "installed_packages", "=", "_list_installed_packages", "(", ")", "imported_modules", ".", "update", "(", "_excluded_imports", "(", ")", ")", "diff", "=", "{", "lib", "for", "lib", "in", "installed_packages", "if", "lib", "not", "in", "imported_modules", "}", "with_dependencies", ",", "_", "=", "_list_dependencies", "(", "diff", ")", "unused_dependencies", "=", "sorted", "(", "[", "d", "for", "d", "in", "diff", "if", "d", "in", "requirements", "]", ")", "for", "unused_dependency", "in", "unused_dependencies", ":", "if", "with_dependencies", ".", "get", "(", "unused_dependency", ")", ":", "print", "(", "' - {}'", ".", "format", "(", "unused_dependency", ")", ")", "for", "dependency", "in", "with_dependencies", ".", "get", "(", "unused_dependency", ")", ":", "print", "(", "'\\t - {}'", ".", "format", "(", "dependency", ")", ")", "else", ":", "print", "(", "' - {}'", ".", "format", "(", "unused_dependency", ")", ")" ]
Look for unused packages listed on project requirements
[ "Look", "for", "unused", "packages", "listed", "on", "project", "requirements" ]
46db0d3d2aa55427027bf0e91d61a24d52730337
https://github.com/joaopcanario/imports/blob/46db0d3d2aa55427027bf0e91d61a24d52730337/imports/imports.py#L94-L112
242,789
jhorman/pledge
pledge/__init__.py
pre
def pre(cond): """ Add a precondition check to the annotated method. The condition is passed the arguments from the annotated method. It does not need to accept all of the methods parameters. The condition is inspected to figure out which parameters to pass. """ cond_args, cond_varargs, cond_varkw, cond_defaults = inspect.getargspec(cond) source = inspect.getsource(cond).strip() def inner(f): if enabled: # deal with the real function, not a wrapper f = getattr(f, 'wrapped_fn', f) # need to check if 'self' is the first arg, # since @pre doesn't want the self param member_function = is_member_function(f) # need metadata for checking defaults method_args, method_defaults = inspect.getargspec(f)[0::3] def check_condition(args, kwargs): cond_kwargs = {} if method_defaults is not None and len(method_defaults) > 0 \ and len(method_args) - len(method_defaults) <= len(args) < len(method_args): args += method_defaults[len(args) - len(method_args):] # collection the args for name, value in zip(cond_args, args[member_function:]): cond_kwargs[name] = value # collect the remaining kwargs for name in cond_args: if name not in cond_kwargs: cond_kwargs[name] = kwargs.get(name) # test the precondition if not cond(**cond_kwargs): # otherwise raise the exception raise AssertionError('Precondition failure, %s' % source) # append to the rest of the preconditions attached to this method if not hasattr(f, 'preconditions'): f.preconditions = [] f.preconditions.append(check_condition) return check(f) else: return f return inner
python
def pre(cond): """ Add a precondition check to the annotated method. The condition is passed the arguments from the annotated method. It does not need to accept all of the methods parameters. The condition is inspected to figure out which parameters to pass. """ cond_args, cond_varargs, cond_varkw, cond_defaults = inspect.getargspec(cond) source = inspect.getsource(cond).strip() def inner(f): if enabled: # deal with the real function, not a wrapper f = getattr(f, 'wrapped_fn', f) # need to check if 'self' is the first arg, # since @pre doesn't want the self param member_function = is_member_function(f) # need metadata for checking defaults method_args, method_defaults = inspect.getargspec(f)[0::3] def check_condition(args, kwargs): cond_kwargs = {} if method_defaults is not None and len(method_defaults) > 0 \ and len(method_args) - len(method_defaults) <= len(args) < len(method_args): args += method_defaults[len(args) - len(method_args):] # collection the args for name, value in zip(cond_args, args[member_function:]): cond_kwargs[name] = value # collect the remaining kwargs for name in cond_args: if name not in cond_kwargs: cond_kwargs[name] = kwargs.get(name) # test the precondition if not cond(**cond_kwargs): # otherwise raise the exception raise AssertionError('Precondition failure, %s' % source) # append to the rest of the preconditions attached to this method if not hasattr(f, 'preconditions'): f.preconditions = [] f.preconditions.append(check_condition) return check(f) else: return f return inner
[ "def", "pre", "(", "cond", ")", ":", "cond_args", ",", "cond_varargs", ",", "cond_varkw", ",", "cond_defaults", "=", "inspect", ".", "getargspec", "(", "cond", ")", "source", "=", "inspect", ".", "getsource", "(", "cond", ")", ".", "strip", "(", ")", "def", "inner", "(", "f", ")", ":", "if", "enabled", ":", "# deal with the real function, not a wrapper", "f", "=", "getattr", "(", "f", ",", "'wrapped_fn'", ",", "f", ")", "# need to check if 'self' is the first arg,", "# since @pre doesn't want the self param", "member_function", "=", "is_member_function", "(", "f", ")", "# need metadata for checking defaults", "method_args", ",", "method_defaults", "=", "inspect", ".", "getargspec", "(", "f", ")", "[", "0", ":", ":", "3", "]", "def", "check_condition", "(", "args", ",", "kwargs", ")", ":", "cond_kwargs", "=", "{", "}", "if", "method_defaults", "is", "not", "None", "and", "len", "(", "method_defaults", ")", ">", "0", "and", "len", "(", "method_args", ")", "-", "len", "(", "method_defaults", ")", "<=", "len", "(", "args", ")", "<", "len", "(", "method_args", ")", ":", "args", "+=", "method_defaults", "[", "len", "(", "args", ")", "-", "len", "(", "method_args", ")", ":", "]", "# collection the args", "for", "name", ",", "value", "in", "zip", "(", "cond_args", ",", "args", "[", "member_function", ":", "]", ")", ":", "cond_kwargs", "[", "name", "]", "=", "value", "# collect the remaining kwargs", "for", "name", "in", "cond_args", ":", "if", "name", "not", "in", "cond_kwargs", ":", "cond_kwargs", "[", "name", "]", "=", "kwargs", ".", "get", "(", "name", ")", "# test the precondition", "if", "not", "cond", "(", "*", "*", "cond_kwargs", ")", ":", "# otherwise raise the exception", "raise", "AssertionError", "(", "'Precondition failure, %s'", "%", "source", ")", "# append to the rest of the preconditions attached to this method", "if", "not", "hasattr", "(", "f", ",", "'preconditions'", ")", ":", "f", ".", "preconditions", "=", "[", "]", "f", ".", "preconditions", ".", "append", "(", "check_condition", ")", "return", "check", "(", "f", ")", "else", ":", "return", "f", "return", "inner" ]
Add a precondition check to the annotated method. The condition is passed the arguments from the annotated method. It does not need to accept all of the methods parameters. The condition is inspected to figure out which parameters to pass.
[ "Add", "a", "precondition", "check", "to", "the", "annotated", "method", ".", "The", "condition", "is", "passed", "the", "arguments", "from", "the", "annotated", "method", ".", "It", "does", "not", "need", "to", "accept", "all", "of", "the", "methods", "parameters", ".", "The", "condition", "is", "inspected", "to", "figure", "out", "which", "parameters", "to", "pass", "." ]
062ba5b788aeb15e68c85a329374a50b4618544d
https://github.com/jhorman/pledge/blob/062ba5b788aeb15e68c85a329374a50b4618544d/pledge/__init__.py#L24-L76
242,790
jhorman/pledge
pledge/__init__.py
post
def post(cond): """ Add a postcondition check to the annotated method. The condition is passed the return value of the annotated method. """ source = inspect.getsource(cond).strip() def inner(f): if enabled: # deal with the real function, not a wrapper f = getattr(f, 'wrapped_fn', f) def check_condition(result): if not cond(result): raise AssertionError('Postcondition failure, %s' % source) # append to the rest of the postconditions attached to this method if not hasattr(f, 'postconditions'): f.postconditions = [] f.postconditions.append(check_condition) return check(f) else: return f return inner
python
def post(cond): """ Add a postcondition check to the annotated method. The condition is passed the return value of the annotated method. """ source = inspect.getsource(cond).strip() def inner(f): if enabled: # deal with the real function, not a wrapper f = getattr(f, 'wrapped_fn', f) def check_condition(result): if not cond(result): raise AssertionError('Postcondition failure, %s' % source) # append to the rest of the postconditions attached to this method if not hasattr(f, 'postconditions'): f.postconditions = [] f.postconditions.append(check_condition) return check(f) else: return f return inner
[ "def", "post", "(", "cond", ")", ":", "source", "=", "inspect", ".", "getsource", "(", "cond", ")", ".", "strip", "(", ")", "def", "inner", "(", "f", ")", ":", "if", "enabled", ":", "# deal with the real function, not a wrapper", "f", "=", "getattr", "(", "f", ",", "'wrapped_fn'", ",", "f", ")", "def", "check_condition", "(", "result", ")", ":", "if", "not", "cond", "(", "result", ")", ":", "raise", "AssertionError", "(", "'Postcondition failure, %s'", "%", "source", ")", "# append to the rest of the postconditions attached to this method", "if", "not", "hasattr", "(", "f", ",", "'postconditions'", ")", ":", "f", ".", "postconditions", "=", "[", "]", "f", ".", "postconditions", ".", "append", "(", "check_condition", ")", "return", "check", "(", "f", ")", "else", ":", "return", "f", "return", "inner" ]
Add a postcondition check to the annotated method. The condition is passed the return value of the annotated method.
[ "Add", "a", "postcondition", "check", "to", "the", "annotated", "method", ".", "The", "condition", "is", "passed", "the", "return", "value", "of", "the", "annotated", "method", "." ]
062ba5b788aeb15e68c85a329374a50b4618544d
https://github.com/jhorman/pledge/blob/062ba5b788aeb15e68c85a329374a50b4618544d/pledge/__init__.py#L78-L103
242,791
jhorman/pledge
pledge/__init__.py
takes
def takes(*type_list): """ Decorates a function with type checks. Examples @takes(int): take an int as the first param @takes(int, str): take and int as first, string as 2nd @takes(int, (int, None)): take an int as first, and an int or None as second """ def inner(f): if enabled: # deal with the real function, not a wrapper f = getattr(f, 'wrapped_fn', f) # need to check if 'self' is the first arg, # since @pre doesn't want the self param member_function = is_member_function(f) # need metadata for defaults check method_args, method_defaults = inspect.getargspec(f)[0::3] if member_function: method_args = method_args[member_function:] def check_condition(args, kwargs): if method_defaults is not None and len(method_defaults) > 0 \ and len(method_args) - len(method_defaults) <= len(args) < len(method_args): args += method_defaults[len(args) - len(method_args):] for i, (arg, t) in enumerate(zip(args[member_function:], type_list)): method_arg = method_args[i] if method_arg not in kwargs and not check_type(t, arg): raise AssertionError('Precondition failure, wrong type for argument') for kwarg in kwargs: arg_position = method_args.index(kwarg) if arg_position < len(type_list): t = type_list[arg_position] if not check_type(t, kwargs.get(kwarg)): raise AssertionError('Precondition failure, wrong type for argument %s' % kwarg) # append to the rest of the postconditions attached to this method if not hasattr(f, 'preconditions'): f.preconditions = [] f.preconditions.append(check_condition) return check(f) else: return f return inner
python
def takes(*type_list): """ Decorates a function with type checks. Examples @takes(int): take an int as the first param @takes(int, str): take and int as first, string as 2nd @takes(int, (int, None)): take an int as first, and an int or None as second """ def inner(f): if enabled: # deal with the real function, not a wrapper f = getattr(f, 'wrapped_fn', f) # need to check if 'self' is the first arg, # since @pre doesn't want the self param member_function = is_member_function(f) # need metadata for defaults check method_args, method_defaults = inspect.getargspec(f)[0::3] if member_function: method_args = method_args[member_function:] def check_condition(args, kwargs): if method_defaults is not None and len(method_defaults) > 0 \ and len(method_args) - len(method_defaults) <= len(args) < len(method_args): args += method_defaults[len(args) - len(method_args):] for i, (arg, t) in enumerate(zip(args[member_function:], type_list)): method_arg = method_args[i] if method_arg not in kwargs and not check_type(t, arg): raise AssertionError('Precondition failure, wrong type for argument') for kwarg in kwargs: arg_position = method_args.index(kwarg) if arg_position < len(type_list): t = type_list[arg_position] if not check_type(t, kwargs.get(kwarg)): raise AssertionError('Precondition failure, wrong type for argument %s' % kwarg) # append to the rest of the postconditions attached to this method if not hasattr(f, 'preconditions'): f.preconditions = [] f.preconditions.append(check_condition) return check(f) else: return f return inner
[ "def", "takes", "(", "*", "type_list", ")", ":", "def", "inner", "(", "f", ")", ":", "if", "enabled", ":", "# deal with the real function, not a wrapper", "f", "=", "getattr", "(", "f", ",", "'wrapped_fn'", ",", "f", ")", "# need to check if 'self' is the first arg,", "# since @pre doesn't want the self param", "member_function", "=", "is_member_function", "(", "f", ")", "# need metadata for defaults check", "method_args", ",", "method_defaults", "=", "inspect", ".", "getargspec", "(", "f", ")", "[", "0", ":", ":", "3", "]", "if", "member_function", ":", "method_args", "=", "method_args", "[", "member_function", ":", "]", "def", "check_condition", "(", "args", ",", "kwargs", ")", ":", "if", "method_defaults", "is", "not", "None", "and", "len", "(", "method_defaults", ")", ">", "0", "and", "len", "(", "method_args", ")", "-", "len", "(", "method_defaults", ")", "<=", "len", "(", "args", ")", "<", "len", "(", "method_args", ")", ":", "args", "+=", "method_defaults", "[", "len", "(", "args", ")", "-", "len", "(", "method_args", ")", ":", "]", "for", "i", ",", "(", "arg", ",", "t", ")", "in", "enumerate", "(", "zip", "(", "args", "[", "member_function", ":", "]", ",", "type_list", ")", ")", ":", "method_arg", "=", "method_args", "[", "i", "]", "if", "method_arg", "not", "in", "kwargs", "and", "not", "check_type", "(", "t", ",", "arg", ")", ":", "raise", "AssertionError", "(", "'Precondition failure, wrong type for argument'", ")", "for", "kwarg", "in", "kwargs", ":", "arg_position", "=", "method_args", ".", "index", "(", "kwarg", ")", "if", "arg_position", "<", "len", "(", "type_list", ")", ":", "t", "=", "type_list", "[", "arg_position", "]", "if", "not", "check_type", "(", "t", ",", "kwargs", ".", "get", "(", "kwarg", ")", ")", ":", "raise", "AssertionError", "(", "'Precondition failure, wrong type for argument %s'", "%", "kwarg", ")", "# append to the rest of the postconditions attached to this method", "if", "not", "hasattr", "(", "f", ",", "'preconditions'", ")", ":", "f", ".", "preconditions", "=", "[", "]", "f", ".", "preconditions", ".", "append", "(", "check_condition", ")", "return", "check", "(", "f", ")", "else", ":", "return", "f", "return", "inner" ]
Decorates a function with type checks. Examples @takes(int): take an int as the first param @takes(int, str): take and int as first, string as 2nd @takes(int, (int, None)): take an int as first, and an int or None as second
[ "Decorates", "a", "function", "with", "type", "checks", ".", "Examples" ]
062ba5b788aeb15e68c85a329374a50b4618544d
https://github.com/jhorman/pledge/blob/062ba5b788aeb15e68c85a329374a50b4618544d/pledge/__init__.py#L105-L153
242,792
jhorman/pledge
pledge/__init__.py
check_conditions
def check_conditions(f, args, kwargs): """ This is what runs all of the conditions attached to a method, along with the conditions on the superclasses. """ member_function = is_member_function(f) # check the functions direct pre conditions check_preconditions(f, args, kwargs) # for member functions check the pre conditions up the chain base_classes = [] if member_function: base_classes = inspect.getmro(type(args[0]))[1:-1] for clz in base_classes: super_fn = getattr(clz, f.func_name, None) check_preconditions(super_fn, args, kwargs) # run the real function return_value = f(*args, **kwargs) # check the functions direct post conditions check_postconditions(f, return_value) # for member functions check the post conditions up the chain if member_function: for clz in base_classes: super_fn = getattr(clz, f.func_name, None) check_postconditions(super_fn, return_value) return return_value
python
def check_conditions(f, args, kwargs): """ This is what runs all of the conditions attached to a method, along with the conditions on the superclasses. """ member_function = is_member_function(f) # check the functions direct pre conditions check_preconditions(f, args, kwargs) # for member functions check the pre conditions up the chain base_classes = [] if member_function: base_classes = inspect.getmro(type(args[0]))[1:-1] for clz in base_classes: super_fn = getattr(clz, f.func_name, None) check_preconditions(super_fn, args, kwargs) # run the real function return_value = f(*args, **kwargs) # check the functions direct post conditions check_postconditions(f, return_value) # for member functions check the post conditions up the chain if member_function: for clz in base_classes: super_fn = getattr(clz, f.func_name, None) check_postconditions(super_fn, return_value) return return_value
[ "def", "check_conditions", "(", "f", ",", "args", ",", "kwargs", ")", ":", "member_function", "=", "is_member_function", "(", "f", ")", "# check the functions direct pre conditions", "check_preconditions", "(", "f", ",", "args", ",", "kwargs", ")", "# for member functions check the pre conditions up the chain", "base_classes", "=", "[", "]", "if", "member_function", ":", "base_classes", "=", "inspect", ".", "getmro", "(", "type", "(", "args", "[", "0", "]", ")", ")", "[", "1", ":", "-", "1", "]", "for", "clz", "in", "base_classes", ":", "super_fn", "=", "getattr", "(", "clz", ",", "f", ".", "func_name", ",", "None", ")", "check_preconditions", "(", "super_fn", ",", "args", ",", "kwargs", ")", "# run the real function", "return_value", "=", "f", "(", "*", "args", ",", "*", "*", "kwargs", ")", "# check the functions direct post conditions", "check_postconditions", "(", "f", ",", "return_value", ")", "# for member functions check the post conditions up the chain", "if", "member_function", ":", "for", "clz", "in", "base_classes", ":", "super_fn", "=", "getattr", "(", "clz", ",", "f", ".", "func_name", ",", "None", ")", "check_postconditions", "(", "super_fn", ",", "return_value", ")", "return", "return_value" ]
This is what runs all of the conditions attached to a method, along with the conditions on the superclasses.
[ "This", "is", "what", "runs", "all", "of", "the", "conditions", "attached", "to", "a", "method", "along", "with", "the", "conditions", "on", "the", "superclasses", "." ]
062ba5b788aeb15e68c85a329374a50b4618544d
https://github.com/jhorman/pledge/blob/062ba5b788aeb15e68c85a329374a50b4618544d/pledge/__init__.py#L185-L215
242,793
jhorman/pledge
pledge/__init__.py
check_preconditions
def check_preconditions(f, args, kwargs): """ Runs all of the preconditions. """ f = getattr(f, 'wrapped_fn', f) if f and hasattr(f, 'preconditions'): for cond in f.preconditions: cond(args, kwargs)
python
def check_preconditions(f, args, kwargs): """ Runs all of the preconditions. """ f = getattr(f, 'wrapped_fn', f) if f and hasattr(f, 'preconditions'): for cond in f.preconditions: cond(args, kwargs)
[ "def", "check_preconditions", "(", "f", ",", "args", ",", "kwargs", ")", ":", "f", "=", "getattr", "(", "f", ",", "'wrapped_fn'", ",", "f", ")", "if", "f", "and", "hasattr", "(", "f", ",", "'preconditions'", ")", ":", "for", "cond", "in", "f", ".", "preconditions", ":", "cond", "(", "args", ",", "kwargs", ")" ]
Runs all of the preconditions.
[ "Runs", "all", "of", "the", "preconditions", "." ]
062ba5b788aeb15e68c85a329374a50b4618544d
https://github.com/jhorman/pledge/blob/062ba5b788aeb15e68c85a329374a50b4618544d/pledge/__init__.py#L217-L222
242,794
jhorman/pledge
pledge/__init__.py
check_postconditions
def check_postconditions(f, return_value): """ Runs all of the postconditions. """ f = getattr(f, 'wrapped_fn', f) if f and hasattr(f, 'postconditions'): for cond in f.postconditions: cond(return_value)
python
def check_postconditions(f, return_value): """ Runs all of the postconditions. """ f = getattr(f, 'wrapped_fn', f) if f and hasattr(f, 'postconditions'): for cond in f.postconditions: cond(return_value)
[ "def", "check_postconditions", "(", "f", ",", "return_value", ")", ":", "f", "=", "getattr", "(", "f", ",", "'wrapped_fn'", ",", "f", ")", "if", "f", "and", "hasattr", "(", "f", ",", "'postconditions'", ")", ":", "for", "cond", "in", "f", ".", "postconditions", ":", "cond", "(", "return_value", ")" ]
Runs all of the postconditions.
[ "Runs", "all", "of", "the", "postconditions", "." ]
062ba5b788aeb15e68c85a329374a50b4618544d
https://github.com/jhorman/pledge/blob/062ba5b788aeb15e68c85a329374a50b4618544d/pledge/__init__.py#L224-L229
242,795
jhorman/pledge
pledge/__init__.py
is_member_function
def is_member_function(f): """ Checks if the first argument to the method is 'self'. """ f_args, f_varargs, f_varkw, f_defaults = inspect.getargspec(f) return 1 if 'self' in f_args else 0
python
def is_member_function(f): """ Checks if the first argument to the method is 'self'. """ f_args, f_varargs, f_varkw, f_defaults = inspect.getargspec(f) return 1 if 'self' in f_args else 0
[ "def", "is_member_function", "(", "f", ")", ":", "f_args", ",", "f_varargs", ",", "f_varkw", ",", "f_defaults", "=", "inspect", ".", "getargspec", "(", "f", ")", "return", "1", "if", "'self'", "in", "f_args", "else", "0" ]
Checks if the first argument to the method is 'self'.
[ "Checks", "if", "the", "first", "argument", "to", "the", "method", "is", "self", "." ]
062ba5b788aeb15e68c85a329374a50b4618544d
https://github.com/jhorman/pledge/blob/062ba5b788aeb15e68c85a329374a50b4618544d/pledge/__init__.py#L231-L234
242,796
jhorman/pledge
pledge/__init__.py
list_of
def list_of(cls): """ Returns a function that checks that each element in a list is of a specific type. """ return lambda l: isinstance(l, list) and all(isinstance(x, cls) for x in l)
python
def list_of(cls): """ Returns a function that checks that each element in a list is of a specific type. """ return lambda l: isinstance(l, list) and all(isinstance(x, cls) for x in l)
[ "def", "list_of", "(", "cls", ")", ":", "return", "lambda", "l", ":", "isinstance", "(", "l", ",", "list", ")", "and", "all", "(", "isinstance", "(", "x", ",", "cls", ")", "for", "x", "in", "l", ")" ]
Returns a function that checks that each element in a list is of a specific type.
[ "Returns", "a", "function", "that", "checks", "that", "each", "element", "in", "a", "list", "is", "of", "a", "specific", "type", "." ]
062ba5b788aeb15e68c85a329374a50b4618544d
https://github.com/jhorman/pledge/blob/062ba5b788aeb15e68c85a329374a50b4618544d/pledge/__init__.py#L243-L248
242,797
jhorman/pledge
pledge/__init__.py
set_of
def set_of(cls): """ Returns a function that checks that each element in a set is of a specific type. """ return lambda l: isinstance(l, set) and all(isinstance(x, cls) for x in l)
python
def set_of(cls): """ Returns a function that checks that each element in a set is of a specific type. """ return lambda l: isinstance(l, set) and all(isinstance(x, cls) for x in l)
[ "def", "set_of", "(", "cls", ")", ":", "return", "lambda", "l", ":", "isinstance", "(", "l", ",", "set", ")", "and", "all", "(", "isinstance", "(", "x", ",", "cls", ")", "for", "x", "in", "l", ")" ]
Returns a function that checks that each element in a set is of a specific type.
[ "Returns", "a", "function", "that", "checks", "that", "each", "element", "in", "a", "set", "is", "of", "a", "specific", "type", "." ]
062ba5b788aeb15e68c85a329374a50b4618544d
https://github.com/jhorman/pledge/blob/062ba5b788aeb15e68c85a329374a50b4618544d/pledge/__init__.py#L250-L255
242,798
jalanb/pysyte
pysyte/streams.py
swallow_stdout
def swallow_stdout(stream=None): """Divert stdout into the given stream >>> string = StringIO() >>> with swallow_stdout(string): ... print('hello') >>> assert string.getvalue().rstrip() == 'hello' """ saved = sys.stdout if stream is None: stream = StringIO() sys.stdout = stream try: yield finally: sys.stdout = saved
python
def swallow_stdout(stream=None): """Divert stdout into the given stream >>> string = StringIO() >>> with swallow_stdout(string): ... print('hello') >>> assert string.getvalue().rstrip() == 'hello' """ saved = sys.stdout if stream is None: stream = StringIO() sys.stdout = stream try: yield finally: sys.stdout = saved
[ "def", "swallow_stdout", "(", "stream", "=", "None", ")", ":", "saved", "=", "sys", ".", "stdout", "if", "stream", "is", "None", ":", "stream", "=", "StringIO", "(", ")", "sys", ".", "stdout", "=", "stream", "try", ":", "yield", "finally", ":", "sys", ".", "stdout", "=", "saved" ]
Divert stdout into the given stream >>> string = StringIO() >>> with swallow_stdout(string): ... print('hello') >>> assert string.getvalue().rstrip() == 'hello'
[ "Divert", "stdout", "into", "the", "given", "stream" ]
4e278101943d1ceb1a6bcaf6ddc72052ecf13114
https://github.com/jalanb/pysyte/blob/4e278101943d1ceb1a6bcaf6ddc72052ecf13114/pysyte/streams.py#L11-L26
242,799
cdeboever3/cdpybio
cdpybio/star.py
read_sj_out_tab
def read_sj_out_tab(filename): """Read an SJ.out.tab file as produced by the RNA-STAR aligner into a pandas Dataframe. Parameters ---------- filename : str of filename or file handle Filename of the SJ.out.tab file you want to read in Returns ------- sj : pandas.DataFrame Dataframe of splice junctions """ def int_to_intron_motif(n): if n == 0: return 'non-canonical' if n == 1: return 'GT/AG' if n == 2: return 'CT/AC' if n == 3: return 'GC/AG' if n == 4: return 'CT/GC' if n == 5: return 'AT/AC' if n == 6: return 'GT/AT' sj = pd.read_table(filename, header=None, names=COLUMN_NAMES, low_memory=False) sj.intron_motif = sj.intron_motif.map(int_to_intron_motif) sj.annotated = sj.annotated.map(bool) sj.strand.astype('object') sj.strand = sj.strand.apply(lambda x: ['unk','+','-'][x]) # See https://groups.google.com/d/msg/rna-star/B0Y4oH8ZSOY/NO4OJbbUU4cJ for # definition of strand in SJout files. sj = sj.sort_values(by=['chrom', 'start', 'end']) return sj
python
def read_sj_out_tab(filename): """Read an SJ.out.tab file as produced by the RNA-STAR aligner into a pandas Dataframe. Parameters ---------- filename : str of filename or file handle Filename of the SJ.out.tab file you want to read in Returns ------- sj : pandas.DataFrame Dataframe of splice junctions """ def int_to_intron_motif(n): if n == 0: return 'non-canonical' if n == 1: return 'GT/AG' if n == 2: return 'CT/AC' if n == 3: return 'GC/AG' if n == 4: return 'CT/GC' if n == 5: return 'AT/AC' if n == 6: return 'GT/AT' sj = pd.read_table(filename, header=None, names=COLUMN_NAMES, low_memory=False) sj.intron_motif = sj.intron_motif.map(int_to_intron_motif) sj.annotated = sj.annotated.map(bool) sj.strand.astype('object') sj.strand = sj.strand.apply(lambda x: ['unk','+','-'][x]) # See https://groups.google.com/d/msg/rna-star/B0Y4oH8ZSOY/NO4OJbbUU4cJ for # definition of strand in SJout files. sj = sj.sort_values(by=['chrom', 'start', 'end']) return sj
[ "def", "read_sj_out_tab", "(", "filename", ")", ":", "def", "int_to_intron_motif", "(", "n", ")", ":", "if", "n", "==", "0", ":", "return", "'non-canonical'", "if", "n", "==", "1", ":", "return", "'GT/AG'", "if", "n", "==", "2", ":", "return", "'CT/AC'", "if", "n", "==", "3", ":", "return", "'GC/AG'", "if", "n", "==", "4", ":", "return", "'CT/GC'", "if", "n", "==", "5", ":", "return", "'AT/AC'", "if", "n", "==", "6", ":", "return", "'GT/AT'", "sj", "=", "pd", ".", "read_table", "(", "filename", ",", "header", "=", "None", ",", "names", "=", "COLUMN_NAMES", ",", "low_memory", "=", "False", ")", "sj", ".", "intron_motif", "=", "sj", ".", "intron_motif", ".", "map", "(", "int_to_intron_motif", ")", "sj", ".", "annotated", "=", "sj", ".", "annotated", ".", "map", "(", "bool", ")", "sj", ".", "strand", ".", "astype", "(", "'object'", ")", "sj", ".", "strand", "=", "sj", ".", "strand", ".", "apply", "(", "lambda", "x", ":", "[", "'unk'", ",", "'+'", ",", "'-'", "]", "[", "x", "]", ")", "# See https://groups.google.com/d/msg/rna-star/B0Y4oH8ZSOY/NO4OJbbUU4cJ for", "# definition of strand in SJout files.", "sj", "=", "sj", ".", "sort_values", "(", "by", "=", "[", "'chrom'", ",", "'start'", ",", "'end'", "]", ")", "return", "sj" ]
Read an SJ.out.tab file as produced by the RNA-STAR aligner into a pandas Dataframe. Parameters ---------- filename : str of filename or file handle Filename of the SJ.out.tab file you want to read in Returns ------- sj : pandas.DataFrame Dataframe of splice junctions
[ "Read", "an", "SJ", ".", "out", ".", "tab", "file", "as", "produced", "by", "the", "RNA", "-", "STAR", "aligner", "into", "a", "pandas", "Dataframe", "." ]
38efdf0e11d01bc00a135921cb91a19c03db5d5c
https://github.com/cdeboever3/cdpybio/blob/38efdf0e11d01bc00a135921cb91a19c03db5d5c/cdpybio/star.py#L47-L87