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
238,700
mikicz/arca
arca/utils.py
get_hash_for_file
def get_hash_for_file(repo: Repo, path: Union[str, Path]) -> str: """ Returns the hash for the specified path. Equivalent to ``git rev-parse HEAD:X`` :param repo: The repo to check in :param path: The path to a file or folder to get hash for :return: The hash """ return repo.git.rev_parse(f"HEAD:{str(path)}")
python
def get_hash_for_file(repo: Repo, path: Union[str, Path]) -> str: """ Returns the hash for the specified path. Equivalent to ``git rev-parse HEAD:X`` :param repo: The repo to check in :param path: The path to a file or folder to get hash for :return: The hash """ return repo.git.rev_parse(f"HEAD:{str(path)}")
[ "def", "get_hash_for_file", "(", "repo", ":", "Repo", ",", "path", ":", "Union", "[", "str", ",", "Path", "]", ")", "->", "str", ":", "return", "repo", ".", "git", ".", "rev_parse", "(", "f\"HEAD:{str(path)}\"", ")" ]
Returns the hash for the specified path. Equivalent to ``git rev-parse HEAD:X`` :param repo: The repo to check in :param path: The path to a file or folder to get hash for :return: The hash
[ "Returns", "the", "hash", "for", "the", "specified", "path", "." ]
e67fdc00be473ecf8ec16d024e1a3f2c47ca882c
https://github.com/mikicz/arca/blob/e67fdc00be473ecf8ec16d024e1a3f2c47ca882c/arca/utils.py#L158-L167
238,701
mikicz/arca
arca/utils.py
Settings.get
def get(self, *keys: str, default: Any = NOT_SET) -> Any: """ Returns values from the settings in the order of keys, the first value encountered is used. Example: >>> settings = Settings({"ARCA_ONE": 1, "ARCA_TWO": 2}) >>> settings.get("one") 1 >>> settings.get("one", "two") 1 >>> settings.get("two", "one") 2 >>> settings.get("three", "one") 1 >>> settings.get("three", default=3) 3 >>> settings.get("three") Traceback (most recent call last): ... KeyError: :param keys: One or more keys to get from settings. If multiple keys are provided, the value of the first key that has a value is returned. :param default: If none of the ``options`` aren't set, return this value. :return: A value from the settings or the default. :raise ValueError: If no keys are provided. :raise KeyError: If none of the keys are set and no default is provided. """ if not len(keys): raise ValueError("At least one key must be provided.") for option in keys: key = f"{self.PREFIX}_{option.upper()}" if key in self._data: return self._data[key] if default is NOT_SET: raise KeyError("None of the following key is present in settings and no default is set: {}".format( ", ".join(keys) )) return default
python
def get(self, *keys: str, default: Any = NOT_SET) -> Any: """ Returns values from the settings in the order of keys, the first value encountered is used. Example: >>> settings = Settings({"ARCA_ONE": 1, "ARCA_TWO": 2}) >>> settings.get("one") 1 >>> settings.get("one", "two") 1 >>> settings.get("two", "one") 2 >>> settings.get("three", "one") 1 >>> settings.get("three", default=3) 3 >>> settings.get("three") Traceback (most recent call last): ... KeyError: :param keys: One or more keys to get from settings. If multiple keys are provided, the value of the first key that has a value is returned. :param default: If none of the ``options`` aren't set, return this value. :return: A value from the settings or the default. :raise ValueError: If no keys are provided. :raise KeyError: If none of the keys are set and no default is provided. """ if not len(keys): raise ValueError("At least one key must be provided.") for option in keys: key = f"{self.PREFIX}_{option.upper()}" if key in self._data: return self._data[key] if default is NOT_SET: raise KeyError("None of the following key is present in settings and no default is set: {}".format( ", ".join(keys) )) return default
[ "def", "get", "(", "self", ",", "*", "keys", ":", "str", ",", "default", ":", "Any", "=", "NOT_SET", ")", "->", "Any", ":", "if", "not", "len", "(", "keys", ")", ":", "raise", "ValueError", "(", "\"At least one key must be provided.\"", ")", "for", "option", "in", "keys", ":", "key", "=", "f\"{self.PREFIX}_{option.upper()}\"", "if", "key", "in", "self", ".", "_data", ":", "return", "self", ".", "_data", "[", "key", "]", "if", "default", "is", "NOT_SET", ":", "raise", "KeyError", "(", "\"None of the following key is present in settings and no default is set: {}\"", ".", "format", "(", "\", \"", ".", "join", "(", "keys", ")", ")", ")", "return", "default" ]
Returns values from the settings in the order of keys, the first value encountered is used. Example: >>> settings = Settings({"ARCA_ONE": 1, "ARCA_TWO": 2}) >>> settings.get("one") 1 >>> settings.get("one", "two") 1 >>> settings.get("two", "one") 2 >>> settings.get("three", "one") 1 >>> settings.get("three", default=3) 3 >>> settings.get("three") Traceback (most recent call last): ... KeyError: :param keys: One or more keys to get from settings. If multiple keys are provided, the value of the first key that has a value is returned. :param default: If none of the ``options`` aren't set, return this value. :return: A value from the settings or the default. :raise ValueError: If no keys are provided. :raise KeyError: If none of the keys are set and no default is provided.
[ "Returns", "values", "from", "the", "settings", "in", "the", "order", "of", "keys", "the", "first", "value", "encountered", "is", "used", "." ]
e67fdc00be473ecf8ec16d024e1a3f2c47ca882c
https://github.com/mikicz/arca/blob/e67fdc00be473ecf8ec16d024e1a3f2c47ca882c/arca/utils.py#L96-L139
238,702
grow/webreview-client
webreview/webreview.py
batch
def batch(items, size): """Batches a list into a list of lists, with sub-lists sized by a specified batch size.""" return [items[x:x + size] for x in xrange(0, len(items), size)]
python
def batch(items, size): """Batches a list into a list of lists, with sub-lists sized by a specified batch size.""" return [items[x:x + size] for x in xrange(0, len(items), size)]
[ "def", "batch", "(", "items", ",", "size", ")", ":", "return", "[", "items", "[", "x", ":", "x", "+", "size", "]", "for", "x", "in", "xrange", "(", "0", ",", "len", "(", "items", ")", ",", "size", ")", "]" ]
Batches a list into a list of lists, with sub-lists sized by a specified batch size.
[ "Batches", "a", "list", "into", "a", "list", "of", "lists", "with", "sub", "-", "lists", "sized", "by", "a", "specified", "batch", "size", "." ]
0f0ef732384b57e2001e735bca5f210a1d5ce6ed
https://github.com/grow/webreview-client/blob/0f0ef732384b57e2001e735bca5f210a1d5ce6ed/webreview/webreview.py#L74-L77
238,703
grow/webreview-client
webreview/webreview.py
get_storage
def get_storage(key, username): """Returns the Storage class compatible with the current environment.""" if IS_APPENGINE and appengine: return appengine.StorageByKeyName( appengine.CredentialsModel, username, 'credentials') file_name = os.path.expanduser('~/.config/webreview/{}_{}'.format(key, username)) dir_name = os.path.dirname(file_name) if not os.path.exists(dir_name): os.makedirs(dir_name) return oauth_file.Storage(file_name)
python
def get_storage(key, username): """Returns the Storage class compatible with the current environment.""" if IS_APPENGINE and appengine: return appengine.StorageByKeyName( appengine.CredentialsModel, username, 'credentials') file_name = os.path.expanduser('~/.config/webreview/{}_{}'.format(key, username)) dir_name = os.path.dirname(file_name) if not os.path.exists(dir_name): os.makedirs(dir_name) return oauth_file.Storage(file_name)
[ "def", "get_storage", "(", "key", ",", "username", ")", ":", "if", "IS_APPENGINE", "and", "appengine", ":", "return", "appengine", ".", "StorageByKeyName", "(", "appengine", ".", "CredentialsModel", ",", "username", ",", "'credentials'", ")", "file_name", "=", "os", ".", "path", ".", "expanduser", "(", "'~/.config/webreview/{}_{}'", ".", "format", "(", "key", ",", "username", ")", ")", "dir_name", "=", "os", ".", "path", ".", "dirname", "(", "file_name", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "dir_name", ")", ":", "os", ".", "makedirs", "(", "dir_name", ")", "return", "oauth_file", ".", "Storage", "(", "file_name", ")" ]
Returns the Storage class compatible with the current environment.
[ "Returns", "the", "Storage", "class", "compatible", "with", "the", "current", "environment", "." ]
0f0ef732384b57e2001e735bca5f210a1d5ce6ed
https://github.com/grow/webreview-client/blob/0f0ef732384b57e2001e735bca5f210a1d5ce6ed/webreview/webreview.py#L80-L89
238,704
gevious/flask_slither
flask_slither/db.py
MongoDbQuery._clean_record
def _clean_record(self, record): """Remove all fields with `None` values""" for k, v in dict(record).items(): if isinstance(v, dict): v = self._clean_record(v) if v is None: record.pop(k) return record
python
def _clean_record(self, record): """Remove all fields with `None` values""" for k, v in dict(record).items(): if isinstance(v, dict): v = self._clean_record(v) if v is None: record.pop(k) return record
[ "def", "_clean_record", "(", "self", ",", "record", ")", ":", "for", "k", ",", "v", "in", "dict", "(", "record", ")", ".", "items", "(", ")", ":", "if", "isinstance", "(", "v", ",", "dict", ")", ":", "v", "=", "self", ".", "_clean_record", "(", "v", ")", "if", "v", "is", "None", ":", "record", ".", "pop", "(", "k", ")", "return", "record" ]
Remove all fields with `None` values
[ "Remove", "all", "fields", "with", "None", "values" ]
bf1fd1e58224c19883f4b19c5f727f47ee9857da
https://github.com/gevious/flask_slither/blob/bf1fd1e58224c19883f4b19c5f727f47ee9857da/flask_slither/db.py#L43-L50
238,705
gevious/flask_slither
flask_slither/db.py
MongoDbQuery.serialize
def serialize(self, root, records): """Serialize the payload into JSON""" logging.info("Serializing record") logging.debug("Root: {}".format(root)) logging.debug("Records: {}".format(records)) if records == {}: return '{}' if isinstance(records, dict): if list(records.keys())[0] == 'errors': logging.warning("Found errors. Moving on".format(records)) root = None elif '_id' in records: records['id'] = records.pop('_id') else: records = list(records) # rename _id to id for r in records: if '_id' in r: r['id'] = r.pop('_id') if root is not None: records = {root: records} return json.dumps(records, cls=JSONEncoder)
python
def serialize(self, root, records): """Serialize the payload into JSON""" logging.info("Serializing record") logging.debug("Root: {}".format(root)) logging.debug("Records: {}".format(records)) if records == {}: return '{}' if isinstance(records, dict): if list(records.keys())[0] == 'errors': logging.warning("Found errors. Moving on".format(records)) root = None elif '_id' in records: records['id'] = records.pop('_id') else: records = list(records) # rename _id to id for r in records: if '_id' in r: r['id'] = r.pop('_id') if root is not None: records = {root: records} return json.dumps(records, cls=JSONEncoder)
[ "def", "serialize", "(", "self", ",", "root", ",", "records", ")", ":", "logging", ".", "info", "(", "\"Serializing record\"", ")", "logging", ".", "debug", "(", "\"Root: {}\"", ".", "format", "(", "root", ")", ")", "logging", ".", "debug", "(", "\"Records: {}\"", ".", "format", "(", "records", ")", ")", "if", "records", "==", "{", "}", ":", "return", "'{}'", "if", "isinstance", "(", "records", ",", "dict", ")", ":", "if", "list", "(", "records", ".", "keys", "(", ")", ")", "[", "0", "]", "==", "'errors'", ":", "logging", ".", "warning", "(", "\"Found errors. Moving on\"", ".", "format", "(", "records", ")", ")", "root", "=", "None", "elif", "'_id'", "in", "records", ":", "records", "[", "'id'", "]", "=", "records", ".", "pop", "(", "'_id'", ")", "else", ":", "records", "=", "list", "(", "records", ")", "# rename _id to id", "for", "r", "in", "records", ":", "if", "'_id'", "in", "r", ":", "r", "[", "'id'", "]", "=", "r", ".", "pop", "(", "'_id'", ")", "if", "root", "is", "not", "None", ":", "records", "=", "{", "root", ":", "records", "}", "return", "json", ".", "dumps", "(", "records", ",", "cls", "=", "JSONEncoder", ")" ]
Serialize the payload into JSON
[ "Serialize", "the", "payload", "into", "JSON" ]
bf1fd1e58224c19883f4b19c5f727f47ee9857da
https://github.com/gevious/flask_slither/blob/bf1fd1e58224c19883f4b19c5f727f47ee9857da/flask_slither/db.py#L116-L139
238,706
klmitch/policies
policies/policy.py
rule
def rule(ctxt, name): """ Allows evaluation of another rule while evaluating a rule. :param ctxt: The evaluation context for the rule. :param name: The name of the rule to evaluate. """ # If the result of evaluation is in the rule cache, bypass # evaluation if name in ctxt.rule_cache: ctxt.stack.append(ctxt.rule_cache[name]) return # Obtain the rule we're to evaluate try: rule = ctxt.policy[name] except KeyError: # Rule doesn't exist; log a message and assume False log = logging.getLogger('policies') log.warn("Request to evaluate non-existant rule %r " "while evaluating rule %r" % (name, ctxt.name)) ctxt.stack.append(False) ctxt.rule_cache[name] = False return # Evaluate the rule, stopping at the set_authz instruction with ctxt.push_rule(name): rule.instructions(ctxt, True) # Cache the result ctxt.rule_cache[name] = ctxt.stack[-1]
python
def rule(ctxt, name): """ Allows evaluation of another rule while evaluating a rule. :param ctxt: The evaluation context for the rule. :param name: The name of the rule to evaluate. """ # If the result of evaluation is in the rule cache, bypass # evaluation if name in ctxt.rule_cache: ctxt.stack.append(ctxt.rule_cache[name]) return # Obtain the rule we're to evaluate try: rule = ctxt.policy[name] except KeyError: # Rule doesn't exist; log a message and assume False log = logging.getLogger('policies') log.warn("Request to evaluate non-existant rule %r " "while evaluating rule %r" % (name, ctxt.name)) ctxt.stack.append(False) ctxt.rule_cache[name] = False return # Evaluate the rule, stopping at the set_authz instruction with ctxt.push_rule(name): rule.instructions(ctxt, True) # Cache the result ctxt.rule_cache[name] = ctxt.stack[-1]
[ "def", "rule", "(", "ctxt", ",", "name", ")", ":", "# If the result of evaluation is in the rule cache, bypass", "# evaluation", "if", "name", "in", "ctxt", ".", "rule_cache", ":", "ctxt", ".", "stack", ".", "append", "(", "ctxt", ".", "rule_cache", "[", "name", "]", ")", "return", "# Obtain the rule we're to evaluate", "try", ":", "rule", "=", "ctxt", ".", "policy", "[", "name", "]", "except", "KeyError", ":", "# Rule doesn't exist; log a message and assume False", "log", "=", "logging", ".", "getLogger", "(", "'policies'", ")", "log", ".", "warn", "(", "\"Request to evaluate non-existant rule %r \"", "\"while evaluating rule %r\"", "%", "(", "name", ",", "ctxt", ".", "name", ")", ")", "ctxt", ".", "stack", ".", "append", "(", "False", ")", "ctxt", ".", "rule_cache", "[", "name", "]", "=", "False", "return", "# Evaluate the rule, stopping at the set_authz instruction", "with", "ctxt", ".", "push_rule", "(", "name", ")", ":", "rule", ".", "instructions", "(", "ctxt", ",", "True", ")", "# Cache the result", "ctxt", ".", "rule_cache", "[", "name", "]", "=", "ctxt", ".", "stack", "[", "-", "1", "]" ]
Allows evaluation of another rule while evaluating a rule. :param ctxt: The evaluation context for the rule. :param name: The name of the rule to evaluate.
[ "Allows", "evaluation", "of", "another", "rule", "while", "evaluating", "a", "rule", "." ]
edf26c5707a5a0cc8e9f59a209a64dee7f79b7a4
https://github.com/klmitch/policies/blob/edf26c5707a5a0cc8e9f59a209a64dee7f79b7a4/policies/policy.py#L563-L594
238,707
klmitch/policies
policies/policy.py
PolicyContext.resolve
def resolve(self, symbol): """ Resolve a symbol encountered during a rule evaluation into the actual value for that symbol. :param symbol: The symbol being resolved. :returns: The value of that symbol. If the symbol was not declared in the ``variables`` parameter of the constructor, a call will be made to the ``Policy``'s ``resolve()`` method. """ # Try the variables first if symbol in self.variables: return self.variables[symbol] return self.policy.resolve(symbol)
python
def resolve(self, symbol): """ Resolve a symbol encountered during a rule evaluation into the actual value for that symbol. :param symbol: The symbol being resolved. :returns: The value of that symbol. If the symbol was not declared in the ``variables`` parameter of the constructor, a call will be made to the ``Policy``'s ``resolve()`` method. """ # Try the variables first if symbol in self.variables: return self.variables[symbol] return self.policy.resolve(symbol)
[ "def", "resolve", "(", "self", ",", "symbol", ")", ":", "# Try the variables first", "if", "symbol", "in", "self", ".", "variables", ":", "return", "self", ".", "variables", "[", "symbol", "]", "return", "self", ".", "policy", ".", "resolve", "(", "symbol", ")" ]
Resolve a symbol encountered during a rule evaluation into the actual value for that symbol. :param symbol: The symbol being resolved. :returns: The value of that symbol. If the symbol was not declared in the ``variables`` parameter of the constructor, a call will be made to the ``Policy``'s ``resolve()`` method.
[ "Resolve", "a", "symbol", "encountered", "during", "a", "rule", "evaluation", "into", "the", "actual", "value", "for", "that", "symbol", "." ]
edf26c5707a5a0cc8e9f59a209a64dee7f79b7a4
https://github.com/klmitch/policies/blob/edf26c5707a5a0cc8e9f59a209a64dee7f79b7a4/policies/policy.py#L82-L99
238,708
klmitch/policies
policies/policy.py
PolicyContext.push_rule
def push_rule(self, name): """ Allow one rule to be evaluated in the context of another. This allows keeping track of the rule names during nested rule evaluation. :param name: The name of the nested rule to be evaluated. :returns: A context manager, suitable for use with the ``with`` statement. No value is generated. """ # Verify that we haven't been evaluating the rule already; # this is to prohibit recursive rules from locking us up... if name in self._name: raise PolicyException( "Rule recursion detected; invocation chain: %s -> %s" % (' -> '.join(self._name), name)) # Save the name temporarily, and set up the program counter # and step self._name.append(name) self._pc.append(0) self._step.append(1) try: yield except Exception as exc: exc_info = sys.exc_info() # Report only if we haven't reported it yet if not self.reported: # Get the logger and emit a log message log = logging.getLogger('policies') log.warn("Exception raised while evaluating rule %r: %s" % (name, exc)) self.reported = True six.reraise(*exc_info) finally: # Pop the name off the stack of names and restore program # counter and step self._name.pop() self._pc.pop() self._step.pop()
python
def push_rule(self, name): """ Allow one rule to be evaluated in the context of another. This allows keeping track of the rule names during nested rule evaluation. :param name: The name of the nested rule to be evaluated. :returns: A context manager, suitable for use with the ``with`` statement. No value is generated. """ # Verify that we haven't been evaluating the rule already; # this is to prohibit recursive rules from locking us up... if name in self._name: raise PolicyException( "Rule recursion detected; invocation chain: %s -> %s" % (' -> '.join(self._name), name)) # Save the name temporarily, and set up the program counter # and step self._name.append(name) self._pc.append(0) self._step.append(1) try: yield except Exception as exc: exc_info = sys.exc_info() # Report only if we haven't reported it yet if not self.reported: # Get the logger and emit a log message log = logging.getLogger('policies') log.warn("Exception raised while evaluating rule %r: %s" % (name, exc)) self.reported = True six.reraise(*exc_info) finally: # Pop the name off the stack of names and restore program # counter and step self._name.pop() self._pc.pop() self._step.pop()
[ "def", "push_rule", "(", "self", ",", "name", ")", ":", "# Verify that we haven't been evaluating the rule already;", "# this is to prohibit recursive rules from locking us up...", "if", "name", "in", "self", ".", "_name", ":", "raise", "PolicyException", "(", "\"Rule recursion detected; invocation chain: %s -> %s\"", "%", "(", "' -> '", ".", "join", "(", "self", ".", "_name", ")", ",", "name", ")", ")", "# Save the name temporarily, and set up the program counter", "# and step", "self", ".", "_name", ".", "append", "(", "name", ")", "self", ".", "_pc", ".", "append", "(", "0", ")", "self", ".", "_step", ".", "append", "(", "1", ")", "try", ":", "yield", "except", "Exception", "as", "exc", ":", "exc_info", "=", "sys", ".", "exc_info", "(", ")", "# Report only if we haven't reported it yet", "if", "not", "self", ".", "reported", ":", "# Get the logger and emit a log message", "log", "=", "logging", ".", "getLogger", "(", "'policies'", ")", "log", ".", "warn", "(", "\"Exception raised while evaluating rule %r: %s\"", "%", "(", "name", ",", "exc", ")", ")", "self", ".", "reported", "=", "True", "six", ".", "reraise", "(", "*", "exc_info", ")", "finally", ":", "# Pop the name off the stack of names and restore program", "# counter and step", "self", ".", "_name", ".", "pop", "(", ")", "self", ".", "_pc", ".", "pop", "(", ")", "self", ".", "_step", ".", "pop", "(", ")" ]
Allow one rule to be evaluated in the context of another. This allows keeping track of the rule names during nested rule evaluation. :param name: The name of the nested rule to be evaluated. :returns: A context manager, suitable for use with the ``with`` statement. No value is generated.
[ "Allow", "one", "rule", "to", "be", "evaluated", "in", "the", "context", "of", "another", ".", "This", "allows", "keeping", "track", "of", "the", "rule", "names", "during", "nested", "rule", "evaluation", "." ]
edf26c5707a5a0cc8e9f59a209a64dee7f79b7a4
https://github.com/klmitch/policies/blob/edf26c5707a5a0cc8e9f59a209a64dee7f79b7a4/policies/policy.py#L102-L145
238,709
klmitch/policies
policies/policy.py
Policy.declare
def declare(self, name, text='', doc=None, attrs=None, attr_docs=None): """ Declare a rule. This allows a default for a given rule to be set, along with default values for the authorization attributes. This function can also include documentation for the rule and the authorization attributes, allowing a sample policy configuration file to be generated. :param name: The name of the rule. :param text: The text of the rule. Defaults to the empty string. :param doc: A string documenting the purpose of the rule. :param attrs: A dictionary of default values for the authorization attributes. Note that authorization attributes cannot have names beginning with an underscore ("_"). :param attr_docs: A dictionary of strings for documenting the purpose of the authorization attributes. """ self._defaults[name] = rules.Rule(name, text, attrs) self._docs[name] = rules.RuleDoc(name, doc, attr_docs) return self._defaults[name]
python
def declare(self, name, text='', doc=None, attrs=None, attr_docs=None): """ Declare a rule. This allows a default for a given rule to be set, along with default values for the authorization attributes. This function can also include documentation for the rule and the authorization attributes, allowing a sample policy configuration file to be generated. :param name: The name of the rule. :param text: The text of the rule. Defaults to the empty string. :param doc: A string documenting the purpose of the rule. :param attrs: A dictionary of default values for the authorization attributes. Note that authorization attributes cannot have names beginning with an underscore ("_"). :param attr_docs: A dictionary of strings for documenting the purpose of the authorization attributes. """ self._defaults[name] = rules.Rule(name, text, attrs) self._docs[name] = rules.RuleDoc(name, doc, attr_docs) return self._defaults[name]
[ "def", "declare", "(", "self", ",", "name", ",", "text", "=", "''", ",", "doc", "=", "None", ",", "attrs", "=", "None", ",", "attr_docs", "=", "None", ")", ":", "self", ".", "_defaults", "[", "name", "]", "=", "rules", ".", "Rule", "(", "name", ",", "text", ",", "attrs", ")", "self", ".", "_docs", "[", "name", "]", "=", "rules", ".", "RuleDoc", "(", "name", ",", "doc", ",", "attr_docs", ")", "return", "self", ".", "_defaults", "[", "name", "]" ]
Declare a rule. This allows a default for a given rule to be set, along with default values for the authorization attributes. This function can also include documentation for the rule and the authorization attributes, allowing a sample policy configuration file to be generated. :param name: The name of the rule. :param text: The text of the rule. Defaults to the empty string. :param doc: A string documenting the purpose of the rule. :param attrs: A dictionary of default values for the authorization attributes. Note that authorization attributes cannot have names beginning with an underscore ("_"). :param attr_docs: A dictionary of strings for documenting the purpose of the authorization attributes.
[ "Declare", "a", "rule", ".", "This", "allows", "a", "default", "for", "a", "given", "rule", "to", "be", "set", "along", "with", "default", "values", "for", "the", "authorization", "attributes", ".", "This", "function", "can", "also", "include", "documentation", "for", "the", "rule", "and", "the", "authorization", "attributes", "allowing", "a", "sample", "policy", "configuration", "file", "to", "be", "generated", "." ]
edf26c5707a5a0cc8e9f59a209a64dee7f79b7a4
https://github.com/klmitch/policies/blob/edf26c5707a5a0cc8e9f59a209a64dee7f79b7a4/policies/policy.py#L365-L388
238,710
klmitch/policies
policies/policy.py
Policy.get_doc
def get_doc(self, name): """ Retrieve a ``RuleDoc`` object from the ``Policy`` with the given name. The ``RuleDoc`` object contains all documentation for the named rule. :param name: The name of the rule to retrieve the documentation for. :returns: A ``RuleDoc`` object containing the documentation for the rule. """ # Create one if there isn't one already if name not in self._docs: self._docs[name] = rules.RuleDoc(name) return self._docs[name]
python
def get_doc(self, name): """ Retrieve a ``RuleDoc`` object from the ``Policy`` with the given name. The ``RuleDoc`` object contains all documentation for the named rule. :param name: The name of the rule to retrieve the documentation for. :returns: A ``RuleDoc`` object containing the documentation for the rule. """ # Create one if there isn't one already if name not in self._docs: self._docs[name] = rules.RuleDoc(name) return self._docs[name]
[ "def", "get_doc", "(", "self", ",", "name", ")", ":", "# Create one if there isn't one already", "if", "name", "not", "in", "self", ".", "_docs", ":", "self", ".", "_docs", "[", "name", "]", "=", "rules", ".", "RuleDoc", "(", "name", ")", "return", "self", ".", "_docs", "[", "name", "]" ]
Retrieve a ``RuleDoc`` object from the ``Policy`` with the given name. The ``RuleDoc`` object contains all documentation for the named rule. :param name: The name of the rule to retrieve the documentation for. :returns: A ``RuleDoc`` object containing the documentation for the rule.
[ "Retrieve", "a", "RuleDoc", "object", "from", "the", "Policy", "with", "the", "given", "name", ".", "The", "RuleDoc", "object", "contains", "all", "documentation", "for", "the", "named", "rule", "." ]
edf26c5707a5a0cc8e9f59a209a64dee7f79b7a4
https://github.com/klmitch/policies/blob/edf26c5707a5a0cc8e9f59a209a64dee7f79b7a4/policies/policy.py#L409-L426
238,711
klmitch/policies
policies/policy.py
Policy.resolve
def resolve(self, symbol): """ Resolve a symbol using the entrypoint group. :param symbol: The symbol being resolved. :returns: The value of that symbol. If the symbol cannot be found, or if no entrypoint group was passed to the constructor, will return ``None``. """ # Search for a corresponding symbol if symbol not in self._resolve_cache: result = None # Search through entrypoints only if we have a group if self._group is not None: for ep in pkg_resources.iter_entry_points(self._group, symbol): try: result = ep.load() except (ImportError, AttributeError, pkg_resources.UnknownExtra): continue # We found the result we were looking for break # Cache the result self._resolve_cache[symbol] = result return self._resolve_cache[symbol]
python
def resolve(self, symbol): """ Resolve a symbol using the entrypoint group. :param symbol: The symbol being resolved. :returns: The value of that symbol. If the symbol cannot be found, or if no entrypoint group was passed to the constructor, will return ``None``. """ # Search for a corresponding symbol if symbol not in self._resolve_cache: result = None # Search through entrypoints only if we have a group if self._group is not None: for ep in pkg_resources.iter_entry_points(self._group, symbol): try: result = ep.load() except (ImportError, AttributeError, pkg_resources.UnknownExtra): continue # We found the result we were looking for break # Cache the result self._resolve_cache[symbol] = result return self._resolve_cache[symbol]
[ "def", "resolve", "(", "self", ",", "symbol", ")", ":", "# Search for a corresponding symbol", "if", "symbol", "not", "in", "self", ".", "_resolve_cache", ":", "result", "=", "None", "# Search through entrypoints only if we have a group", "if", "self", ".", "_group", "is", "not", "None", ":", "for", "ep", "in", "pkg_resources", ".", "iter_entry_points", "(", "self", ".", "_group", ",", "symbol", ")", ":", "try", ":", "result", "=", "ep", ".", "load", "(", ")", "except", "(", "ImportError", ",", "AttributeError", ",", "pkg_resources", ".", "UnknownExtra", ")", ":", "continue", "# We found the result we were looking for", "break", "# Cache the result", "self", ".", "_resolve_cache", "[", "symbol", "]", "=", "result", "return", "self", ".", "_resolve_cache", "[", "symbol", "]" ]
Resolve a symbol using the entrypoint group. :param symbol: The symbol being resolved. :returns: The value of that symbol. If the symbol cannot be found, or if no entrypoint group was passed to the constructor, will return ``None``.
[ "Resolve", "a", "symbol", "using", "the", "entrypoint", "group", "." ]
edf26c5707a5a0cc8e9f59a209a64dee7f79b7a4
https://github.com/klmitch/policies/blob/edf26c5707a5a0cc8e9f59a209a64dee7f79b7a4/policies/policy.py#L467-L497
238,712
klmitch/policies
policies/policy.py
Policy.evaluate
def evaluate(self, name, variables=None): """ Evaluate a named rule. :param name: The name of the rule to evaluate. :param variables: An optional dictionary of variables to make available during evaluation of the rule. :returns: An instance of ``policies.authorization.Authorization`` with the result of the rule evaluation. This will include any authorization attributes. """ # Get the rule and predeclaration rule = self._rules.get(name) default = self._defaults.get(name) # Short-circuit if we don't have either if rule is None and default is None: return authorization.Authorization(False) # Marry the attribute defaults attrs = {} if default: attrs.update(default.attrs) if rule: attrs.update(rule.attrs) # Select the rule we'll actually use if rule is None: rule = default # Construct the context ctxt = self.context_class(self, attrs, variables or {}) # Execute the rule try: with ctxt.push_rule(name): rule.instructions(ctxt) except Exception as exc: # Fail closed return authorization.Authorization(False, attrs) # Return the authorization result return ctxt.authz
python
def evaluate(self, name, variables=None): """ Evaluate a named rule. :param name: The name of the rule to evaluate. :param variables: An optional dictionary of variables to make available during evaluation of the rule. :returns: An instance of ``policies.authorization.Authorization`` with the result of the rule evaluation. This will include any authorization attributes. """ # Get the rule and predeclaration rule = self._rules.get(name) default = self._defaults.get(name) # Short-circuit if we don't have either if rule is None and default is None: return authorization.Authorization(False) # Marry the attribute defaults attrs = {} if default: attrs.update(default.attrs) if rule: attrs.update(rule.attrs) # Select the rule we'll actually use if rule is None: rule = default # Construct the context ctxt = self.context_class(self, attrs, variables or {}) # Execute the rule try: with ctxt.push_rule(name): rule.instructions(ctxt) except Exception as exc: # Fail closed return authorization.Authorization(False, attrs) # Return the authorization result return ctxt.authz
[ "def", "evaluate", "(", "self", ",", "name", ",", "variables", "=", "None", ")", ":", "# Get the rule and predeclaration", "rule", "=", "self", ".", "_rules", ".", "get", "(", "name", ")", "default", "=", "self", ".", "_defaults", ".", "get", "(", "name", ")", "# Short-circuit if we don't have either", "if", "rule", "is", "None", "and", "default", "is", "None", ":", "return", "authorization", ".", "Authorization", "(", "False", ")", "# Marry the attribute defaults", "attrs", "=", "{", "}", "if", "default", ":", "attrs", ".", "update", "(", "default", ".", "attrs", ")", "if", "rule", ":", "attrs", ".", "update", "(", "rule", ".", "attrs", ")", "# Select the rule we'll actually use", "if", "rule", "is", "None", ":", "rule", "=", "default", "# Construct the context", "ctxt", "=", "self", ".", "context_class", "(", "self", ",", "attrs", ",", "variables", "or", "{", "}", ")", "# Execute the rule", "try", ":", "with", "ctxt", ".", "push_rule", "(", "name", ")", ":", "rule", ".", "instructions", "(", "ctxt", ")", "except", "Exception", "as", "exc", ":", "# Fail closed", "return", "authorization", ".", "Authorization", "(", "False", ",", "attrs", ")", "# Return the authorization result", "return", "ctxt", ".", "authz" ]
Evaluate a named rule. :param name: The name of the rule to evaluate. :param variables: An optional dictionary of variables to make available during evaluation of the rule. :returns: An instance of ``policies.authorization.Authorization`` with the result of the rule evaluation. This will include any authorization attributes.
[ "Evaluate", "a", "named", "rule", "." ]
edf26c5707a5a0cc8e9f59a209a64dee7f79b7a4
https://github.com/klmitch/policies/blob/edf26c5707a5a0cc8e9f59a209a64dee7f79b7a4/policies/policy.py#L499-L544
238,713
wickman/compactor
compactor/pid.py
PID.from_string
def from_string(cls, pid): """Parse a PID from its string representation. PIDs may be represented as name@ip:port, e.g. .. code-block:: python pid = PID.from_string('master(1)@192.168.33.2:5051') :param pid: A string representation of a pid. :type pid: ``str`` :return: The parsed pid. :rtype: :class:`PID` :raises: ``ValueError`` should the string not be of the correct syntax. """ try: id_, ip_port = pid.split('@') ip, port = ip_port.split(':') port = int(port) except ValueError: raise ValueError('Invalid PID: %s' % pid) return cls(ip, port, id_)
python
def from_string(cls, pid): """Parse a PID from its string representation. PIDs may be represented as name@ip:port, e.g. .. code-block:: python pid = PID.from_string('master(1)@192.168.33.2:5051') :param pid: A string representation of a pid. :type pid: ``str`` :return: The parsed pid. :rtype: :class:`PID` :raises: ``ValueError`` should the string not be of the correct syntax. """ try: id_, ip_port = pid.split('@') ip, port = ip_port.split(':') port = int(port) except ValueError: raise ValueError('Invalid PID: %s' % pid) return cls(ip, port, id_)
[ "def", "from_string", "(", "cls", ",", "pid", ")", ":", "try", ":", "id_", ",", "ip_port", "=", "pid", ".", "split", "(", "'@'", ")", "ip", ",", "port", "=", "ip_port", ".", "split", "(", "':'", ")", "port", "=", "int", "(", "port", ")", "except", "ValueError", ":", "raise", "ValueError", "(", "'Invalid PID: %s'", "%", "pid", ")", "return", "cls", "(", "ip", ",", "port", ",", "id_", ")" ]
Parse a PID from its string representation. PIDs may be represented as name@ip:port, e.g. .. code-block:: python pid = PID.from_string('master(1)@192.168.33.2:5051') :param pid: A string representation of a pid. :type pid: ``str`` :return: The parsed pid. :rtype: :class:`PID` :raises: ``ValueError`` should the string not be of the correct syntax.
[ "Parse", "a", "PID", "from", "its", "string", "representation", "." ]
52714be3d84aa595a212feccb4d92ec250cede2a
https://github.com/wickman/compactor/blob/52714be3d84aa595a212feccb4d92ec250cede2a/compactor/pid.py#L5-L26
238,714
pip-services3-python/pip-services3-commons-python
pip_services3_commons/data/AnyValueArray.py
AnyValueArray.set_as_object
def set_as_object(self, index = None, value= None): """ Sets a new value to array element specified by its index. When the index is not defined, it resets the entire array value. This method has double purpose because method overrides are not supported in JavaScript. :param index: (optional) an index of the element to set :param value: a new element or array value. """ if index == None and value != None: self.set_as_array(value) else: self[index] = value
python
def set_as_object(self, index = None, value= None): """ Sets a new value to array element specified by its index. When the index is not defined, it resets the entire array value. This method has double purpose because method overrides are not supported in JavaScript. :param index: (optional) an index of the element to set :param value: a new element or array value. """ if index == None and value != None: self.set_as_array(value) else: self[index] = value
[ "def", "set_as_object", "(", "self", ",", "index", "=", "None", ",", "value", "=", "None", ")", ":", "if", "index", "==", "None", "and", "value", "!=", "None", ":", "self", ".", "set_as_array", "(", "value", ")", "else", ":", "self", "[", "index", "]", "=", "value" ]
Sets a new value to array element specified by its index. When the index is not defined, it resets the entire array value. This method has double purpose because method overrides are not supported in JavaScript. :param index: (optional) an index of the element to set :param value: a new element or array value.
[ "Sets", "a", "new", "value", "to", "array", "element", "specified", "by", "its", "index", ".", "When", "the", "index", "is", "not", "defined", "it", "resets", "the", "entire", "array", "value", ".", "This", "method", "has", "double", "purpose", "because", "method", "overrides", "are", "not", "supported", "in", "JavaScript", "." ]
22cbbb3e91e49717f65c083d36147fdb07ba9e3b
https://github.com/pip-services3-python/pip-services3-commons-python/blob/22cbbb3e91e49717f65c083d36147fdb07ba9e3b/pip_services3_commons/data/AnyValueArray.py#L67-L80
238,715
pip-services3-python/pip-services3-commons-python
pip_services3_commons/data/AnyValueArray.py
AnyValueArray.get_as_array
def get_as_array(self, index): """ Converts array element into an AnyValueArray or returns empty AnyValueArray if conversion is not possible. :param index: an index of element to get. :return: AnyValueArray value of the element or empty AnyValueArray if conversion is not supported. """ if index == None: array = [] for value in self: array.append(value) return array else: value = self[index] return AnyValueArray.from_value(value)
python
def get_as_array(self, index): """ Converts array element into an AnyValueArray or returns empty AnyValueArray if conversion is not possible. :param index: an index of element to get. :return: AnyValueArray value of the element or empty AnyValueArray if conversion is not supported. """ if index == None: array = [] for value in self: array.append(value) return array else: value = self[index] return AnyValueArray.from_value(value)
[ "def", "get_as_array", "(", "self", ",", "index", ")", ":", "if", "index", "==", "None", ":", "array", "=", "[", "]", "for", "value", "in", "self", ":", "array", ".", "append", "(", "value", ")", "return", "array", "else", ":", "value", "=", "self", "[", "index", "]", "return", "AnyValueArray", ".", "from_value", "(", "value", ")" ]
Converts array element into an AnyValueArray or returns empty AnyValueArray if conversion is not possible. :param index: an index of element to get. :return: AnyValueArray value of the element or empty AnyValueArray if conversion is not supported.
[ "Converts", "array", "element", "into", "an", "AnyValueArray", "or", "returns", "empty", "AnyValueArray", "if", "conversion", "is", "not", "possible", "." ]
22cbbb3e91e49717f65c083d36147fdb07ba9e3b
https://github.com/pip-services3-python/pip-services3-commons-python/blob/22cbbb3e91e49717f65c083d36147fdb07ba9e3b/pip_services3_commons/data/AnyValueArray.py#L82-L97
238,716
pip-services3-python/pip-services3-commons-python
pip_services3_commons/data/AnyValueArray.py
AnyValueArray.get_as_string_with_default
def get_as_string_with_default(self, index, default_value): """ Converts array element into a string or returns default value if conversion is not possible. :param index: an index of element to get. :param default_value: the default value :return: string value ot the element or default value if conversion is not supported. """ value = self[index] return StringConverter.to_string_with_default(value, default_value)
python
def get_as_string_with_default(self, index, default_value): """ Converts array element into a string or returns default value if conversion is not possible. :param index: an index of element to get. :param default_value: the default value :return: string value ot the element or default value if conversion is not supported. """ value = self[index] return StringConverter.to_string_with_default(value, default_value)
[ "def", "get_as_string_with_default", "(", "self", ",", "index", ",", "default_value", ")", ":", "value", "=", "self", "[", "index", "]", "return", "StringConverter", ".", "to_string_with_default", "(", "value", ",", "default_value", ")" ]
Converts array element into a string or returns default value if conversion is not possible. :param index: an index of element to get. :param default_value: the default value :return: string value ot the element or default value if conversion is not supported.
[ "Converts", "array", "element", "into", "a", "string", "or", "returns", "default", "value", "if", "conversion", "is", "not", "possible", "." ]
22cbbb3e91e49717f65c083d36147fdb07ba9e3b
https://github.com/pip-services3-python/pip-services3-commons-python/blob/22cbbb3e91e49717f65c083d36147fdb07ba9e3b/pip_services3_commons/data/AnyValueArray.py#L131-L142
238,717
pip-services3-python/pip-services3-commons-python
pip_services3_commons/data/AnyValueArray.py
AnyValueArray.get_as_boolean_with_default
def get_as_boolean_with_default(self, index, default_value): """ Converts array element into a boolean or returns default value if conversion is not possible. :param index: an index of element to get. :param default_value: the default value :return: boolean value ot the element or default value if conversion is not supported. """ value = self[index] return BooleanConverter.to_boolean_with_default(value, default_value)
python
def get_as_boolean_with_default(self, index, default_value): """ Converts array element into a boolean or returns default value if conversion is not possible. :param index: an index of element to get. :param default_value: the default value :return: boolean value ot the element or default value if conversion is not supported. """ value = self[index] return BooleanConverter.to_boolean_with_default(value, default_value)
[ "def", "get_as_boolean_with_default", "(", "self", ",", "index", ",", "default_value", ")", ":", "value", "=", "self", "[", "index", "]", "return", "BooleanConverter", ".", "to_boolean_with_default", "(", "value", ",", "default_value", ")" ]
Converts array element into a boolean or returns default value if conversion is not possible. :param index: an index of element to get. :param default_value: the default value :return: boolean value ot the element or default value if conversion is not supported.
[ "Converts", "array", "element", "into", "a", "boolean", "or", "returns", "default", "value", "if", "conversion", "is", "not", "possible", "." ]
22cbbb3e91e49717f65c083d36147fdb07ba9e3b
https://github.com/pip-services3-python/pip-services3-commons-python/blob/22cbbb3e91e49717f65c083d36147fdb07ba9e3b/pip_services3_commons/data/AnyValueArray.py#L166-L177
238,718
pip-services3-python/pip-services3-commons-python
pip_services3_commons/data/AnyValueArray.py
AnyValueArray.get_as_integer_with_default
def get_as_integer_with_default(self, index, default_value): """ Converts array element into an integer or returns default value if conversion is not possible. :param index: an index of element to get. :param default_value: the default value :return: integer value ot the element or default value if conversion is not supported. """ value = self[index] return IntegerConverter.to_integer_with_default(value, default_value)
python
def get_as_integer_with_default(self, index, default_value): """ Converts array element into an integer or returns default value if conversion is not possible. :param index: an index of element to get. :param default_value: the default value :return: integer value ot the element or default value if conversion is not supported. """ value = self[index] return IntegerConverter.to_integer_with_default(value, default_value)
[ "def", "get_as_integer_with_default", "(", "self", ",", "index", ",", "default_value", ")", ":", "value", "=", "self", "[", "index", "]", "return", "IntegerConverter", ".", "to_integer_with_default", "(", "value", ",", "default_value", ")" ]
Converts array element into an integer or returns default value if conversion is not possible. :param index: an index of element to get. :param default_value: the default value :return: integer value ot the element or default value if conversion is not supported.
[ "Converts", "array", "element", "into", "an", "integer", "or", "returns", "default", "value", "if", "conversion", "is", "not", "possible", "." ]
22cbbb3e91e49717f65c083d36147fdb07ba9e3b
https://github.com/pip-services3-python/pip-services3-commons-python/blob/22cbbb3e91e49717f65c083d36147fdb07ba9e3b/pip_services3_commons/data/AnyValueArray.py#L201-L212
238,719
pip-services3-python/pip-services3-commons-python
pip_services3_commons/data/AnyValueArray.py
AnyValueArray.get_as_float_with_default
def get_as_float_with_default(self, index, default_value): """ Converts array element into a float or returns default value if conversion is not possible. :param index: an index of element to get. :param default_value: the default value :return: float value ot the element or default value if conversion is not supported. """ value = self[index] return FloatConverter.to_float_with_default(value, default_value)
python
def get_as_float_with_default(self, index, default_value): """ Converts array element into a float or returns default value if conversion is not possible. :param index: an index of element to get. :param default_value: the default value :return: float value ot the element or default value if conversion is not supported. """ value = self[index] return FloatConverter.to_float_with_default(value, default_value)
[ "def", "get_as_float_with_default", "(", "self", ",", "index", ",", "default_value", ")", ":", "value", "=", "self", "[", "index", "]", "return", "FloatConverter", ".", "to_float_with_default", "(", "value", ",", "default_value", ")" ]
Converts array element into a float or returns default value if conversion is not possible. :param index: an index of element to get. :param default_value: the default value :return: float value ot the element or default value if conversion is not supported.
[ "Converts", "array", "element", "into", "a", "float", "or", "returns", "default", "value", "if", "conversion", "is", "not", "possible", "." ]
22cbbb3e91e49717f65c083d36147fdb07ba9e3b
https://github.com/pip-services3-python/pip-services3-commons-python/blob/22cbbb3e91e49717f65c083d36147fdb07ba9e3b/pip_services3_commons/data/AnyValueArray.py#L248-L259
238,720
pip-services3-python/pip-services3-commons-python
pip_services3_commons/data/AnyValueArray.py
AnyValueArray.get_as_datetime_with_default
def get_as_datetime_with_default(self, index, default_value): """ Converts array element into a Date or returns default value if conversion is not possible. :param index: an index of element to get. :param default_value: the default value :return: Date value ot the element or default value if conversion is not supported. """ value = self[index] return DateTimeConverter.to_datetime_with_default(value, default_value)
python
def get_as_datetime_with_default(self, index, default_value): """ Converts array element into a Date or returns default value if conversion is not possible. :param index: an index of element to get. :param default_value: the default value :return: Date value ot the element or default value if conversion is not supported. """ value = self[index] return DateTimeConverter.to_datetime_with_default(value, default_value)
[ "def", "get_as_datetime_with_default", "(", "self", ",", "index", ",", "default_value", ")", ":", "value", "=", "self", "[", "index", "]", "return", "DateTimeConverter", ".", "to_datetime_with_default", "(", "value", ",", "default_value", ")" ]
Converts array element into a Date or returns default value if conversion is not possible. :param index: an index of element to get. :param default_value: the default value :return: Date value ot the element or default value if conversion is not supported.
[ "Converts", "array", "element", "into", "a", "Date", "or", "returns", "default", "value", "if", "conversion", "is", "not", "possible", "." ]
22cbbb3e91e49717f65c083d36147fdb07ba9e3b
https://github.com/pip-services3-python/pip-services3-commons-python/blob/22cbbb3e91e49717f65c083d36147fdb07ba9e3b/pip_services3_commons/data/AnyValueArray.py#L283-L294
238,721
pip-services3-python/pip-services3-commons-python
pip_services3_commons/data/AnyValueArray.py
AnyValueArray.get_as_nullable_type
def get_as_nullable_type(self, index, value_type): """ Converts array element into a value defined by specied typecode. If conversion is not possible it returns None. :param index: an index of element to get. :param value_type: the TypeCode that defined the type of the result :return: element value defined by the typecode or None if conversion is not supported. """ value = self[index] return TypeConverter.to_nullable_type(value_type, value)
python
def get_as_nullable_type(self, index, value_type): """ Converts array element into a value defined by specied typecode. If conversion is not possible it returns None. :param index: an index of element to get. :param value_type: the TypeCode that defined the type of the result :return: element value defined by the typecode or None if conversion is not supported. """ value = self[index] return TypeConverter.to_nullable_type(value_type, value)
[ "def", "get_as_nullable_type", "(", "self", ",", "index", ",", "value_type", ")", ":", "value", "=", "self", "[", "index", "]", "return", "TypeConverter", ".", "to_nullable_type", "(", "value_type", ",", "value", ")" ]
Converts array element into a value defined by specied typecode. If conversion is not possible it returns None. :param index: an index of element to get. :param value_type: the TypeCode that defined the type of the result :return: element value defined by the typecode or None if conversion is not supported.
[ "Converts", "array", "element", "into", "a", "value", "defined", "by", "specied", "typecode", ".", "If", "conversion", "is", "not", "possible", "it", "returns", "None", "." ]
22cbbb3e91e49717f65c083d36147fdb07ba9e3b
https://github.com/pip-services3-python/pip-services3-commons-python/blob/22cbbb3e91e49717f65c083d36147fdb07ba9e3b/pip_services3_commons/data/AnyValueArray.py#L296-L308
238,722
pip-services3-python/pip-services3-commons-python
pip_services3_commons/data/AnyValueArray.py
AnyValueArray.get_as_type
def get_as_type(self, index, value_type): """ Converts array element into a value defined by specied typecode. If conversion is not possible it returns default value for the specified type. :param index: an index of element to get. :param value_type: the TypeCode that defined the type of the result :return: element value defined by the typecode or default if conversion is not supported. """ value = self[index] return TypeConverter.to_type(value_type, value)
python
def get_as_type(self, index, value_type): """ Converts array element into a value defined by specied typecode. If conversion is not possible it returns default value for the specified type. :param index: an index of element to get. :param value_type: the TypeCode that defined the type of the result :return: element value defined by the typecode or default if conversion is not supported. """ value = self[index] return TypeConverter.to_type(value_type, value)
[ "def", "get_as_type", "(", "self", ",", "index", ",", "value_type", ")", ":", "value", "=", "self", "[", "index", "]", "return", "TypeConverter", ".", "to_type", "(", "value_type", ",", "value", ")" ]
Converts array element into a value defined by specied typecode. If conversion is not possible it returns default value for the specified type. :param index: an index of element to get. :param value_type: the TypeCode that defined the type of the result :return: element value defined by the typecode or default if conversion is not supported.
[ "Converts", "array", "element", "into", "a", "value", "defined", "by", "specied", "typecode", ".", "If", "conversion", "is", "not", "possible", "it", "returns", "default", "value", "for", "the", "specified", "type", "." ]
22cbbb3e91e49717f65c083d36147fdb07ba9e3b
https://github.com/pip-services3-python/pip-services3-commons-python/blob/22cbbb3e91e49717f65c083d36147fdb07ba9e3b/pip_services3_commons/data/AnyValueArray.py#L310-L322
238,723
pip-services3-python/pip-services3-commons-python
pip_services3_commons/data/AnyValueArray.py
AnyValueArray.get_as_type_with_default
def get_as_type_with_default(self, index, value_type, default_value): """ Converts array element into a value defined by specied typecode. If conversion is not possible it returns default value. :param index: an index of element to get. :param value_type: the TypeCode that defined the type of the result :param default_value: the default value :return: element value defined by the typecode or default value if conversion is not supported. """ value = self[index] return TypeConverter.to_type_with_default(value_type, value, default_value)
python
def get_as_type_with_default(self, index, value_type, default_value): """ Converts array element into a value defined by specied typecode. If conversion is not possible it returns default value. :param index: an index of element to get. :param value_type: the TypeCode that defined the type of the result :param default_value: the default value :return: element value defined by the typecode or default value if conversion is not supported. """ value = self[index] return TypeConverter.to_type_with_default(value_type, value, default_value)
[ "def", "get_as_type_with_default", "(", "self", ",", "index", ",", "value_type", ",", "default_value", ")", ":", "value", "=", "self", "[", "index", "]", "return", "TypeConverter", ".", "to_type_with_default", "(", "value_type", ",", "value", ",", "default_value", ")" ]
Converts array element into a value defined by specied typecode. If conversion is not possible it returns default value. :param index: an index of element to get. :param value_type: the TypeCode that defined the type of the result :param default_value: the default value :return: element value defined by the typecode or default value if conversion is not supported.
[ "Converts", "array", "element", "into", "a", "value", "defined", "by", "specied", "typecode", ".", "If", "conversion", "is", "not", "possible", "it", "returns", "default", "value", "." ]
22cbbb3e91e49717f65c083d36147fdb07ba9e3b
https://github.com/pip-services3-python/pip-services3-commons-python/blob/22cbbb3e91e49717f65c083d36147fdb07ba9e3b/pip_services3_commons/data/AnyValueArray.py#L324-L338
238,724
pip-services3-python/pip-services3-commons-python
pip_services3_commons/data/AnyValueArray.py
AnyValueArray.contains
def contains(self, value): """ Checks if this array contains a value. The check uses direct comparison between elements and the specified value. :param value: a value to be checked :return: true if this array contains the value or false otherwise. """ str_value = StringConverter.to_nullable_string(value) for element in self: str_element = StringConverter.to_string(element) if str_value == None and str_element == None: return True if str_value == None or str_element == None: continue if str_value == str_element: return True return False
python
def contains(self, value): """ Checks if this array contains a value. The check uses direct comparison between elements and the specified value. :param value: a value to be checked :return: true if this array contains the value or false otherwise. """ str_value = StringConverter.to_nullable_string(value) for element in self: str_element = StringConverter.to_string(element) if str_value == None and str_element == None: return True if str_value == None or str_element == None: continue if str_value == str_element: return True return False
[ "def", "contains", "(", "self", ",", "value", ")", ":", "str_value", "=", "StringConverter", ".", "to_nullable_string", "(", "value", ")", "for", "element", "in", "self", ":", "str_element", "=", "StringConverter", ".", "to_string", "(", "element", ")", "if", "str_value", "==", "None", "and", "str_element", "==", "None", ":", "return", "True", "if", "str_value", "==", "None", "or", "str_element", "==", "None", ":", "continue", "if", "str_value", "==", "str_element", ":", "return", "True", "return", "False" ]
Checks if this array contains a value. The check uses direct comparison between elements and the specified value. :param value: a value to be checked :return: true if this array contains the value or false otherwise.
[ "Checks", "if", "this", "array", "contains", "a", "value", ".", "The", "check", "uses", "direct", "comparison", "between", "elements", "and", "the", "specified", "value", "." ]
22cbbb3e91e49717f65c083d36147fdb07ba9e3b
https://github.com/pip-services3-python/pip-services3-commons-python/blob/22cbbb3e91e49717f65c083d36147fdb07ba9e3b/pip_services3_commons/data/AnyValueArray.py#L367-L389
238,725
pip-services3-python/pip-services3-commons-python
pip_services3_commons/data/AnyValueArray.py
AnyValueArray.contains_as_type
def contains_as_type(self, value_type, value): """ Checks if this array contains a value. The check before comparison converts elements and the value to type specified by type code. :param value_type: a type code that defines a type to convert values before comparison :param value: a value to be checked :return: true if this array contains the value or false otherwise. """ typed_value = TypeConverter.to_nullable_type(value_type, value) for element in self: typed_element = TypeConverter.to_type(value_type, element) if typed_value == None and typed_element == None: return True if typed_value == None or typed_element == None: continue if typed_value == typed_element: return True return False
python
def contains_as_type(self, value_type, value): """ Checks if this array contains a value. The check before comparison converts elements and the value to type specified by type code. :param value_type: a type code that defines a type to convert values before comparison :param value: a value to be checked :return: true if this array contains the value or false otherwise. """ typed_value = TypeConverter.to_nullable_type(value_type, value) for element in self: typed_element = TypeConverter.to_type(value_type, element) if typed_value == None and typed_element == None: return True if typed_value == None or typed_element == None: continue if typed_value == typed_element: return True return False
[ "def", "contains_as_type", "(", "self", ",", "value_type", ",", "value", ")", ":", "typed_value", "=", "TypeConverter", ".", "to_nullable_type", "(", "value_type", ",", "value", ")", "for", "element", "in", "self", ":", "typed_element", "=", "TypeConverter", ".", "to_type", "(", "value_type", ",", "element", ")", "if", "typed_value", "==", "None", "and", "typed_element", "==", "None", ":", "return", "True", "if", "typed_value", "==", "None", "or", "typed_element", "==", "None", ":", "continue", "if", "typed_value", "==", "typed_element", ":", "return", "True", "return", "False" ]
Checks if this array contains a value. The check before comparison converts elements and the value to type specified by type code. :param value_type: a type code that defines a type to convert values before comparison :param value: a value to be checked :return: true if this array contains the value or false otherwise.
[ "Checks", "if", "this", "array", "contains", "a", "value", ".", "The", "check", "before", "comparison", "converts", "elements", "and", "the", "value", "to", "type", "specified", "by", "type", "code", "." ]
22cbbb3e91e49717f65c083d36147fdb07ba9e3b
https://github.com/pip-services3-python/pip-services3-commons-python/blob/22cbbb3e91e49717f65c083d36147fdb07ba9e3b/pip_services3_commons/data/AnyValueArray.py#L392-L416
238,726
pip-services3-python/pip-services3-commons-python
pip_services3_commons/data/AnyValueArray.py
AnyValueArray.from_value
def from_value(value): """ Converts specified value into AnyValueArray. :param value: value to be converted :return: a newly created AnyValueArray. """ value = ArrayConverter.to_nullable_array(value) if value != None: return AnyValueArray(value) return AnyValueArray()
python
def from_value(value): """ Converts specified value into AnyValueArray. :param value: value to be converted :return: a newly created AnyValueArray. """ value = ArrayConverter.to_nullable_array(value) if value != None: return AnyValueArray(value) return AnyValueArray()
[ "def", "from_value", "(", "value", ")", ":", "value", "=", "ArrayConverter", ".", "to_nullable_array", "(", "value", ")", "if", "value", "!=", "None", ":", "return", "AnyValueArray", "(", "value", ")", "return", "AnyValueArray", "(", ")" ]
Converts specified value into AnyValueArray. :param value: value to be converted :return: a newly created AnyValueArray.
[ "Converts", "specified", "value", "into", "AnyValueArray", "." ]
22cbbb3e91e49717f65c083d36147fdb07ba9e3b
https://github.com/pip-services3-python/pip-services3-commons-python/blob/22cbbb3e91e49717f65c083d36147fdb07ba9e3b/pip_services3_commons/data/AnyValueArray.py#L457-L468
238,727
pip-services3-python/pip-services3-commons-python
pip_services3_commons/data/AnyValueArray.py
AnyValueArray.from_string
def from_string(values, separator, remove_duplicates = False): """ Splits specified string into elements using a separator and assigns the elements to a newly created AnyValueArray. :param values: a string value to be split and assigned to AnyValueArray :param separator: a separator to split the string :param remove_duplicates: (optional) true to remove duplicated elements :return: a newly created AnyValueArray. """ result = AnyValueArray() if values == None or len(values) == 0: return result items = str(values).split(separator) for item in items: if (item != None and len(item) > 0) or remove_duplicates == False: result.append(item) return result
python
def from_string(values, separator, remove_duplicates = False): """ Splits specified string into elements using a separator and assigns the elements to a newly created AnyValueArray. :param values: a string value to be split and assigned to AnyValueArray :param separator: a separator to split the string :param remove_duplicates: (optional) true to remove duplicated elements :return: a newly created AnyValueArray. """ result = AnyValueArray() if values == None or len(values) == 0: return result items = str(values).split(separator) for item in items: if (item != None and len(item) > 0) or remove_duplicates == False: result.append(item) return result
[ "def", "from_string", "(", "values", ",", "separator", ",", "remove_duplicates", "=", "False", ")", ":", "result", "=", "AnyValueArray", "(", ")", "if", "values", "==", "None", "or", "len", "(", "values", ")", "==", "0", ":", "return", "result", "items", "=", "str", "(", "values", ")", ".", "split", "(", "separator", ")", "for", "item", "in", "items", ":", "if", "(", "item", "!=", "None", "and", "len", "(", "item", ")", ">", "0", ")", "or", "remove_duplicates", "==", "False", ":", "result", ".", "append", "(", "item", ")", "return", "result" ]
Splits specified string into elements using a separator and assigns the elements to a newly created AnyValueArray. :param values: a string value to be split and assigned to AnyValueArray :param separator: a separator to split the string :param remove_duplicates: (optional) true to remove duplicated elements :return: a newly created AnyValueArray.
[ "Splits", "specified", "string", "into", "elements", "using", "a", "separator", "and", "assigns", "the", "elements", "to", "a", "newly", "created", "AnyValueArray", "." ]
22cbbb3e91e49717f65c083d36147fdb07ba9e3b
https://github.com/pip-services3-python/pip-services3-commons-python/blob/22cbbb3e91e49717f65c083d36147fdb07ba9e3b/pip_services3_commons/data/AnyValueArray.py#L471-L494
238,728
JukeboxPipeline/jukebox-core
src/jukeboxcore/gui/widgetdelegate.py
WidgetDelegate.paint
def paint(self, painter, option, index): """Use the painter and style option to render the item specified by the item index. :param painter: the painter to paint :type painter: :class:`QtGui.QPainter` :param option: the options for painting :type option: :class:`QtGui.QStyleOptionViewItem` :param index: the index to paint :type index: :class:`QtCore.QModelIndex` :returns: None :rtype: None :raises: None """ if self._widget is None: return super(WidgetDelegate, self).paint(painter, option, index) self.set_widget_index(index) painter.save() painter.translate(option.rect.topLeft()) self._widget.resize(option.rect.size()) self._widget.render(painter, QtCore.QPoint()) painter.restore()
python
def paint(self, painter, option, index): """Use the painter and style option to render the item specified by the item index. :param painter: the painter to paint :type painter: :class:`QtGui.QPainter` :param option: the options for painting :type option: :class:`QtGui.QStyleOptionViewItem` :param index: the index to paint :type index: :class:`QtCore.QModelIndex` :returns: None :rtype: None :raises: None """ if self._widget is None: return super(WidgetDelegate, self).paint(painter, option, index) self.set_widget_index(index) painter.save() painter.translate(option.rect.topLeft()) self._widget.resize(option.rect.size()) self._widget.render(painter, QtCore.QPoint()) painter.restore()
[ "def", "paint", "(", "self", ",", "painter", ",", "option", ",", "index", ")", ":", "if", "self", ".", "_widget", "is", "None", ":", "return", "super", "(", "WidgetDelegate", ",", "self", ")", ".", "paint", "(", "painter", ",", "option", ",", "index", ")", "self", ".", "set_widget_index", "(", "index", ")", "painter", ".", "save", "(", ")", "painter", ".", "translate", "(", "option", ".", "rect", ".", "topLeft", "(", ")", ")", "self", ".", "_widget", ".", "resize", "(", "option", ".", "rect", ".", "size", "(", ")", ")", "self", ".", "_widget", ".", "render", "(", "painter", ",", "QtCore", ".", "QPoint", "(", ")", ")", "painter", ".", "restore", "(", ")" ]
Use the painter and style option to render the item specified by the item index. :param painter: the painter to paint :type painter: :class:`QtGui.QPainter` :param option: the options for painting :type option: :class:`QtGui.QStyleOptionViewItem` :param index: the index to paint :type index: :class:`QtCore.QModelIndex` :returns: None :rtype: None :raises: None
[ "Use", "the", "painter", "and", "style", "option", "to", "render", "the", "item", "specified", "by", "the", "item", "index", "." ]
bac2280ca49940355270e4b69400ce9976ab2e6f
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/gui/widgetdelegate.py#L87-L108
238,729
JukeboxPipeline/jukebox-core
src/jukeboxcore/gui/widgetdelegate.py
WidgetDelegate.sizeHint
def sizeHint(self, option, index): """Return the appropriate amount for the size of the widget The widget will always be expanded to at least the size of the viewport. :param option: the options for painting :type option: :class:`QtGui.QStyleOptionViewItem` :param index: the index to paint :type index: :class:`QtCore.QModelIndex` :returns: None :rtype: None :raises: None """ if self._widget is None: return super(WidgetDelegate, self).sizeHint(option, index) self.set_widget_index(index) self._widget.resize(option.rect.size()) sh = self._widget.sizeHint() return sh
python
def sizeHint(self, option, index): """Return the appropriate amount for the size of the widget The widget will always be expanded to at least the size of the viewport. :param option: the options for painting :type option: :class:`QtGui.QStyleOptionViewItem` :param index: the index to paint :type index: :class:`QtCore.QModelIndex` :returns: None :rtype: None :raises: None """ if self._widget is None: return super(WidgetDelegate, self).sizeHint(option, index) self.set_widget_index(index) self._widget.resize(option.rect.size()) sh = self._widget.sizeHint() return sh
[ "def", "sizeHint", "(", "self", ",", "option", ",", "index", ")", ":", "if", "self", ".", "_widget", "is", "None", ":", "return", "super", "(", "WidgetDelegate", ",", "self", ")", ".", "sizeHint", "(", "option", ",", "index", ")", "self", ".", "set_widget_index", "(", "index", ")", "self", ".", "_widget", ".", "resize", "(", "option", ".", "rect", ".", "size", "(", ")", ")", "sh", "=", "self", ".", "_widget", ".", "sizeHint", "(", ")", "return", "sh" ]
Return the appropriate amount for the size of the widget The widget will always be expanded to at least the size of the viewport. :param option: the options for painting :type option: :class:`QtGui.QStyleOptionViewItem` :param index: the index to paint :type index: :class:`QtCore.QModelIndex` :returns: None :rtype: None :raises: None
[ "Return", "the", "appropriate", "amount", "for", "the", "size", "of", "the", "widget" ]
bac2280ca49940355270e4b69400ce9976ab2e6f
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/gui/widgetdelegate.py#L110-L129
238,730
JukeboxPipeline/jukebox-core
src/jukeboxcore/gui/widgetdelegate.py
WidgetDelegate.close_editors
def close_editors(self, ): """Close all current editors :returns: None :rtype: None :raises: None """ for k in reversed(self._edit_widgets.keys()): self.commit_close_editor(k)
python
def close_editors(self, ): """Close all current editors :returns: None :rtype: None :raises: None """ for k in reversed(self._edit_widgets.keys()): self.commit_close_editor(k)
[ "def", "close_editors", "(", "self", ",", ")", ":", "for", "k", "in", "reversed", "(", "self", ".", "_edit_widgets", ".", "keys", "(", ")", ")", ":", "self", ".", "commit_close_editor", "(", "k", ")" ]
Close all current editors :returns: None :rtype: None :raises: None
[ "Close", "all", "current", "editors" ]
bac2280ca49940355270e4b69400ce9976ab2e6f
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/gui/widgetdelegate.py#L158-L166
238,731
JukeboxPipeline/jukebox-core
src/jukeboxcore/gui/widgetdelegate.py
WidgetDelegate.createEditor
def createEditor(self, parent, option, index): """Return the editor to be used for editing the data item with the given index. Note that the index contains information about the model being used. The editor's parent widget is specified by parent, and the item options by option. This will set auto fill background to True on the editor, because else, you would see The rendered delegate below. :param parent: the parent widget :type parent: QtGui.QWidget :param option: the options for painting :type option: QtGui.QStyleOptionViewItem :param index: the index to paint :type index: QtCore.QModelIndex :returns: The created widget | None :rtype: :class:`QtGui.QWidget` | None :raises: None """ # close all editors self.close_editors() e = self.create_editor_widget(parent, option, index) if e: self._edit_widgets[index] = e e.setAutoFillBackground(True) e.destroyed.connect(partial(self.editor_destroyed, index=index)) return e
python
def createEditor(self, parent, option, index): """Return the editor to be used for editing the data item with the given index. Note that the index contains information about the model being used. The editor's parent widget is specified by parent, and the item options by option. This will set auto fill background to True on the editor, because else, you would see The rendered delegate below. :param parent: the parent widget :type parent: QtGui.QWidget :param option: the options for painting :type option: QtGui.QStyleOptionViewItem :param index: the index to paint :type index: QtCore.QModelIndex :returns: The created widget | None :rtype: :class:`QtGui.QWidget` | None :raises: None """ # close all editors self.close_editors() e = self.create_editor_widget(parent, option, index) if e: self._edit_widgets[index] = e e.setAutoFillBackground(True) e.destroyed.connect(partial(self.editor_destroyed, index=index)) return e
[ "def", "createEditor", "(", "self", ",", "parent", ",", "option", ",", "index", ")", ":", "# close all editors", "self", ".", "close_editors", "(", ")", "e", "=", "self", ".", "create_editor_widget", "(", "parent", ",", "option", ",", "index", ")", "if", "e", ":", "self", ".", "_edit_widgets", "[", "index", "]", "=", "e", "e", ".", "setAutoFillBackground", "(", "True", ")", "e", ".", "destroyed", ".", "connect", "(", "partial", "(", "self", ".", "editor_destroyed", ",", "index", "=", "index", ")", ")", "return", "e" ]
Return the editor to be used for editing the data item with the given index. Note that the index contains information about the model being used. The editor's parent widget is specified by parent, and the item options by option. This will set auto fill background to True on the editor, because else, you would see The rendered delegate below. :param parent: the parent widget :type parent: QtGui.QWidget :param option: the options for painting :type option: QtGui.QStyleOptionViewItem :param index: the index to paint :type index: QtCore.QModelIndex :returns: The created widget | None :rtype: :class:`QtGui.QWidget` | None :raises: None
[ "Return", "the", "editor", "to", "be", "used", "for", "editing", "the", "data", "item", "with", "the", "given", "index", "." ]
bac2280ca49940355270e4b69400ce9976ab2e6f
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/gui/widgetdelegate.py#L168-L194
238,732
JukeboxPipeline/jukebox-core
src/jukeboxcore/gui/widgetdelegate.py
WidgetDelegate.commit_close_editor
def commit_close_editor(self, index, endedithint=QtGui.QAbstractItemDelegate.NoHint): """Commit and close the editor Call this method whenever the user finished editing. :param index: The index of the editor :type index: :class:`QtCore.QModelIndex` :param endedithint: Hints that the delegate can give the model and view to make editing data comfortable for the user :type endedithint: :data:`QtGui.QAbstractItemDelegate.EndEditHint` :returns: None :rtype: None :raises: None """ editor = self._edit_widgets[index] self.commitData.emit(editor) self.closeEditor.emit(editor, endedithint) del self._edit_widgets[index]
python
def commit_close_editor(self, index, endedithint=QtGui.QAbstractItemDelegate.NoHint): """Commit and close the editor Call this method whenever the user finished editing. :param index: The index of the editor :type index: :class:`QtCore.QModelIndex` :param endedithint: Hints that the delegate can give the model and view to make editing data comfortable for the user :type endedithint: :data:`QtGui.QAbstractItemDelegate.EndEditHint` :returns: None :rtype: None :raises: None """ editor = self._edit_widgets[index] self.commitData.emit(editor) self.closeEditor.emit(editor, endedithint) del self._edit_widgets[index]
[ "def", "commit_close_editor", "(", "self", ",", "index", ",", "endedithint", "=", "QtGui", ".", "QAbstractItemDelegate", ".", "NoHint", ")", ":", "editor", "=", "self", ".", "_edit_widgets", "[", "index", "]", "self", ".", "commitData", ".", "emit", "(", "editor", ")", "self", ".", "closeEditor", ".", "emit", "(", "editor", ",", "endedithint", ")", "del", "self", ".", "_edit_widgets", "[", "index", "]" ]
Commit and close the editor Call this method whenever the user finished editing. :param index: The index of the editor :type index: :class:`QtCore.QModelIndex` :param endedithint: Hints that the delegate can give the model and view to make editing data comfortable for the user :type endedithint: :data:`QtGui.QAbstractItemDelegate.EndEditHint` :returns: None :rtype: None :raises: None
[ "Commit", "and", "close", "the", "editor" ]
bac2280ca49940355270e4b69400ce9976ab2e6f
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/gui/widgetdelegate.py#L211-L228
238,733
JukeboxPipeline/jukebox-core
src/jukeboxcore/gui/widgetdelegate.py
WidgetDelegate.updateEditorGeometry
def updateEditorGeometry(self, editor, option, index): """Make sure the editor is the same size as the widget By default it can get smaller because does not expand over viewport size. This will make sure it will resize to the same size as the widget. :param editor: the editor to update :type editor: :class:`QtGui.QWidget` :param option: the options for painting :type option: QtGui.QStyleOptionViewItem :param index: the index to paint :type index: QtCore.QModelIndex :returns: None :rtype: None :raises: None """ super(WidgetDelegate, self).updateEditorGeometry(editor, option, index) editor.setGeometry(option.rect) if self.keep_editor_size: esh = editor.sizeHint() osh = option.rect.size() w = osh.width() if osh.width() > esh.width() else esh.width() h = osh.height() if osh.height() > esh.height() else esh.height() editor.resize(w, h)
python
def updateEditorGeometry(self, editor, option, index): """Make sure the editor is the same size as the widget By default it can get smaller because does not expand over viewport size. This will make sure it will resize to the same size as the widget. :param editor: the editor to update :type editor: :class:`QtGui.QWidget` :param option: the options for painting :type option: QtGui.QStyleOptionViewItem :param index: the index to paint :type index: QtCore.QModelIndex :returns: None :rtype: None :raises: None """ super(WidgetDelegate, self).updateEditorGeometry(editor, option, index) editor.setGeometry(option.rect) if self.keep_editor_size: esh = editor.sizeHint() osh = option.rect.size() w = osh.width() if osh.width() > esh.width() else esh.width() h = osh.height() if osh.height() > esh.height() else esh.height() editor.resize(w, h)
[ "def", "updateEditorGeometry", "(", "self", ",", "editor", ",", "option", ",", "index", ")", ":", "super", "(", "WidgetDelegate", ",", "self", ")", ".", "updateEditorGeometry", "(", "editor", ",", "option", ",", "index", ")", "editor", ".", "setGeometry", "(", "option", ".", "rect", ")", "if", "self", ".", "keep_editor_size", ":", "esh", "=", "editor", ".", "sizeHint", "(", ")", "osh", "=", "option", ".", "rect", ".", "size", "(", ")", "w", "=", "osh", ".", "width", "(", ")", "if", "osh", ".", "width", "(", ")", ">", "esh", ".", "width", "(", ")", "else", "esh", ".", "width", "(", ")", "h", "=", "osh", ".", "height", "(", ")", "if", "osh", ".", "height", "(", ")", ">", "esh", ".", "height", "(", ")", "else", "esh", ".", "height", "(", ")", "editor", ".", "resize", "(", "w", ",", "h", ")" ]
Make sure the editor is the same size as the widget By default it can get smaller because does not expand over viewport size. This will make sure it will resize to the same size as the widget. :param editor: the editor to update :type editor: :class:`QtGui.QWidget` :param option: the options for painting :type option: QtGui.QStyleOptionViewItem :param index: the index to paint :type index: QtCore.QModelIndex :returns: None :rtype: None :raises: None
[ "Make", "sure", "the", "editor", "is", "the", "same", "size", "as", "the", "widget" ]
bac2280ca49940355270e4b69400ce9976ab2e6f
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/gui/widgetdelegate.py#L254-L277
238,734
JukeboxPipeline/jukebox-core
src/jukeboxcore/gui/widgetdelegate.py
WidgetDelegateViewMixin.get_pos_in_delegate
def get_pos_in_delegate(self, index, globalpos): """Map the global position to the position relative to the given index :param index: the index to map to :type index: :class:`QtCore.QModelIndex` :param globalpos: the global position :type globalpos: :class:`QtCore.QPoint` :returns: The position relative to the given index :rtype: :class:`QtCore.QPoint` :raises: None """ rect = self.visualRect(index) # rect of the index p = self.viewport().mapToGlobal(rect.topLeft()) return globalpos - p
python
def get_pos_in_delegate(self, index, globalpos): """Map the global position to the position relative to the given index :param index: the index to map to :type index: :class:`QtCore.QModelIndex` :param globalpos: the global position :type globalpos: :class:`QtCore.QPoint` :returns: The position relative to the given index :rtype: :class:`QtCore.QPoint` :raises: None """ rect = self.visualRect(index) # rect of the index p = self.viewport().mapToGlobal(rect.topLeft()) return globalpos - p
[ "def", "get_pos_in_delegate", "(", "self", ",", "index", ",", "globalpos", ")", ":", "rect", "=", "self", ".", "visualRect", "(", "index", ")", "# rect of the index", "p", "=", "self", ".", "viewport", "(", ")", ".", "mapToGlobal", "(", "rect", ".", "topLeft", "(", ")", ")", "return", "globalpos", "-", "p" ]
Map the global position to the position relative to the given index :param index: the index to map to :type index: :class:`QtCore.QModelIndex` :param globalpos: the global position :type globalpos: :class:`QtCore.QPoint` :returns: The position relative to the given index :rtype: :class:`QtCore.QPoint` :raises: None
[ "Map", "the", "global", "position", "to", "the", "position", "relative", "to", "the", "given", "index" ]
bac2280ca49940355270e4b69400ce9976ab2e6f
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/gui/widgetdelegate.py#L377-L391
238,735
JukeboxPipeline/jukebox-core
src/jukeboxcore/gui/widgetdelegate.py
WidgetDelegateViewMixin.propagate_event_to_delegate
def propagate_event_to_delegate(self, event, eventhandler): """Propagate the given Mouse event to the widgetdelegate Enter edit mode, get the editor widget and issue an event on that widget. :param event: the mouse event :type event: :class:`QtGui.QMouseEvent` :param eventhandler: the eventhandler to use. E.g. ``"mousePressEvent"`` :type eventhandler: str :returns: None :rtype: None :raises: None """ # if we are recursing because we sent a click event, and it got propagated to the parents # and we recieve it again, terminate if self.__recursing: return # find index at mouse position i = self.index_at_event(event) # if the index is not valid, we don't care # handle it the default way if not i.isValid(): return getattr(super(WidgetDelegateViewMixin, self), eventhandler)(event) # get the widget delegate. if there is None, handle it the default way delegate = self.itemDelegate(i) if not isinstance(delegate, WidgetDelegate): return getattr(super(WidgetDelegateViewMixin, self), eventhandler)(event) # see if there is already a editor widget = delegate.edit_widget(i) if not widget: # close all editors, then start editing delegate.close_editors() # Force editing. If in editing state, view will refuse editing. if self.state() == self.EditingState: self.setState(self.NoState) self.edit(i) # get the editor widget. if there is None, there is nothing to do so return widget = delegate.edit_widget(i) if not widget: return getattr(super(WidgetDelegateViewMixin, self), eventhandler)(event) # try to find the relative position to the widget pid = self.get_pos_in_delegate(i, event.globalPos()) widgetatpos = widget.childAt(pid) if widgetatpos: widgettoclick = widgetatpos g = widget.mapToGlobal(pid) clickpos = widgettoclick.mapFromGlobal(g) else: widgettoclick = widget clickpos = pid # create a new event for the editor widget. e = QtGui.QMouseEvent(event.type(), clickpos, event.button(), event.buttons(), event.modifiers()) # before we send, make sure, we cannot recurse self.__recursing = True try: r = QtGui.QApplication.sendEvent(widgettoclick, e) finally: self.__recursing = False # out of the recursion. now we can accept click events again return r
python
def propagate_event_to_delegate(self, event, eventhandler): """Propagate the given Mouse event to the widgetdelegate Enter edit mode, get the editor widget and issue an event on that widget. :param event: the mouse event :type event: :class:`QtGui.QMouseEvent` :param eventhandler: the eventhandler to use. E.g. ``"mousePressEvent"`` :type eventhandler: str :returns: None :rtype: None :raises: None """ # if we are recursing because we sent a click event, and it got propagated to the parents # and we recieve it again, terminate if self.__recursing: return # find index at mouse position i = self.index_at_event(event) # if the index is not valid, we don't care # handle it the default way if not i.isValid(): return getattr(super(WidgetDelegateViewMixin, self), eventhandler)(event) # get the widget delegate. if there is None, handle it the default way delegate = self.itemDelegate(i) if not isinstance(delegate, WidgetDelegate): return getattr(super(WidgetDelegateViewMixin, self), eventhandler)(event) # see if there is already a editor widget = delegate.edit_widget(i) if not widget: # close all editors, then start editing delegate.close_editors() # Force editing. If in editing state, view will refuse editing. if self.state() == self.EditingState: self.setState(self.NoState) self.edit(i) # get the editor widget. if there is None, there is nothing to do so return widget = delegate.edit_widget(i) if not widget: return getattr(super(WidgetDelegateViewMixin, self), eventhandler)(event) # try to find the relative position to the widget pid = self.get_pos_in_delegate(i, event.globalPos()) widgetatpos = widget.childAt(pid) if widgetatpos: widgettoclick = widgetatpos g = widget.mapToGlobal(pid) clickpos = widgettoclick.mapFromGlobal(g) else: widgettoclick = widget clickpos = pid # create a new event for the editor widget. e = QtGui.QMouseEvent(event.type(), clickpos, event.button(), event.buttons(), event.modifiers()) # before we send, make sure, we cannot recurse self.__recursing = True try: r = QtGui.QApplication.sendEvent(widgettoclick, e) finally: self.__recursing = False # out of the recursion. now we can accept click events again return r
[ "def", "propagate_event_to_delegate", "(", "self", ",", "event", ",", "eventhandler", ")", ":", "# if we are recursing because we sent a click event, and it got propagated to the parents", "# and we recieve it again, terminate", "if", "self", ".", "__recursing", ":", "return", "# find index at mouse position", "i", "=", "self", ".", "index_at_event", "(", "event", ")", "# if the index is not valid, we don't care", "# handle it the default way", "if", "not", "i", ".", "isValid", "(", ")", ":", "return", "getattr", "(", "super", "(", "WidgetDelegateViewMixin", ",", "self", ")", ",", "eventhandler", ")", "(", "event", ")", "# get the widget delegate. if there is None, handle it the default way", "delegate", "=", "self", ".", "itemDelegate", "(", "i", ")", "if", "not", "isinstance", "(", "delegate", ",", "WidgetDelegate", ")", ":", "return", "getattr", "(", "super", "(", "WidgetDelegateViewMixin", ",", "self", ")", ",", "eventhandler", ")", "(", "event", ")", "# see if there is already a editor", "widget", "=", "delegate", ".", "edit_widget", "(", "i", ")", "if", "not", "widget", ":", "# close all editors, then start editing", "delegate", ".", "close_editors", "(", ")", "# Force editing. If in editing state, view will refuse editing.", "if", "self", ".", "state", "(", ")", "==", "self", ".", "EditingState", ":", "self", ".", "setState", "(", "self", ".", "NoState", ")", "self", ".", "edit", "(", "i", ")", "# get the editor widget. if there is None, there is nothing to do so return", "widget", "=", "delegate", ".", "edit_widget", "(", "i", ")", "if", "not", "widget", ":", "return", "getattr", "(", "super", "(", "WidgetDelegateViewMixin", ",", "self", ")", ",", "eventhandler", ")", "(", "event", ")", "# try to find the relative position to the widget", "pid", "=", "self", ".", "get_pos_in_delegate", "(", "i", ",", "event", ".", "globalPos", "(", ")", ")", "widgetatpos", "=", "widget", ".", "childAt", "(", "pid", ")", "if", "widgetatpos", ":", "widgettoclick", "=", "widgetatpos", "g", "=", "widget", ".", "mapToGlobal", "(", "pid", ")", "clickpos", "=", "widgettoclick", ".", "mapFromGlobal", "(", "g", ")", "else", ":", "widgettoclick", "=", "widget", "clickpos", "=", "pid", "# create a new event for the editor widget.", "e", "=", "QtGui", ".", "QMouseEvent", "(", "event", ".", "type", "(", ")", ",", "clickpos", ",", "event", ".", "button", "(", ")", ",", "event", ".", "buttons", "(", ")", ",", "event", ".", "modifiers", "(", ")", ")", "# before we send, make sure, we cannot recurse", "self", ".", "__recursing", "=", "True", "try", ":", "r", "=", "QtGui", ".", "QApplication", ".", "sendEvent", "(", "widgettoclick", ",", "e", ")", "finally", ":", "self", ".", "__recursing", "=", "False", "# out of the recursion. now we can accept click events again", "return", "r" ]
Propagate the given Mouse event to the widgetdelegate Enter edit mode, get the editor widget and issue an event on that widget. :param event: the mouse event :type event: :class:`QtGui.QMouseEvent` :param eventhandler: the eventhandler to use. E.g. ``"mousePressEvent"`` :type eventhandler: str :returns: None :rtype: None :raises: None
[ "Propagate", "the", "given", "Mouse", "event", "to", "the", "widgetdelegate" ]
bac2280ca49940355270e4b69400ce9976ab2e6f
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/gui/widgetdelegate.py#L393-L459
238,736
JukeboxPipeline/jukebox-core
src/jukeboxcore/gui/widgetdelegate.py
WD_TreeView.get_total_indentation
def get_total_indentation(self, index): """Get the indentation for the given index :param index: the index to query :type index: :class:`QtCore.ModelIndex` :returns: the number of parents :rtype: int :raises: None """ n = 0 while index.isValid(): n += 1 index = index.parent() return n * self.indentation()
python
def get_total_indentation(self, index): """Get the indentation for the given index :param index: the index to query :type index: :class:`QtCore.ModelIndex` :returns: the number of parents :rtype: int :raises: None """ n = 0 while index.isValid(): n += 1 index = index.parent() return n * self.indentation()
[ "def", "get_total_indentation", "(", "self", ",", "index", ")", ":", "n", "=", "0", "while", "index", ".", "isValid", "(", ")", ":", "n", "+=", "1", "index", "=", "index", ".", "parent", "(", ")", "return", "n", "*", "self", ".", "indentation", "(", ")" ]
Get the indentation for the given index :param index: the index to query :type index: :class:`QtCore.ModelIndex` :returns: the number of parents :rtype: int :raises: None
[ "Get", "the", "indentation", "for", "the", "given", "index" ]
bac2280ca49940355270e4b69400ce9976ab2e6f
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/gui/widgetdelegate.py#L534-L547
238,737
majerteam/sqla_inspect
sqla_inspect/csv.py
CsvWriter.render
def render(self, f_buf=None): """ Write to the dest buffer :param obj f_buf: A file buffer supporting the write and seek methods """ if f_buf is None: f_buf = StringIO.StringIO() headers = getattr(self, 'headers', ()) keys = [ force_encoding(header['label'], self.encoding) for header in headers ] extra_headers = getattr(self, 'extra_headers', ()) keys.extend([ force_encoding(header['label'], self.encoding) for header in extra_headers ]) outfile = csv.DictWriter( f_buf, keys, extrasaction='ignore', delimiter=self.delimiter, quotechar=self.quotechar, quoting=csv.QUOTE_ALL, ) outfile.writeheader() _datas = getattr(self, '_datas', ()) outfile.writerows(_datas) f_buf.seek(0) return f_buf
python
def render(self, f_buf=None): """ Write to the dest buffer :param obj f_buf: A file buffer supporting the write and seek methods """ if f_buf is None: f_buf = StringIO.StringIO() headers = getattr(self, 'headers', ()) keys = [ force_encoding(header['label'], self.encoding) for header in headers ] extra_headers = getattr(self, 'extra_headers', ()) keys.extend([ force_encoding(header['label'], self.encoding) for header in extra_headers ]) outfile = csv.DictWriter( f_buf, keys, extrasaction='ignore', delimiter=self.delimiter, quotechar=self.quotechar, quoting=csv.QUOTE_ALL, ) outfile.writeheader() _datas = getattr(self, '_datas', ()) outfile.writerows(_datas) f_buf.seek(0) return f_buf
[ "def", "render", "(", "self", ",", "f_buf", "=", "None", ")", ":", "if", "f_buf", "is", "None", ":", "f_buf", "=", "StringIO", ".", "StringIO", "(", ")", "headers", "=", "getattr", "(", "self", ",", "'headers'", ",", "(", ")", ")", "keys", "=", "[", "force_encoding", "(", "header", "[", "'label'", "]", ",", "self", ".", "encoding", ")", "for", "header", "in", "headers", "]", "extra_headers", "=", "getattr", "(", "self", ",", "'extra_headers'", ",", "(", ")", ")", "keys", ".", "extend", "(", "[", "force_encoding", "(", "header", "[", "'label'", "]", ",", "self", ".", "encoding", ")", "for", "header", "in", "extra_headers", "]", ")", "outfile", "=", "csv", ".", "DictWriter", "(", "f_buf", ",", "keys", ",", "extrasaction", "=", "'ignore'", ",", "delimiter", "=", "self", ".", "delimiter", ",", "quotechar", "=", "self", ".", "quotechar", ",", "quoting", "=", "csv", ".", "QUOTE_ALL", ",", ")", "outfile", ".", "writeheader", "(", ")", "_datas", "=", "getattr", "(", "self", ",", "'_datas'", ",", "(", ")", ")", "outfile", ".", "writerows", "(", "_datas", ")", "f_buf", ".", "seek", "(", "0", ")", "return", "f_buf" ]
Write to the dest buffer :param obj f_buf: A file buffer supporting the write and seek methods
[ "Write", "to", "the", "dest", "buffer" ]
67edb5541e6a56b0a657d3774d1e19c1110cd402
https://github.com/majerteam/sqla_inspect/blob/67edb5541e6a56b0a657d3774d1e19c1110cd402/sqla_inspect/csv.py#L47-L82
238,738
majerteam/sqla_inspect
sqla_inspect/csv.py
CsvWriter.format_row
def format_row(self, row): """ Format the row to fit our export switch the key used to store it in the dict since csv writer is expecting dict with keys matching the headers' names we switch the name the attributes fo the row are stored using labels instead of names """ res_dict = {} headers = getattr(self, 'headers', []) extra_headers = getattr(self, 'extra_headers', []) for header in tuple(headers) + tuple(extra_headers): name, label = header['name'], header['label'] val = row.get(name) if val is None: continue label = force_encoding(label, self.encoding) if hasattr(self, "format_%s" % name): val = getattr(self, "format_%s" % name)(val) res_dict[label] = force_encoding(val, self.encoding) return res_dict
python
def format_row(self, row): """ Format the row to fit our export switch the key used to store it in the dict since csv writer is expecting dict with keys matching the headers' names we switch the name the attributes fo the row are stored using labels instead of names """ res_dict = {} headers = getattr(self, 'headers', []) extra_headers = getattr(self, 'extra_headers', []) for header in tuple(headers) + tuple(extra_headers): name, label = header['name'], header['label'] val = row.get(name) if val is None: continue label = force_encoding(label, self.encoding) if hasattr(self, "format_%s" % name): val = getattr(self, "format_%s" % name)(val) res_dict[label] = force_encoding(val, self.encoding) return res_dict
[ "def", "format_row", "(", "self", ",", "row", ")", ":", "res_dict", "=", "{", "}", "headers", "=", "getattr", "(", "self", ",", "'headers'", ",", "[", "]", ")", "extra_headers", "=", "getattr", "(", "self", ",", "'extra_headers'", ",", "[", "]", ")", "for", "header", "in", "tuple", "(", "headers", ")", "+", "tuple", "(", "extra_headers", ")", ":", "name", ",", "label", "=", "header", "[", "'name'", "]", ",", "header", "[", "'label'", "]", "val", "=", "row", ".", "get", "(", "name", ")", "if", "val", "is", "None", ":", "continue", "label", "=", "force_encoding", "(", "label", ",", "self", ".", "encoding", ")", "if", "hasattr", "(", "self", ",", "\"format_%s\"", "%", "name", ")", ":", "val", "=", "getattr", "(", "self", ",", "\"format_%s\"", "%", "name", ")", "(", "val", ")", "res_dict", "[", "label", "]", "=", "force_encoding", "(", "val", ",", "self", ".", "encoding", ")", "return", "res_dict" ]
Format the row to fit our export switch the key used to store it in the dict since csv writer is expecting dict with keys matching the headers' names we switch the name the attributes fo the row are stored using labels instead of names
[ "Format", "the", "row", "to", "fit", "our", "export", "switch", "the", "key", "used", "to", "store", "it", "in", "the", "dict" ]
67edb5541e6a56b0a657d3774d1e19c1110cd402
https://github.com/majerteam/sqla_inspect/blob/67edb5541e6a56b0a657d3774d1e19c1110cd402/sqla_inspect/csv.py#L84-L106
238,739
majerteam/sqla_inspect
sqla_inspect/csv.py
CsvWriter.set_headers
def set_headers(self, headers): """ Set the headers of our csv writer :param list headers: list of dict with label and name key (label is mandatory : used for the export) """ self.headers = [] if 'order' in self.options: for element in self.options['order']: for header in headers: if header['key'] == element: self.headers.append(header) break else: self.headers = headers
python
def set_headers(self, headers): """ Set the headers of our csv writer :param list headers: list of dict with label and name key (label is mandatory : used for the export) """ self.headers = [] if 'order' in self.options: for element in self.options['order']: for header in headers: if header['key'] == element: self.headers.append(header) break else: self.headers = headers
[ "def", "set_headers", "(", "self", ",", "headers", ")", ":", "self", ".", "headers", "=", "[", "]", "if", "'order'", "in", "self", ".", "options", ":", "for", "element", "in", "self", ".", "options", "[", "'order'", "]", ":", "for", "header", "in", "headers", ":", "if", "header", "[", "'key'", "]", "==", "element", ":", "self", ".", "headers", ".", "append", "(", "header", ")", "break", "else", ":", "self", ".", "headers", "=", "headers" ]
Set the headers of our csv writer :param list headers: list of dict with label and name key (label is mandatory : used for the export)
[ "Set", "the", "headers", "of", "our", "csv", "writer" ]
67edb5541e6a56b0a657d3774d1e19c1110cd402
https://github.com/majerteam/sqla_inspect/blob/67edb5541e6a56b0a657d3774d1e19c1110cd402/sqla_inspect/csv.py#L108-L123
238,740
jkwill87/teletype
teletype/components/config.py
set_style
def set_style(primary=None, secondary=None): """ Sets primary and secondary component styles. """ global _primary_style, _secondary_style if primary: _primary_style = primary if secondary: _secondary_style = secondary
python
def set_style(primary=None, secondary=None): """ Sets primary and secondary component styles. """ global _primary_style, _secondary_style if primary: _primary_style = primary if secondary: _secondary_style = secondary
[ "def", "set_style", "(", "primary", "=", "None", ",", "secondary", "=", "None", ")", ":", "global", "_primary_style", ",", "_secondary_style", "if", "primary", ":", "_primary_style", "=", "primary", "if", "secondary", ":", "_secondary_style", "=", "secondary" ]
Sets primary and secondary component styles.
[ "Sets", "primary", "and", "secondary", "component", "styles", "." ]
8ba95c56dcb5e4d7f6ae155eb6cdabfdfaf346cf
https://github.com/jkwill87/teletype/blob/8ba95c56dcb5e4d7f6ae155eb6cdabfdfaf346cf/teletype/components/config.py#L30-L37
238,741
jkwill87/teletype
teletype/components/config.py
set_char
def set_char(key, value): """ Updates charters used to render components. """ global _chars category = _get_char_category(key) if not category: raise KeyError _chars[category][key] = value
python
def set_char(key, value): """ Updates charters used to render components. """ global _chars category = _get_char_category(key) if not category: raise KeyError _chars[category][key] = value
[ "def", "set_char", "(", "key", ",", "value", ")", ":", "global", "_chars", "category", "=", "_get_char_category", "(", "key", ")", "if", "not", "category", ":", "raise", "KeyError", "_chars", "[", "category", "]", "[", "key", "]", "=", "value" ]
Updates charters used to render components.
[ "Updates", "charters", "used", "to", "render", "components", "." ]
8ba95c56dcb5e4d7f6ae155eb6cdabfdfaf346cf
https://github.com/jkwill87/teletype/blob/8ba95c56dcb5e4d7f6ae155eb6cdabfdfaf346cf/teletype/components/config.py#L40-L47
238,742
jkwill87/teletype
teletype/components/config.py
ascii_mode
def ascii_mode(enabled=True): """ Disables color and switches to an ASCII character set if True. """ global _backups, _chars, _primary_style, _secondary_style, _ascii_mode if not (enabled or _backups) or (enabled and _ascii_mode): return if enabled: _backups = _chars.copy(), _primary_style, _secondary_style _chars = { "primary": {"selected": "*", "block": "#"}, "secondary": {"arrow": ">", "left-edge": "|", "right-edge": "|"}, "plain": {"unselected": "."}, } _primary_style = () _secondary_style = () else: _chars, _primary_style, _secondary_style = _backups _ascii_mode = enabled
python
def ascii_mode(enabled=True): """ Disables color and switches to an ASCII character set if True. """ global _backups, _chars, _primary_style, _secondary_style, _ascii_mode if not (enabled or _backups) or (enabled and _ascii_mode): return if enabled: _backups = _chars.copy(), _primary_style, _secondary_style _chars = { "primary": {"selected": "*", "block": "#"}, "secondary": {"arrow": ">", "left-edge": "|", "right-edge": "|"}, "plain": {"unselected": "."}, } _primary_style = () _secondary_style = () else: _chars, _primary_style, _secondary_style = _backups _ascii_mode = enabled
[ "def", "ascii_mode", "(", "enabled", "=", "True", ")", ":", "global", "_backups", ",", "_chars", ",", "_primary_style", ",", "_secondary_style", ",", "_ascii_mode", "if", "not", "(", "enabled", "or", "_backups", ")", "or", "(", "enabled", "and", "_ascii_mode", ")", ":", "return", "if", "enabled", ":", "_backups", "=", "_chars", ".", "copy", "(", ")", ",", "_primary_style", ",", "_secondary_style", "_chars", "=", "{", "\"primary\"", ":", "{", "\"selected\"", ":", "\"*\"", ",", "\"block\"", ":", "\"#\"", "}", ",", "\"secondary\"", ":", "{", "\"arrow\"", ":", "\">\"", ",", "\"left-edge\"", ":", "\"|\"", ",", "\"right-edge\"", ":", "\"|\"", "}", ",", "\"plain\"", ":", "{", "\"unselected\"", ":", "\".\"", "}", ",", "}", "_primary_style", "=", "(", ")", "_secondary_style", "=", "(", ")", "else", ":", "_chars", ",", "_primary_style", ",", "_secondary_style", "=", "_backups", "_ascii_mode", "=", "enabled" ]
Disables color and switches to an ASCII character set if True.
[ "Disables", "color", "and", "switches", "to", "an", "ASCII", "character", "set", "if", "True", "." ]
8ba95c56dcb5e4d7f6ae155eb6cdabfdfaf346cf
https://github.com/jkwill87/teletype/blob/8ba95c56dcb5e4d7f6ae155eb6cdabfdfaf346cf/teletype/components/config.py#L50-L67
238,743
Brazelton-Lab/bio_utils
bio_utils/verifiers/sam.py
sam_verifier
def sam_verifier(entries, line=None): """Raises error if invalid SAM format detected Args: entries (list): A list of SamEntry instances line (int): Line number of first entry Raises: FormatError: Error when SAM format incorrect with descriptive message """ regex = r'^[!-?A-~]{1,255}\t' \ + r'([0-9]{1,4}|[0-5][0-9]{4}|' \ + r'[0-9]{1,4}|[1-5][0-9]{4}|' \ + r'6[0-4][0-9]{3}|65[0-4][0-9]{2}|' \ + r'655[0-2][0-9]|6553[0-7])\t' \ + r'\*|[!-()+-<>-~][!-~]*\t' \ + r'([0-9]{1,9}|1[0-9]{9}|2(0[0-9]{8}|' \ + r'1([0-3][0-9]{7}|4([0-6][0-9]{6}|' \ + r'7([0-3][0-9]{5}|4([0-7][0-9]{4}|' \ + r'8([0-2][0-9]{3}|3([0-5][0-9]{2}|' \ + r'6([0-3][0-9]|4[0-7])))))))))\t' \ + r'([0-9]{1,2}|1[0-9]{2}|' \ + r'2[0-4][0-9]|25[0-5])\t' \ + r'\*|([0-9]+[MIDNSHPX=])+\t' \ + r'\*|=|[!-()+-<>-~][!-~]*\t' \ + r'([0-9]{1,9}|1[0-9]{9}|2(0[0-9]{8}|' \ + r'1([0-3][0-9]{7}|4([0-6][0-9]{6}|' \ + r'7([0-3][0-9]{5}|4([0-7][0-9]{4}|' \ + r'8([0-2][0-9]{3}|3([0-5][0-9]{2}|' \ + r'6([0-3][0-9]|4[0-7])))))))))\t' \ + r'-?([0-9]{1,9}|1[0-9]{9}|2(0[0-9]{8}|' \ + r'1([0-3][0-9]{7}|4([0-6][0-9]{6}|' \ + r'7([0-3][0-9]{5}|4([0-7][0-9]{4}|' \ + r'8([0-2][0-9]{3}|3([0-5][0-9]{2}|' \ + r'6([0-3][0-9]|4[0-7])))))))))\t' \ + r'\*|[A-Za-z=.]+\t' \ + r'[!-~]+{0}$'.format(os.linesep) delimiter = r'\t' for entry in entries: try: entry_verifier([entry.write()], regex, delimiter) except FormatError as error: # Format info on what entry error came from if line: intro = 'Line {0}'.format(str(line)) elif error.part == 0: intro = 'An entry with reference {0}'.format(entry.rname) else: intro = 'An entry with query {0}'.format(entry.qname) # Generate error if error.part == 0: if len(entry.qname) == 0: msg = '{0} has no query name'.format(intro) elif len(entry.qname) > 255: msg = '{0} query name must be less than 255 ' \ 'characters'.format(intro) else: msg = '{0} query name contains characters not in ' \ '[!-?A-~]'.format(intro) elif error.part == 1: msg = '{0} flag not in range [0-(2^31-1)]'.format(intro) elif error.part == 2: if len(entry.rname) == 0: msg = '{0} has no reference name'.format(intro) else: msg = '{0} reference name has characters not in ' \ '[!-()+-<>-~][!-~]'.format(intro) elif error.part == 3: msg = '{0} leftmost position not in range ' \ '[0-(2^31-1)]'.format(intro) elif error.part == 4: msg = '{0} mapping quality not in range ' \ '[0-(2^8-1)]'.format(intro) elif error.part == 5: msg = '{0} CIGAR string has characters not in ' \ '[0-9MIDNSHPX=]'.format(intro) elif error.part == 6: msg = '{0} mate read name has characters not in ' \ '[!-()+-<>-~][!-~]'.format(intro) elif error.part == 7: msg = '{0} mate read position not in range ' \ '[0-(2^31-1)]'.format(intro) elif error.part == 8: msg = '{0} template length not in range ' \ '[(-2^31+1)-(2^31-1)]'.format(intro) elif error.part == 9: msg = '{0} sequence has characters not in ' \ '[A-Za-z=.]'.format(intro) elif error.part == 10: msg = '{0} quality scores has characters not in ' \ '[!-~]'.format(intro) else: msg = '{0}: Unknown Error: Likely a Bug'.format(intro) raise FormatError(message=msg) if line: line += 1
python
def sam_verifier(entries, line=None): """Raises error if invalid SAM format detected Args: entries (list): A list of SamEntry instances line (int): Line number of first entry Raises: FormatError: Error when SAM format incorrect with descriptive message """ regex = r'^[!-?A-~]{1,255}\t' \ + r'([0-9]{1,4}|[0-5][0-9]{4}|' \ + r'[0-9]{1,4}|[1-5][0-9]{4}|' \ + r'6[0-4][0-9]{3}|65[0-4][0-9]{2}|' \ + r'655[0-2][0-9]|6553[0-7])\t' \ + r'\*|[!-()+-<>-~][!-~]*\t' \ + r'([0-9]{1,9}|1[0-9]{9}|2(0[0-9]{8}|' \ + r'1([0-3][0-9]{7}|4([0-6][0-9]{6}|' \ + r'7([0-3][0-9]{5}|4([0-7][0-9]{4}|' \ + r'8([0-2][0-9]{3}|3([0-5][0-9]{2}|' \ + r'6([0-3][0-9]|4[0-7])))))))))\t' \ + r'([0-9]{1,2}|1[0-9]{2}|' \ + r'2[0-4][0-9]|25[0-5])\t' \ + r'\*|([0-9]+[MIDNSHPX=])+\t' \ + r'\*|=|[!-()+-<>-~][!-~]*\t' \ + r'([0-9]{1,9}|1[0-9]{9}|2(0[0-9]{8}|' \ + r'1([0-3][0-9]{7}|4([0-6][0-9]{6}|' \ + r'7([0-3][0-9]{5}|4([0-7][0-9]{4}|' \ + r'8([0-2][0-9]{3}|3([0-5][0-9]{2}|' \ + r'6([0-3][0-9]|4[0-7])))))))))\t' \ + r'-?([0-9]{1,9}|1[0-9]{9}|2(0[0-9]{8}|' \ + r'1([0-3][0-9]{7}|4([0-6][0-9]{6}|' \ + r'7([0-3][0-9]{5}|4([0-7][0-9]{4}|' \ + r'8([0-2][0-9]{3}|3([0-5][0-9]{2}|' \ + r'6([0-3][0-9]|4[0-7])))))))))\t' \ + r'\*|[A-Za-z=.]+\t' \ + r'[!-~]+{0}$'.format(os.linesep) delimiter = r'\t' for entry in entries: try: entry_verifier([entry.write()], regex, delimiter) except FormatError as error: # Format info on what entry error came from if line: intro = 'Line {0}'.format(str(line)) elif error.part == 0: intro = 'An entry with reference {0}'.format(entry.rname) else: intro = 'An entry with query {0}'.format(entry.qname) # Generate error if error.part == 0: if len(entry.qname) == 0: msg = '{0} has no query name'.format(intro) elif len(entry.qname) > 255: msg = '{0} query name must be less than 255 ' \ 'characters'.format(intro) else: msg = '{0} query name contains characters not in ' \ '[!-?A-~]'.format(intro) elif error.part == 1: msg = '{0} flag not in range [0-(2^31-1)]'.format(intro) elif error.part == 2: if len(entry.rname) == 0: msg = '{0} has no reference name'.format(intro) else: msg = '{0} reference name has characters not in ' \ '[!-()+-<>-~][!-~]'.format(intro) elif error.part == 3: msg = '{0} leftmost position not in range ' \ '[0-(2^31-1)]'.format(intro) elif error.part == 4: msg = '{0} mapping quality not in range ' \ '[0-(2^8-1)]'.format(intro) elif error.part == 5: msg = '{0} CIGAR string has characters not in ' \ '[0-9MIDNSHPX=]'.format(intro) elif error.part == 6: msg = '{0} mate read name has characters not in ' \ '[!-()+-<>-~][!-~]'.format(intro) elif error.part == 7: msg = '{0} mate read position not in range ' \ '[0-(2^31-1)]'.format(intro) elif error.part == 8: msg = '{0} template length not in range ' \ '[(-2^31+1)-(2^31-1)]'.format(intro) elif error.part == 9: msg = '{0} sequence has characters not in ' \ '[A-Za-z=.]'.format(intro) elif error.part == 10: msg = '{0} quality scores has characters not in ' \ '[!-~]'.format(intro) else: msg = '{0}: Unknown Error: Likely a Bug'.format(intro) raise FormatError(message=msg) if line: line += 1
[ "def", "sam_verifier", "(", "entries", ",", "line", "=", "None", ")", ":", "regex", "=", "r'^[!-?A-~]{1,255}\\t'", "+", "r'([0-9]{1,4}|[0-5][0-9]{4}|'", "+", "r'[0-9]{1,4}|[1-5][0-9]{4}|'", "+", "r'6[0-4][0-9]{3}|65[0-4][0-9]{2}|'", "+", "r'655[0-2][0-9]|6553[0-7])\\t'", "+", "r'\\*|[!-()+-<>-~][!-~]*\\t'", "+", "r'([0-9]{1,9}|1[0-9]{9}|2(0[0-9]{8}|'", "+", "r'1([0-3][0-9]{7}|4([0-6][0-9]{6}|'", "+", "r'7([0-3][0-9]{5}|4([0-7][0-9]{4}|'", "+", "r'8([0-2][0-9]{3}|3([0-5][0-9]{2}|'", "+", "r'6([0-3][0-9]|4[0-7])))))))))\\t'", "+", "r'([0-9]{1,2}|1[0-9]{2}|'", "+", "r'2[0-4][0-9]|25[0-5])\\t'", "+", "r'\\*|([0-9]+[MIDNSHPX=])+\\t'", "+", "r'\\*|=|[!-()+-<>-~][!-~]*\\t'", "+", "r'([0-9]{1,9}|1[0-9]{9}|2(0[0-9]{8}|'", "+", "r'1([0-3][0-9]{7}|4([0-6][0-9]{6}|'", "+", "r'7([0-3][0-9]{5}|4([0-7][0-9]{4}|'", "+", "r'8([0-2][0-9]{3}|3([0-5][0-9]{2}|'", "+", "r'6([0-3][0-9]|4[0-7])))))))))\\t'", "+", "r'-?([0-9]{1,9}|1[0-9]{9}|2(0[0-9]{8}|'", "+", "r'1([0-3][0-9]{7}|4([0-6][0-9]{6}|'", "+", "r'7([0-3][0-9]{5}|4([0-7][0-9]{4}|'", "+", "r'8([0-2][0-9]{3}|3([0-5][0-9]{2}|'", "+", "r'6([0-3][0-9]|4[0-7])))))))))\\t'", "+", "r'\\*|[A-Za-z=.]+\\t'", "+", "r'[!-~]+{0}$'", ".", "format", "(", "os", ".", "linesep", ")", "delimiter", "=", "r'\\t'", "for", "entry", "in", "entries", ":", "try", ":", "entry_verifier", "(", "[", "entry", ".", "write", "(", ")", "]", ",", "regex", ",", "delimiter", ")", "except", "FormatError", "as", "error", ":", "# Format info on what entry error came from", "if", "line", ":", "intro", "=", "'Line {0}'", ".", "format", "(", "str", "(", "line", ")", ")", "elif", "error", ".", "part", "==", "0", ":", "intro", "=", "'An entry with reference {0}'", ".", "format", "(", "entry", ".", "rname", ")", "else", ":", "intro", "=", "'An entry with query {0}'", ".", "format", "(", "entry", ".", "qname", ")", "# Generate error", "if", "error", ".", "part", "==", "0", ":", "if", "len", "(", "entry", ".", "qname", ")", "==", "0", ":", "msg", "=", "'{0} has no query name'", ".", "format", "(", "intro", ")", "elif", "len", "(", "entry", ".", "qname", ")", ">", "255", ":", "msg", "=", "'{0} query name must be less than 255 '", "'characters'", ".", "format", "(", "intro", ")", "else", ":", "msg", "=", "'{0} query name contains characters not in '", "'[!-?A-~]'", ".", "format", "(", "intro", ")", "elif", "error", ".", "part", "==", "1", ":", "msg", "=", "'{0} flag not in range [0-(2^31-1)]'", ".", "format", "(", "intro", ")", "elif", "error", ".", "part", "==", "2", ":", "if", "len", "(", "entry", ".", "rname", ")", "==", "0", ":", "msg", "=", "'{0} has no reference name'", ".", "format", "(", "intro", ")", "else", ":", "msg", "=", "'{0} reference name has characters not in '", "'[!-()+-<>-~][!-~]'", ".", "format", "(", "intro", ")", "elif", "error", ".", "part", "==", "3", ":", "msg", "=", "'{0} leftmost position not in range '", "'[0-(2^31-1)]'", ".", "format", "(", "intro", ")", "elif", "error", ".", "part", "==", "4", ":", "msg", "=", "'{0} mapping quality not in range '", "'[0-(2^8-1)]'", ".", "format", "(", "intro", ")", "elif", "error", ".", "part", "==", "5", ":", "msg", "=", "'{0} CIGAR string has characters not in '", "'[0-9MIDNSHPX=]'", ".", "format", "(", "intro", ")", "elif", "error", ".", "part", "==", "6", ":", "msg", "=", "'{0} mate read name has characters not in '", "'[!-()+-<>-~][!-~]'", ".", "format", "(", "intro", ")", "elif", "error", ".", "part", "==", "7", ":", "msg", "=", "'{0} mate read position not in range '", "'[0-(2^31-1)]'", ".", "format", "(", "intro", ")", "elif", "error", ".", "part", "==", "8", ":", "msg", "=", "'{0} template length not in range '", "'[(-2^31+1)-(2^31-1)]'", ".", "format", "(", "intro", ")", "elif", "error", ".", "part", "==", "9", ":", "msg", "=", "'{0} sequence has characters not in '", "'[A-Za-z=.]'", ".", "format", "(", "intro", ")", "elif", "error", ".", "part", "==", "10", ":", "msg", "=", "'{0} quality scores has characters not in '", "'[!-~]'", ".", "format", "(", "intro", ")", "else", ":", "msg", "=", "'{0}: Unknown Error: Likely a Bug'", ".", "format", "(", "intro", ")", "raise", "FormatError", "(", "message", "=", "msg", ")", "if", "line", ":", "line", "+=", "1" ]
Raises error if invalid SAM format detected Args: entries (list): A list of SamEntry instances line (int): Line number of first entry Raises: FormatError: Error when SAM format incorrect with descriptive message
[ "Raises", "error", "if", "invalid", "SAM", "format", "detected" ]
5a7ddf13ee0bf4baaaeb6b2b99e01bf74aa132b7
https://github.com/Brazelton-Lab/bio_utils/blob/5a7ddf13ee0bf4baaaeb6b2b99e01bf74aa132b7/bio_utils/verifiers/sam.py#L45-L145
238,744
baguette-io/baguette-messaging
farine/amqp/publisher.py
Publisher.send
def send(self, message, *args, **kwargs): """ Send the the `message` to the broker. :param message: The message to send. Its type depends on the serializer used. :type message: object :rtype: None """ routing_keys = kwargs.get('routing_key') or self.routing_key routing_keys = [routing_keys] if isinstance(routing_keys, basestring) else routing_keys correlation_id = kwargs.get('correlation_id', None) reply_to = kwargs.get('reply_to', None) declare=[self.exchange] + kwargs.get('declare', []) conn = self.get_connection() with connections[conn].acquire(block=True) as connection: self.exchange.maybe_bind(connection) #reply_to.maybe_bind(connection) #reply_to.declare(True) with producers[connection].acquire(block=True) as producer: for routing_key in routing_keys: LOGGER.info('Send message %s to exchange %s with routing_key %s reply_to %s correlation_id %s', message, self.exchange.name, routing_key, reply_to, correlation_id) producer.publish( message, exchange=self.exchange, declare=declare, serializer=self.settings['serializer'], routing_key=routing_key, correlation_id=correlation_id, retry=self.settings['retry'], delivery_mode=self.settings['delivery_mode'], reply_to=reply_to, retry_policy=self.settings['retry_policy'])
python
def send(self, message, *args, **kwargs): """ Send the the `message` to the broker. :param message: The message to send. Its type depends on the serializer used. :type message: object :rtype: None """ routing_keys = kwargs.get('routing_key') or self.routing_key routing_keys = [routing_keys] if isinstance(routing_keys, basestring) else routing_keys correlation_id = kwargs.get('correlation_id', None) reply_to = kwargs.get('reply_to', None) declare=[self.exchange] + kwargs.get('declare', []) conn = self.get_connection() with connections[conn].acquire(block=True) as connection: self.exchange.maybe_bind(connection) #reply_to.maybe_bind(connection) #reply_to.declare(True) with producers[connection].acquire(block=True) as producer: for routing_key in routing_keys: LOGGER.info('Send message %s to exchange %s with routing_key %s reply_to %s correlation_id %s', message, self.exchange.name, routing_key, reply_to, correlation_id) producer.publish( message, exchange=self.exchange, declare=declare, serializer=self.settings['serializer'], routing_key=routing_key, correlation_id=correlation_id, retry=self.settings['retry'], delivery_mode=self.settings['delivery_mode'], reply_to=reply_to, retry_policy=self.settings['retry_policy'])
[ "def", "send", "(", "self", ",", "message", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "routing_keys", "=", "kwargs", ".", "get", "(", "'routing_key'", ")", "or", "self", ".", "routing_key", "routing_keys", "=", "[", "routing_keys", "]", "if", "isinstance", "(", "routing_keys", ",", "basestring", ")", "else", "routing_keys", "correlation_id", "=", "kwargs", ".", "get", "(", "'correlation_id'", ",", "None", ")", "reply_to", "=", "kwargs", ".", "get", "(", "'reply_to'", ",", "None", ")", "declare", "=", "[", "self", ".", "exchange", "]", "+", "kwargs", ".", "get", "(", "'declare'", ",", "[", "]", ")", "conn", "=", "self", ".", "get_connection", "(", ")", "with", "connections", "[", "conn", "]", ".", "acquire", "(", "block", "=", "True", ")", "as", "connection", ":", "self", ".", "exchange", ".", "maybe_bind", "(", "connection", ")", "#reply_to.maybe_bind(connection)", "#reply_to.declare(True)", "with", "producers", "[", "connection", "]", ".", "acquire", "(", "block", "=", "True", ")", "as", "producer", ":", "for", "routing_key", "in", "routing_keys", ":", "LOGGER", ".", "info", "(", "'Send message %s to exchange %s with routing_key %s reply_to %s correlation_id %s'", ",", "message", ",", "self", ".", "exchange", ".", "name", ",", "routing_key", ",", "reply_to", ",", "correlation_id", ")", "producer", ".", "publish", "(", "message", ",", "exchange", "=", "self", ".", "exchange", ",", "declare", "=", "declare", ",", "serializer", "=", "self", ".", "settings", "[", "'serializer'", "]", ",", "routing_key", "=", "routing_key", ",", "correlation_id", "=", "correlation_id", ",", "retry", "=", "self", ".", "settings", "[", "'retry'", "]", ",", "delivery_mode", "=", "self", ".", "settings", "[", "'delivery_mode'", "]", ",", "reply_to", "=", "reply_to", ",", "retry_policy", "=", "self", ".", "settings", "[", "'retry_policy'", "]", ")" ]
Send the the `message` to the broker. :param message: The message to send. Its type depends on the serializer used. :type message: object :rtype: None
[ "Send", "the", "the", "message", "to", "the", "broker", "." ]
8d1c4707ea7eace8617fed2d97df2fcc9d0cdee1
https://github.com/baguette-io/baguette-messaging/blob/8d1c4707ea7eace8617fed2d97df2fcc9d0cdee1/farine/amqp/publisher.py#L47-L79
238,745
borzecki/q
quicksearch/cli.py
exit_with_error
def exit_with_error(message): """ Display formatted error message and exit call """ click.secho(message, err=True, bg='red', fg='white') sys.exit(0)
python
def exit_with_error(message): """ Display formatted error message and exit call """ click.secho(message, err=True, bg='red', fg='white') sys.exit(0)
[ "def", "exit_with_error", "(", "message", ")", ":", "click", ".", "secho", "(", "message", ",", "err", "=", "True", ",", "bg", "=", "'red'", ",", "fg", "=", "'white'", ")", "sys", ".", "exit", "(", "0", ")" ]
Display formatted error message and exit call
[ "Display", "formatted", "error", "message", "and", "exit", "call" ]
9d5c153fb12b353a73d6909599ad4b1e4e56304d
https://github.com/borzecki/q/blob/9d5c153fb12b353a73d6909599ad4b1e4e56304d/quicksearch/cli.py#L10-L13
238,746
borzecki/q
quicksearch/cli.py
main
def main(search_engine, search_option, list_engines, query): """Quick search command tool for your terminal""" engine_data = {} if list_engines: for name in engines: conf = get_config(name) optionals = filter(lambda e: e != 'default', conf.keys()) if optionals: click.echo('{command} -o {options}'.format( command=name.replace('.json', ''), options=', '.join(optionals))) else: click.echo(name.replace('.json', '')) sys.exit(0) for name in engines: if name.find(search_engine) == 0: engine_data = get_config(name) break # read from standard input if available if not sys.stdin.isatty(): query = sys.stdin.read() if not query: exit_with_error('Query parameter is missing.') if not engine_data: exit_with_error('Engine ``{0}`` not found'.format(search_engine)) if search_option not in engine_data: exit_with_error('Option ``{0}`` not available for engine ``{1}``'.\ format(search_option, search_engine)) query = u' '.join(query) if isinstance(query, tuple) else query engine_url = engine_data.get(search_option) url = engine_url.format(query).encode('utf-8') launch.open(url)
python
def main(search_engine, search_option, list_engines, query): """Quick search command tool for your terminal""" engine_data = {} if list_engines: for name in engines: conf = get_config(name) optionals = filter(lambda e: e != 'default', conf.keys()) if optionals: click.echo('{command} -o {options}'.format( command=name.replace('.json', ''), options=', '.join(optionals))) else: click.echo(name.replace('.json', '')) sys.exit(0) for name in engines: if name.find(search_engine) == 0: engine_data = get_config(name) break # read from standard input if available if not sys.stdin.isatty(): query = sys.stdin.read() if not query: exit_with_error('Query parameter is missing.') if not engine_data: exit_with_error('Engine ``{0}`` not found'.format(search_engine)) if search_option not in engine_data: exit_with_error('Option ``{0}`` not available for engine ``{1}``'.\ format(search_option, search_engine)) query = u' '.join(query) if isinstance(query, tuple) else query engine_url = engine_data.get(search_option) url = engine_url.format(query).encode('utf-8') launch.open(url)
[ "def", "main", "(", "search_engine", ",", "search_option", ",", "list_engines", ",", "query", ")", ":", "engine_data", "=", "{", "}", "if", "list_engines", ":", "for", "name", "in", "engines", ":", "conf", "=", "get_config", "(", "name", ")", "optionals", "=", "filter", "(", "lambda", "e", ":", "e", "!=", "'default'", ",", "conf", ".", "keys", "(", ")", ")", "if", "optionals", ":", "click", ".", "echo", "(", "'{command} -o {options}'", ".", "format", "(", "command", "=", "name", ".", "replace", "(", "'.json'", ",", "''", ")", ",", "options", "=", "', '", ".", "join", "(", "optionals", ")", ")", ")", "else", ":", "click", ".", "echo", "(", "name", ".", "replace", "(", "'.json'", ",", "''", ")", ")", "sys", ".", "exit", "(", "0", ")", "for", "name", "in", "engines", ":", "if", "name", ".", "find", "(", "search_engine", ")", "==", "0", ":", "engine_data", "=", "get_config", "(", "name", ")", "break", "# read from standard input if available", "if", "not", "sys", ".", "stdin", ".", "isatty", "(", ")", ":", "query", "=", "sys", ".", "stdin", ".", "read", "(", ")", "if", "not", "query", ":", "exit_with_error", "(", "'Query parameter is missing.'", ")", "if", "not", "engine_data", ":", "exit_with_error", "(", "'Engine ``{0}`` not found'", ".", "format", "(", "search_engine", ")", ")", "if", "search_option", "not", "in", "engine_data", ":", "exit_with_error", "(", "'Option ``{0}`` not available for engine ``{1}``'", ".", "format", "(", "search_option", ",", "search_engine", ")", ")", "query", "=", "u' '", ".", "join", "(", "query", ")", "if", "isinstance", "(", "query", ",", "tuple", ")", "else", "query", "engine_url", "=", "engine_data", ".", "get", "(", "search_option", ")", "url", "=", "engine_url", ".", "format", "(", "query", ")", ".", "encode", "(", "'utf-8'", ")", "launch", ".", "open", "(", "url", ")" ]
Quick search command tool for your terminal
[ "Quick", "search", "command", "tool", "for", "your", "terminal" ]
9d5c153fb12b353a73d6909599ad4b1e4e56304d
https://github.com/borzecki/q/blob/9d5c153fb12b353a73d6909599ad4b1e4e56304d/quicksearch/cli.py#L21-L59
238,747
rosenbrockc/ci
pyci/scripts/ci.py
_load_db
def _load_db(): """Deserializes the script database from JSON.""" from os import path from pyci.utility import get_json global datapath, db datapath = path.abspath(path.expanduser(settings.datafile)) vms("Deserializing DB from {}".format(datapath)) db = get_json(datapath, {"installed": [], "enabled": True, "cron": False})
python
def _load_db(): """Deserializes the script database from JSON.""" from os import path from pyci.utility import get_json global datapath, db datapath = path.abspath(path.expanduser(settings.datafile)) vms("Deserializing DB from {}".format(datapath)) db = get_json(datapath, {"installed": [], "enabled": True, "cron": False})
[ "def", "_load_db", "(", ")", ":", "from", "os", "import", "path", "from", "pyci", ".", "utility", "import", "get_json", "global", "datapath", ",", "db", "datapath", "=", "path", ".", "abspath", "(", "path", ".", "expanduser", "(", "settings", ".", "datafile", ")", ")", "vms", "(", "\"Deserializing DB from {}\"", ".", "format", "(", "datapath", ")", ")", "db", "=", "get_json", "(", "datapath", ",", "{", "\"installed\"", ":", "[", "]", ",", "\"enabled\"", ":", "True", ",", "\"cron\"", ":", "False", "}", ")" ]
Deserializes the script database from JSON.
[ "Deserializes", "the", "script", "database", "from", "JSON", "." ]
4d5a60291424a83124d1d962d17fb4c7718cde2b
https://github.com/rosenbrockc/ci/blob/4d5a60291424a83124d1d962d17fb4c7718cde2b/pyci/scripts/ci.py#L115-L122
238,748
rosenbrockc/ci
pyci/scripts/ci.py
_save_db
def _save_db(): """Serializes the contents of the script db to JSON.""" from pyci.utility import json_serial import json vms("Serializing DB to JSON in {}".format(datapath)) with open(datapath, 'w') as f: json.dump(db, f, default=json_serial)
python
def _save_db(): """Serializes the contents of the script db to JSON.""" from pyci.utility import json_serial import json vms("Serializing DB to JSON in {}".format(datapath)) with open(datapath, 'w') as f: json.dump(db, f, default=json_serial)
[ "def", "_save_db", "(", ")", ":", "from", "pyci", ".", "utility", "import", "json_serial", "import", "json", "vms", "(", "\"Serializing DB to JSON in {}\"", ".", "format", "(", "datapath", ")", ")", "with", "open", "(", "datapath", ",", "'w'", ")", "as", "f", ":", "json", ".", "dump", "(", "db", ",", "f", ",", "default", "=", "json_serial", ")" ]
Serializes the contents of the script db to JSON.
[ "Serializes", "the", "contents", "of", "the", "script", "db", "to", "JSON", "." ]
4d5a60291424a83124d1d962d17fb4c7718cde2b
https://github.com/rosenbrockc/ci/blob/4d5a60291424a83124d1d962d17fb4c7718cde2b/pyci/scripts/ci.py#L124-L130
238,749
rosenbrockc/ci
pyci/scripts/ci.py
_check_virtualenv
def _check_virtualenv(): """Makes sure that the virtualenv specified in the global settings file actually exists. """ from os import waitpid from subprocess import Popen, PIPE penvs = Popen("source /usr/local/bin/virtualenvwrapper.sh; workon", shell=True, executable="/bin/bash", stdout=PIPE, stderr=PIPE) waitpid(penvs.pid, 0) envs = penvs.stdout.readlines() enverr = penvs.stderr.readlines() result = (settings.venv + '\n') in envs and len(enverr) == 0 vms("Find virtualenv: {}".format(' '.join(envs).replace('\n', ''))) vms("Find virtualenv | stderr: {}".format(' '.join(enverr))) if not result: info(envs) err("The virtualenv '{}' does not exist; can't use CI server.".format(settings.venv)) if len(enverr) > 0: map(err, enverr) return result
python
def _check_virtualenv(): """Makes sure that the virtualenv specified in the global settings file actually exists. """ from os import waitpid from subprocess import Popen, PIPE penvs = Popen("source /usr/local/bin/virtualenvwrapper.sh; workon", shell=True, executable="/bin/bash", stdout=PIPE, stderr=PIPE) waitpid(penvs.pid, 0) envs = penvs.stdout.readlines() enverr = penvs.stderr.readlines() result = (settings.venv + '\n') in envs and len(enverr) == 0 vms("Find virtualenv: {}".format(' '.join(envs).replace('\n', ''))) vms("Find virtualenv | stderr: {}".format(' '.join(enverr))) if not result: info(envs) err("The virtualenv '{}' does not exist; can't use CI server.".format(settings.venv)) if len(enverr) > 0: map(err, enverr) return result
[ "def", "_check_virtualenv", "(", ")", ":", "from", "os", "import", "waitpid", "from", "subprocess", "import", "Popen", ",", "PIPE", "penvs", "=", "Popen", "(", "\"source /usr/local/bin/virtualenvwrapper.sh; workon\"", ",", "shell", "=", "True", ",", "executable", "=", "\"/bin/bash\"", ",", "stdout", "=", "PIPE", ",", "stderr", "=", "PIPE", ")", "waitpid", "(", "penvs", ".", "pid", ",", "0", ")", "envs", "=", "penvs", ".", "stdout", ".", "readlines", "(", ")", "enverr", "=", "penvs", ".", "stderr", ".", "readlines", "(", ")", "result", "=", "(", "settings", ".", "venv", "+", "'\\n'", ")", "in", "envs", "and", "len", "(", "enverr", ")", "==", "0", "vms", "(", "\"Find virtualenv: {}\"", ".", "format", "(", "' '", ".", "join", "(", "envs", ")", ".", "replace", "(", "'\\n'", ",", "''", ")", ")", ")", "vms", "(", "\"Find virtualenv | stderr: {}\"", ".", "format", "(", "' '", ".", "join", "(", "enverr", ")", ")", ")", "if", "not", "result", ":", "info", "(", "envs", ")", "err", "(", "\"The virtualenv '{}' does not exist; can't use CI server.\"", ".", "format", "(", "settings", ".", "venv", ")", ")", "if", "len", "(", "enverr", ")", ">", "0", ":", "map", "(", "err", ",", "enverr", ")", "return", "result" ]
Makes sure that the virtualenv specified in the global settings file actually exists.
[ "Makes", "sure", "that", "the", "virtualenv", "specified", "in", "the", "global", "settings", "file", "actually", "exists", "." ]
4d5a60291424a83124d1d962d17fb4c7718cde2b
https://github.com/rosenbrockc/ci/blob/4d5a60291424a83124d1d962d17fb4c7718cde2b/pyci/scripts/ci.py#L137-L158
238,750
rosenbrockc/ci
pyci/scripts/ci.py
_check_global_settings
def _check_global_settings(): """Makes sure that the global settings environment variable and file exist for configuration. """ global settings if settings is not None: #We must have already loaded this and everything was okay! return True from os import getenv result = False if getenv("PYCI_XML") is None: err("The environment variable PYCI_XML for the global configuration " "has not been set.") else: from os import path fullpath = path.abspath(path.expanduser(getenv("PYCI_XML"))) if not path.isfile(fullpath): err("The file {} for global configuration does not exist.".format(fullpath)) else: from pyci.config import GlobalSettings settings = GlobalSettings() result = True return result
python
def _check_global_settings(): """Makes sure that the global settings environment variable and file exist for configuration. """ global settings if settings is not None: #We must have already loaded this and everything was okay! return True from os import getenv result = False if getenv("PYCI_XML") is None: err("The environment variable PYCI_XML for the global configuration " "has not been set.") else: from os import path fullpath = path.abspath(path.expanduser(getenv("PYCI_XML"))) if not path.isfile(fullpath): err("The file {} for global configuration does not exist.".format(fullpath)) else: from pyci.config import GlobalSettings settings = GlobalSettings() result = True return result
[ "def", "_check_global_settings", "(", ")", ":", "global", "settings", "if", "settings", "is", "not", "None", ":", "#We must have already loaded this and everything was okay!", "return", "True", "from", "os", "import", "getenv", "result", "=", "False", "if", "getenv", "(", "\"PYCI_XML\"", ")", "is", "None", ":", "err", "(", "\"The environment variable PYCI_XML for the global configuration \"", "\"has not been set.\"", ")", "else", ":", "from", "os", "import", "path", "fullpath", "=", "path", ".", "abspath", "(", "path", ".", "expanduser", "(", "getenv", "(", "\"PYCI_XML\"", ")", ")", ")", "if", "not", "path", ".", "isfile", "(", "fullpath", ")", ":", "err", "(", "\"The file {} for global configuration does not exist.\"", ".", "format", "(", "fullpath", ")", ")", "else", ":", "from", "pyci", ".", "config", "import", "GlobalSettings", "settings", "=", "GlobalSettings", "(", ")", "result", "=", "True", "return", "result" ]
Makes sure that the global settings environment variable and file exist for configuration.
[ "Makes", "sure", "that", "the", "global", "settings", "environment", "variable", "and", "file", "exist", "for", "configuration", "." ]
4d5a60291424a83124d1d962d17fb4c7718cde2b
https://github.com/rosenbrockc/ci/blob/4d5a60291424a83124d1d962d17fb4c7718cde2b/pyci/scripts/ci.py#L160-L185
238,751
rosenbrockc/ci
pyci/scripts/ci.py
_setup_crontab
def _setup_crontab(): """Sets up the crontab if it hasn't already been setup.""" from crontab import CronTab #Since CI works out of a virtualenv anyway, the `ci.py` script will be #installed in the bin already, so we can call it explicitly. command = '/bin/bash -c "source ~/.cron_profile; workon {}; ci.py -cron"'.format(settings.venv) user = _get_real_user() if args["nolive"]: vms("Skipping cron tab configuration because 'nolive' enabled.") return cron = CronTab(user=user) #We need to see if the cron has already been created for this command. existing = False possible = cron.find_comment("pyci_cron") if len(list(possible)) > 0: if args["rollback"]: vms("Removing {} from cron tab.".format(command)) cron.remove_all(command) cron.write() db["cron"] = False _save_db() else: existing = True if not existing and not args["rollback"]: job = cron.new(command=command, comment="pyci_cron") #Run the cron every minute of every hour every day. if args["cronfreq"] == 1: vms("New cron tab configured *minutely* for {}".format(command)) job.setall("* * * * *") else: vms("New cron tab configured every {} minutes for {}.".format(args["cronfreq"], command)) job.setall("*/{} * * * *".format(args["cronfreq"])) cron.write() db["cron"] = True _save_db()
python
def _setup_crontab(): """Sets up the crontab if it hasn't already been setup.""" from crontab import CronTab #Since CI works out of a virtualenv anyway, the `ci.py` script will be #installed in the bin already, so we can call it explicitly. command = '/bin/bash -c "source ~/.cron_profile; workon {}; ci.py -cron"'.format(settings.venv) user = _get_real_user() if args["nolive"]: vms("Skipping cron tab configuration because 'nolive' enabled.") return cron = CronTab(user=user) #We need to see if the cron has already been created for this command. existing = False possible = cron.find_comment("pyci_cron") if len(list(possible)) > 0: if args["rollback"]: vms("Removing {} from cron tab.".format(command)) cron.remove_all(command) cron.write() db["cron"] = False _save_db() else: existing = True if not existing and not args["rollback"]: job = cron.new(command=command, comment="pyci_cron") #Run the cron every minute of every hour every day. if args["cronfreq"] == 1: vms("New cron tab configured *minutely* for {}".format(command)) job.setall("* * * * *") else: vms("New cron tab configured every {} minutes for {}.".format(args["cronfreq"], command)) job.setall("*/{} * * * *".format(args["cronfreq"])) cron.write() db["cron"] = True _save_db()
[ "def", "_setup_crontab", "(", ")", ":", "from", "crontab", "import", "CronTab", "#Since CI works out of a virtualenv anyway, the `ci.py` script will be", "#installed in the bin already, so we can call it explicitly.", "command", "=", "'/bin/bash -c \"source ~/.cron_profile; workon {}; ci.py -cron\"'", ".", "format", "(", "settings", ".", "venv", ")", "user", "=", "_get_real_user", "(", ")", "if", "args", "[", "\"nolive\"", "]", ":", "vms", "(", "\"Skipping cron tab configuration because 'nolive' enabled.\"", ")", "return", "cron", "=", "CronTab", "(", "user", "=", "user", ")", "#We need to see if the cron has already been created for this command.", "existing", "=", "False", "possible", "=", "cron", ".", "find_comment", "(", "\"pyci_cron\"", ")", "if", "len", "(", "list", "(", "possible", ")", ")", ">", "0", ":", "if", "args", "[", "\"rollback\"", "]", ":", "vms", "(", "\"Removing {} from cron tab.\"", ".", "format", "(", "command", ")", ")", "cron", ".", "remove_all", "(", "command", ")", "cron", ".", "write", "(", ")", "db", "[", "\"cron\"", "]", "=", "False", "_save_db", "(", ")", "else", ":", "existing", "=", "True", "if", "not", "existing", "and", "not", "args", "[", "\"rollback\"", "]", ":", "job", "=", "cron", ".", "new", "(", "command", "=", "command", ",", "comment", "=", "\"pyci_cron\"", ")", "#Run the cron every minute of every hour every day.", "if", "args", "[", "\"cronfreq\"", "]", "==", "1", ":", "vms", "(", "\"New cron tab configured *minutely* for {}\"", ".", "format", "(", "command", ")", ")", "job", ".", "setall", "(", "\"* * * * *\"", ")", "else", ":", "vms", "(", "\"New cron tab configured every {} minutes for {}.\"", ".", "format", "(", "args", "[", "\"cronfreq\"", "]", ",", "command", ")", ")", "job", ".", "setall", "(", "\"*/{} * * * *\"", ".", "format", "(", "args", "[", "\"cronfreq\"", "]", ")", ")", "cron", ".", "write", "(", ")", "db", "[", "\"cron\"", "]", "=", "True", "_save_db", "(", ")" ]
Sets up the crontab if it hasn't already been setup.
[ "Sets", "up", "the", "crontab", "if", "it", "hasn", "t", "already", "been", "setup", "." ]
4d5a60291424a83124d1d962d17fb4c7718cde2b
https://github.com/rosenbrockc/ci/blob/4d5a60291424a83124d1d962d17fb4c7718cde2b/pyci/scripts/ci.py#L187-L223
238,752
rosenbrockc/ci
pyci/scripts/ci.py
_cron_profile
def _cron_profile(): """Sets up the .cron_profile file if it does not already exist. """ #The main ingredients of the file are the import of the virtualenvwrapper #and the setting of the PYCI_XML variable for global configuration. from os import path cronpath = path.expanduser("~/.cron_profile") if not path.isfile(cronpath): from os import getenv xmlpath = getenv("PYCI_XML") contents = ['source /usr/local/bin/virtualenvwrapper.sh', 'export PYCI_XML="{}"'.format(xmlpath)] with open(cronpath, 'w') as f: f.write('\n'.join(contents))
python
def _cron_profile(): """Sets up the .cron_profile file if it does not already exist. """ #The main ingredients of the file are the import of the virtualenvwrapper #and the setting of the PYCI_XML variable for global configuration. from os import path cronpath = path.expanduser("~/.cron_profile") if not path.isfile(cronpath): from os import getenv xmlpath = getenv("PYCI_XML") contents = ['source /usr/local/bin/virtualenvwrapper.sh', 'export PYCI_XML="{}"'.format(xmlpath)] with open(cronpath, 'w') as f: f.write('\n'.join(contents))
[ "def", "_cron_profile", "(", ")", ":", "#The main ingredients of the file are the import of the virtualenvwrapper", "#and the setting of the PYCI_XML variable for global configuration.", "from", "os", "import", "path", "cronpath", "=", "path", ".", "expanduser", "(", "\"~/.cron_profile\"", ")", "if", "not", "path", ".", "isfile", "(", "cronpath", ")", ":", "from", "os", "import", "getenv", "xmlpath", "=", "getenv", "(", "\"PYCI_XML\"", ")", "contents", "=", "[", "'source /usr/local/bin/virtualenvwrapper.sh'", ",", "'export PYCI_XML=\"{}\"'", ".", "format", "(", "xmlpath", ")", "]", "with", "open", "(", "cronpath", ",", "'w'", ")", "as", "f", ":", "f", ".", "write", "(", "'\\n'", ".", "join", "(", "contents", ")", ")" ]
Sets up the .cron_profile file if it does not already exist.
[ "Sets", "up", "the", ".", "cron_profile", "file", "if", "it", "does", "not", "already", "exist", "." ]
4d5a60291424a83124d1d962d17fb4c7718cde2b
https://github.com/rosenbrockc/ci/blob/4d5a60291424a83124d1d962d17fb4c7718cde2b/pyci/scripts/ci.py#L225-L238
238,753
rosenbrockc/ci
pyci/scripts/ci.py
_setup_server
def _setup_server(): """Checks whether the server needs to be setup if a repo is being installed. If it does, checks whether anything needs to be done. """ if args["setup"] or args["install"]: #If the cron has been configured, it means that the server has been #setup. We also perform some checks of the configuration file and the #existence of the virtualenv. if not _check_global_settings() or not _check_virtualenv(): return False _cron_profile() if "cron" in db and not db["cron"]: _setup_crontab() if args["rollback"]: _setup_crontab()
python
def _setup_server(): """Checks whether the server needs to be setup if a repo is being installed. If it does, checks whether anything needs to be done. """ if args["setup"] or args["install"]: #If the cron has been configured, it means that the server has been #setup. We also perform some checks of the configuration file and the #existence of the virtualenv. if not _check_global_settings() or not _check_virtualenv(): return False _cron_profile() if "cron" in db and not db["cron"]: _setup_crontab() if args["rollback"]: _setup_crontab()
[ "def", "_setup_server", "(", ")", ":", "if", "args", "[", "\"setup\"", "]", "or", "args", "[", "\"install\"", "]", ":", "#If the cron has been configured, it means that the server has been", "#setup. We also perform some checks of the configuration file and the", "#existence of the virtualenv.", "if", "not", "_check_global_settings", "(", ")", "or", "not", "_check_virtualenv", "(", ")", ":", "return", "False", "_cron_profile", "(", ")", "if", "\"cron\"", "in", "db", "and", "not", "db", "[", "\"cron\"", "]", ":", "_setup_crontab", "(", ")", "if", "args", "[", "\"rollback\"", "]", ":", "_setup_crontab", "(", ")" ]
Checks whether the server needs to be setup if a repo is being installed. If it does, checks whether anything needs to be done.
[ "Checks", "whether", "the", "server", "needs", "to", "be", "setup", "if", "a", "repo", "is", "being", "installed", ".", "If", "it", "does", "checks", "whether", "anything", "needs", "to", "be", "done", "." ]
4d5a60291424a83124d1d962d17fb4c7718cde2b
https://github.com/rosenbrockc/ci/blob/4d5a60291424a83124d1d962d17fb4c7718cde2b/pyci/scripts/ci.py#L240-L256
238,754
rosenbrockc/ci
pyci/scripts/ci.py
_server_rollback
def _server_rollback(): """Removes script database and archive files to rollback the CI server installation. """ #Remove the data and archive files specified in settings. The cron #gets remove by the _setup_server() script if -rollback is specified. from os import path, remove archpath = path.abspath(path.expanduser(settings.archfile)) if path.isfile(archpath) and not args["nolive"]: vms("Removing archive JSON file at {}.".format(archpath)) remove(archpath) datapath = path.abspath(path.expanduser(settings.datafile)) if path.isfile(datapath) and not args["nolive"]: vms("Removing script database JSON file at {}".format(datapath)) remove(datapath)
python
def _server_rollback(): """Removes script database and archive files to rollback the CI server installation. """ #Remove the data and archive files specified in settings. The cron #gets remove by the _setup_server() script if -rollback is specified. from os import path, remove archpath = path.abspath(path.expanduser(settings.archfile)) if path.isfile(archpath) and not args["nolive"]: vms("Removing archive JSON file at {}.".format(archpath)) remove(archpath) datapath = path.abspath(path.expanduser(settings.datafile)) if path.isfile(datapath) and not args["nolive"]: vms("Removing script database JSON file at {}".format(datapath)) remove(datapath)
[ "def", "_server_rollback", "(", ")", ":", "#Remove the data and archive files specified in settings. The cron", "#gets remove by the _setup_server() script if -rollback is specified.", "from", "os", "import", "path", ",", "remove", "archpath", "=", "path", ".", "abspath", "(", "path", ".", "expanduser", "(", "settings", ".", "archfile", ")", ")", "if", "path", ".", "isfile", "(", "archpath", ")", "and", "not", "args", "[", "\"nolive\"", "]", ":", "vms", "(", "\"Removing archive JSON file at {}.\"", ".", "format", "(", "archpath", ")", ")", "remove", "(", "archpath", ")", "datapath", "=", "path", ".", "abspath", "(", "path", ".", "expanduser", "(", "settings", ".", "datafile", ")", ")", "if", "path", ".", "isfile", "(", "datapath", ")", "and", "not", "args", "[", "\"nolive\"", "]", ":", "vms", "(", "\"Removing script database JSON file at {}\"", ".", "format", "(", "datapath", ")", ")", "remove", "(", "datapath", ")" ]
Removes script database and archive files to rollback the CI server installation.
[ "Removes", "script", "database", "and", "archive", "files", "to", "rollback", "the", "CI", "server", "installation", "." ]
4d5a60291424a83124d1d962d17fb4c7718cde2b
https://github.com/rosenbrockc/ci/blob/4d5a60291424a83124d1d962d17fb4c7718cde2b/pyci/scripts/ci.py#L258-L272
238,755
rosenbrockc/ci
pyci/scripts/ci.py
_list_repos
def _list_repos(): """Lists all the installed repos as well as their last start and finish times from the cron's perspective. """ if not args["list"]: return #Just loop over the list of repos we have in a server instance. See if #they also exist in the db's status; if they do, include the start/end #times we have saved. from pyci.server import Server server = Server(testmode=args["nolive"]) output = ["Repository | Started | Finished | XML File Path", "--------------------------------------------------------------------------"] dbs = {} if "status" not in db else db["status"] fullfmt = "{0:<20} | {1:^16} | {2:^16} | {3}" for reponame, repo in server.repositories.items(): if reponame in dbs: start = _fmt_time(dbs[reponame]["start"]) end = _fmt_time(dbs[reponame]["end"]) else: start = "Never" end = "Never" output.append(fullfmt.format(reponame, start, end, repo.filepath)) info('\n'.join(output))
python
def _list_repos(): """Lists all the installed repos as well as their last start and finish times from the cron's perspective. """ if not args["list"]: return #Just loop over the list of repos we have in a server instance. See if #they also exist in the db's status; if they do, include the start/end #times we have saved. from pyci.server import Server server = Server(testmode=args["nolive"]) output = ["Repository | Started | Finished | XML File Path", "--------------------------------------------------------------------------"] dbs = {} if "status" not in db else db["status"] fullfmt = "{0:<20} | {1:^16} | {2:^16} | {3}" for reponame, repo in server.repositories.items(): if reponame in dbs: start = _fmt_time(dbs[reponame]["start"]) end = _fmt_time(dbs[reponame]["end"]) else: start = "Never" end = "Never" output.append(fullfmt.format(reponame, start, end, repo.filepath)) info('\n'.join(output))
[ "def", "_list_repos", "(", ")", ":", "if", "not", "args", "[", "\"list\"", "]", ":", "return", "#Just loop over the list of repos we have in a server instance. See if", "#they also exist in the db's status; if they do, include the start/end", "#times we have saved.", "from", "pyci", ".", "server", "import", "Server", "server", "=", "Server", "(", "testmode", "=", "args", "[", "\"nolive\"", "]", ")", "output", "=", "[", "\"Repository | Started | Finished | XML File Path\"", ",", "\"--------------------------------------------------------------------------\"", "]", "dbs", "=", "{", "}", "if", "\"status\"", "not", "in", "db", "else", "db", "[", "\"status\"", "]", "fullfmt", "=", "\"{0:<20} | {1:^16} | {2:^16} | {3}\"", "for", "reponame", ",", "repo", "in", "server", ".", "repositories", ".", "items", "(", ")", ":", "if", "reponame", "in", "dbs", ":", "start", "=", "_fmt_time", "(", "dbs", "[", "reponame", "]", "[", "\"start\"", "]", ")", "end", "=", "_fmt_time", "(", "dbs", "[", "reponame", "]", "[", "\"end\"", "]", ")", "else", ":", "start", "=", "\"Never\"", "end", "=", "\"Never\"", "output", ".", "append", "(", "fullfmt", ".", "format", "(", "reponame", ",", "start", ",", "end", ",", "repo", ".", "filepath", ")", ")", "info", "(", "'\\n'", ".", "join", "(", "output", ")", ")" ]
Lists all the installed repos as well as their last start and finish times from the cron's perspective.
[ "Lists", "all", "the", "installed", "repos", "as", "well", "as", "their", "last", "start", "and", "finish", "times", "from", "the", "cron", "s", "perspective", "." ]
4d5a60291424a83124d1d962d17fb4c7718cde2b
https://github.com/rosenbrockc/ci/blob/4d5a60291424a83124d1d962d17fb4c7718cde2b/pyci/scripts/ci.py#L404-L430
238,756
rosenbrockc/ci
pyci/scripts/ci.py
run
def run(): """Main script entry to handle the arguments given to the script.""" _parser_options() set_verbose(args["verbose"]) if _check_global_settings(): _load_db() else: exit(-1) #Check the server configuration against the script arguments passed in. _setup_server() if args["rollback"]: _server_rollback() okay("The server rollback appears to have been successful.") exit(0) _server_enable() _list_repos() _handle_install() #This is the workhorse once a successful installation has happened. _do_cron()
python
def run(): """Main script entry to handle the arguments given to the script.""" _parser_options() set_verbose(args["verbose"]) if _check_global_settings(): _load_db() else: exit(-1) #Check the server configuration against the script arguments passed in. _setup_server() if args["rollback"]: _server_rollback() okay("The server rollback appears to have been successful.") exit(0) _server_enable() _list_repos() _handle_install() #This is the workhorse once a successful installation has happened. _do_cron()
[ "def", "run", "(", ")", ":", "_parser_options", "(", ")", "set_verbose", "(", "args", "[", "\"verbose\"", "]", ")", "if", "_check_global_settings", "(", ")", ":", "_load_db", "(", ")", "else", ":", "exit", "(", "-", "1", ")", "#Check the server configuration against the script arguments passed in.", "_setup_server", "(", ")", "if", "args", "[", "\"rollback\"", "]", ":", "_server_rollback", "(", ")", "okay", "(", "\"The server rollback appears to have been successful.\"", ")", "exit", "(", "0", ")", "_server_enable", "(", ")", "_list_repos", "(", ")", "_handle_install", "(", ")", "#This is the workhorse once a successful installation has happened.", "_do_cron", "(", ")" ]
Main script entry to handle the arguments given to the script.
[ "Main", "script", "entry", "to", "handle", "the", "arguments", "given", "to", "the", "script", "." ]
4d5a60291424a83124d1d962d17fb4c7718cde2b
https://github.com/rosenbrockc/ci/blob/4d5a60291424a83124d1d962d17fb4c7718cde2b/pyci/scripts/ci.py#L447-L470
238,757
roboogle/gtkmvc3
gtkmvco/gtkmvc3/controller.py
Controller._idle_register_view
def _idle_register_view(self, view): """Internal method that calls register_view""" assert(self.view is None) self.view = view if self.handlers == "class": for name in dir(self): when, _, what = partition(name, '_') widget, _, signal = partition(what, '__') if when == "on": try: view[widget].connect(signal, getattr(self, name)) except IndexError: # Not a handler pass except KeyError: logger.warn("Widget not found for handler: %s", name) elif self.handlers == "glade": self.__autoconnect_signals() else: raise NotImplementedError("%s is not a valid source of signal " "connections" % self.handlers) self.register_view(view) self.register_adapters() if self.__auto_adapt: self.adapt() return False
python
def _idle_register_view(self, view): """Internal method that calls register_view""" assert(self.view is None) self.view = view if self.handlers == "class": for name in dir(self): when, _, what = partition(name, '_') widget, _, signal = partition(what, '__') if when == "on": try: view[widget].connect(signal, getattr(self, name)) except IndexError: # Not a handler pass except KeyError: logger.warn("Widget not found for handler: %s", name) elif self.handlers == "glade": self.__autoconnect_signals() else: raise NotImplementedError("%s is not a valid source of signal " "connections" % self.handlers) self.register_view(view) self.register_adapters() if self.__auto_adapt: self.adapt() return False
[ "def", "_idle_register_view", "(", "self", ",", "view", ")", ":", "assert", "(", "self", ".", "view", "is", "None", ")", "self", ".", "view", "=", "view", "if", "self", ".", "handlers", "==", "\"class\"", ":", "for", "name", "in", "dir", "(", "self", ")", ":", "when", ",", "_", ",", "what", "=", "partition", "(", "name", ",", "'_'", ")", "widget", ",", "_", ",", "signal", "=", "partition", "(", "what", ",", "'__'", ")", "if", "when", "==", "\"on\"", ":", "try", ":", "view", "[", "widget", "]", ".", "connect", "(", "signal", ",", "getattr", "(", "self", ",", "name", ")", ")", "except", "IndexError", ":", "# Not a handler", "pass", "except", "KeyError", ":", "logger", ".", "warn", "(", "\"Widget not found for handler: %s\"", ",", "name", ")", "elif", "self", ".", "handlers", "==", "\"glade\"", ":", "self", ".", "__autoconnect_signals", "(", ")", "else", ":", "raise", "NotImplementedError", "(", "\"%s is not a valid source of signal \"", "\"connections\"", "%", "self", ".", "handlers", ")", "self", ".", "register_view", "(", "view", ")", "self", ".", "register_adapters", "(", ")", "if", "self", ".", "__auto_adapt", ":", "self", ".", "adapt", "(", ")", "return", "False" ]
Internal method that calls register_view
[ "Internal", "method", "that", "calls", "register_view" ]
63405fd8d2056be26af49103b13a8d5e57fe4dff
https://github.com/roboogle/gtkmvc3/blob/63405fd8d2056be26af49103b13a8d5e57fe4dff/gtkmvco/gtkmvc3/controller.py#L153-L179
238,758
roboogle/gtkmvc3
gtkmvco/gtkmvc3/controller.py
Controller.__autoconnect_signals
def __autoconnect_signals(self): """This is called during view registration, to autoconnect signals in glade file with methods within the controller""" dic = {} for name in dir(self): method = getattr(self, name) if (not isinstance(method, collections.Callable)): continue assert(name not in dic) # not already connected! dic[name] = method # autoconnects glade in the view (if available any) for xml in self.view.glade_xmlWidgets: xml.signal_autoconnect(dic) # autoconnects builder if available if self.view._builder is not None: self.view._builder_connect_signals(dic)
python
def __autoconnect_signals(self): """This is called during view registration, to autoconnect signals in glade file with methods within the controller""" dic = {} for name in dir(self): method = getattr(self, name) if (not isinstance(method, collections.Callable)): continue assert(name not in dic) # not already connected! dic[name] = method # autoconnects glade in the view (if available any) for xml in self.view.glade_xmlWidgets: xml.signal_autoconnect(dic) # autoconnects builder if available if self.view._builder is not None: self.view._builder_connect_signals(dic)
[ "def", "__autoconnect_signals", "(", "self", ")", ":", "dic", "=", "{", "}", "for", "name", "in", "dir", "(", "self", ")", ":", "method", "=", "getattr", "(", "self", ",", "name", ")", "if", "(", "not", "isinstance", "(", "method", ",", "collections", ".", "Callable", ")", ")", ":", "continue", "assert", "(", "name", "not", "in", "dic", ")", "# not already connected!", "dic", "[", "name", "]", "=", "method", "# autoconnects glade in the view (if available any)", "for", "xml", "in", "self", ".", "view", ".", "glade_xmlWidgets", ":", "xml", ".", "signal_autoconnect", "(", "dic", ")", "# autoconnects builder if available", "if", "self", ".", "view", ".", "_builder", "is", "not", "None", ":", "self", ".", "view", ".", "_builder_connect_signals", "(", "dic", ")" ]
This is called during view registration, to autoconnect signals in glade file with methods within the controller
[ "This", "is", "called", "during", "view", "registration", "to", "autoconnect", "signals", "in", "glade", "file", "with", "methods", "within", "the", "controller" ]
63405fd8d2056be26af49103b13a8d5e57fe4dff
https://github.com/roboogle/gtkmvc3/blob/63405fd8d2056be26af49103b13a8d5e57fe4dff/gtkmvco/gtkmvc3/controller.py#L445-L462
238,759
puiterwijk/python-openid-teams
openid_teams/teams.py
TeamsRequest.parseExtensionArgs
def parseExtensionArgs(self, args): """Parse the unqualified teams extension request parameters and add them to this object. This method is essentially the inverse of C{L{getExtensionArgs}}. This method restores the serialized teams extension team names. If you are extracting arguments from a standard OpenID checkid_* request, you probably want to use C{L{fromOpenIDRequest}}, which will extract the teams extension namespace and arguments from the OpenID request. This method is intended for cases where the OpenID server needs more control over how the arguments are parsed than that method provides. >>> args = message.getArgs(teams_uri) >>> request.parseExtensionArgs(args) @param args: The unqualified teams extension arguments @type args: {str:str} @returns: None; updates this object """ items = args.get('query_membership') if items: for team_name in items.split(','): self.requestTeam(team_name)
python
def parseExtensionArgs(self, args): """Parse the unqualified teams extension request parameters and add them to this object. This method is essentially the inverse of C{L{getExtensionArgs}}. This method restores the serialized teams extension team names. If you are extracting arguments from a standard OpenID checkid_* request, you probably want to use C{L{fromOpenIDRequest}}, which will extract the teams extension namespace and arguments from the OpenID request. This method is intended for cases where the OpenID server needs more control over how the arguments are parsed than that method provides. >>> args = message.getArgs(teams_uri) >>> request.parseExtensionArgs(args) @param args: The unqualified teams extension arguments @type args: {str:str} @returns: None; updates this object """ items = args.get('query_membership') if items: for team_name in items.split(','): self.requestTeam(team_name)
[ "def", "parseExtensionArgs", "(", "self", ",", "args", ")", ":", "items", "=", "args", ".", "get", "(", "'query_membership'", ")", "if", "items", ":", "for", "team_name", "in", "items", ".", "split", "(", "','", ")", ":", "self", ".", "requestTeam", "(", "team_name", ")" ]
Parse the unqualified teams extension request parameters and add them to this object. This method is essentially the inverse of C{L{getExtensionArgs}}. This method restores the serialized teams extension team names. If you are extracting arguments from a standard OpenID checkid_* request, you probably want to use C{L{fromOpenIDRequest}}, which will extract the teams extension namespace and arguments from the OpenID request. This method is intended for cases where the OpenID server needs more control over how the arguments are parsed than that method provides. >>> args = message.getArgs(teams_uri) >>> request.parseExtensionArgs(args) @param args: The unqualified teams extension arguments @type args: {str:str} @returns: None; updates this object
[ "Parse", "the", "unqualified", "teams", "extension", "request", "parameters", "and", "add", "them", "to", "this", "object", "." ]
b8fe6c63d0f6d9b4d69f38de3e1caf8b77d893d5
https://github.com/puiterwijk/python-openid-teams/blob/b8fe6c63d0f6d9b4d69f38de3e1caf8b77d893d5/openid_teams/teams.py#L138-L164
238,760
puiterwijk/python-openid-teams
openid_teams/teams.py
TeamsRequest.requestTeam
def requestTeam(self, team_name): """Request the specified team membership from the OpenID user @param team_name: the unqualified team name @type team_name: str """ if not team_name in self.requested: self.requested.append(team_name)
python
def requestTeam(self, team_name): """Request the specified team membership from the OpenID user @param team_name: the unqualified team name @type team_name: str """ if not team_name in self.requested: self.requested.append(team_name)
[ "def", "requestTeam", "(", "self", ",", "team_name", ")", ":", "if", "not", "team_name", "in", "self", ".", "requested", ":", "self", ".", "requested", ".", "append", "(", "team_name", ")" ]
Request the specified team membership from the OpenID user @param team_name: the unqualified team name @type team_name: str
[ "Request", "the", "specified", "team", "membership", "from", "the", "OpenID", "user" ]
b8fe6c63d0f6d9b4d69f38de3e1caf8b77d893d5
https://github.com/puiterwijk/python-openid-teams/blob/b8fe6c63d0f6d9b4d69f38de3e1caf8b77d893d5/openid_teams/teams.py#L177-L184
238,761
puiterwijk/python-openid-teams
openid_teams/teams.py
TeamsRequest.requestTeams
def requestTeams(self, team_names): """Add the given list of team names to the request. @param team_names: The team names to request @type team_names: [str] """ if isinstance(team_names, six.string_types): raise TypeError('Teams should be passed as a list of ' 'strings (not %r)' % (type(field_names),)) for team_name in team_names: self.requestTeam(team_name)
python
def requestTeams(self, team_names): """Add the given list of team names to the request. @param team_names: The team names to request @type team_names: [str] """ if isinstance(team_names, six.string_types): raise TypeError('Teams should be passed as a list of ' 'strings (not %r)' % (type(field_names),)) for team_name in team_names: self.requestTeam(team_name)
[ "def", "requestTeams", "(", "self", ",", "team_names", ")", ":", "if", "isinstance", "(", "team_names", ",", "six", ".", "string_types", ")", ":", "raise", "TypeError", "(", "'Teams should be passed as a list of '", "'strings (not %r)'", "%", "(", "type", "(", "field_names", ")", ",", ")", ")", "for", "team_name", "in", "team_names", ":", "self", ".", "requestTeam", "(", "team_name", ")" ]
Add the given list of team names to the request. @param team_names: The team names to request @type team_names: [str]
[ "Add", "the", "given", "list", "of", "team", "names", "to", "the", "request", "." ]
b8fe6c63d0f6d9b4d69f38de3e1caf8b77d893d5
https://github.com/puiterwijk/python-openid-teams/blob/b8fe6c63d0f6d9b4d69f38de3e1caf8b77d893d5/openid_teams/teams.py#L186-L197
238,762
pip-services3-python/pip-services3-commons-python
pip_services3_commons/reflect/RecursiveObjectReader.py
RecursiveObjectReader.has_property
def has_property(obj, name): """ Checks recursively if object or its subobjects has a property with specified name. The object can be a user defined object, map or array. The property name correspondently must be object property, map key or array index. :param obj: an object to introspect. :param name: a name of the property to check. :return: true if the object has the property and false if it doesn't. """ if obj == None or name == None: return False names = name.split(".") if names == None or len(names) == 0: return False return RecursiveObjectReader._perform_has_property(obj, names, 0)
python
def has_property(obj, name): """ Checks recursively if object or its subobjects has a property with specified name. The object can be a user defined object, map or array. The property name correspondently must be object property, map key or array index. :param obj: an object to introspect. :param name: a name of the property to check. :return: true if the object has the property and false if it doesn't. """ if obj == None or name == None: return False names = name.split(".") if names == None or len(names) == 0: return False return RecursiveObjectReader._perform_has_property(obj, names, 0)
[ "def", "has_property", "(", "obj", ",", "name", ")", ":", "if", "obj", "==", "None", "or", "name", "==", "None", ":", "return", "False", "names", "=", "name", ".", "split", "(", "\".\"", ")", "if", "names", "==", "None", "or", "len", "(", "names", ")", "==", "0", ":", "return", "False", "return", "RecursiveObjectReader", ".", "_perform_has_property", "(", "obj", ",", "names", ",", "0", ")" ]
Checks recursively if object or its subobjects has a property with specified name. The object can be a user defined object, map or array. The property name correspondently must be object property, map key or array index. :param obj: an object to introspect. :param name: a name of the property to check. :return: true if the object has the property and false if it doesn't.
[ "Checks", "recursively", "if", "object", "or", "its", "subobjects", "has", "a", "property", "with", "specified", "name", "." ]
22cbbb3e91e49717f65c083d36147fdb07ba9e3b
https://github.com/pip-services3-python/pip-services3-commons-python/blob/22cbbb3e91e49717f65c083d36147fdb07ba9e3b/pip_services3_commons/reflect/RecursiveObjectReader.py#L37-L57
238,763
pip-services3-python/pip-services3-commons-python
pip_services3_commons/reflect/RecursiveObjectReader.py
RecursiveObjectReader.get_property
def get_property(obj, name): """ Recursively gets value of object or its subobjects property specified by its name. The object can be a user defined object, map or array. The property name correspondently must be object property, map key or array index. :param obj: an object to read property from. :param name: a name of the property to get. :return: the property value or null if property doesn't exist or introspection failed. """ if obj == None or name == None: return None names = name.split(".") if names == None or len(names) == 0: return None return RecursiveObjectReader._perform_get_property(obj, names, 0)
python
def get_property(obj, name): """ Recursively gets value of object or its subobjects property specified by its name. The object can be a user defined object, map or array. The property name correspondently must be object property, map key or array index. :param obj: an object to read property from. :param name: a name of the property to get. :return: the property value or null if property doesn't exist or introspection failed. """ if obj == None or name == None: return None names = name.split(".") if names == None or len(names) == 0: return None return RecursiveObjectReader._perform_get_property(obj, names, 0)
[ "def", "get_property", "(", "obj", ",", "name", ")", ":", "if", "obj", "==", "None", "or", "name", "==", "None", ":", "return", "None", "names", "=", "name", ".", "split", "(", "\".\"", ")", "if", "names", "==", "None", "or", "len", "(", "names", ")", "==", "0", ":", "return", "None", "return", "RecursiveObjectReader", ".", "_perform_get_property", "(", "obj", ",", "names", ",", "0", ")" ]
Recursively gets value of object or its subobjects property specified by its name. The object can be a user defined object, map or array. The property name correspondently must be object property, map key or array index. :param obj: an object to read property from. :param name: a name of the property to get. :return: the property value or null if property doesn't exist or introspection failed.
[ "Recursively", "gets", "value", "of", "object", "or", "its", "subobjects", "property", "specified", "by", "its", "name", "." ]
22cbbb3e91e49717f65c083d36147fdb07ba9e3b
https://github.com/pip-services3-python/pip-services3-commons-python/blob/22cbbb3e91e49717f65c083d36147fdb07ba9e3b/pip_services3_commons/reflect/RecursiveObjectReader.py#L73-L93
238,764
pip-services3-python/pip-services3-commons-python
pip_services3_commons/reflect/RecursiveObjectReader.py
RecursiveObjectReader.get_property_names
def get_property_names(obj): """ Recursively gets names of all properties implemented in specified object and its subobjects. The object can be a user defined object, map or array. Returned property name correspondently are object properties, map keys or array indexes. :param obj: an object to introspect. :return: a list with property names. """ property_names = [] if obj != None: cycle_detect = [] RecursiveObjectReader._perform_get_property_names(obj, None, property_names, cycle_detect) return property_names
python
def get_property_names(obj): """ Recursively gets names of all properties implemented in specified object and its subobjects. The object can be a user defined object, map or array. Returned property name correspondently are object properties, map keys or array indexes. :param obj: an object to introspect. :return: a list with property names. """ property_names = [] if obj != None: cycle_detect = [] RecursiveObjectReader._perform_get_property_names(obj, None, property_names, cycle_detect) return property_names
[ "def", "get_property_names", "(", "obj", ")", ":", "property_names", "=", "[", "]", "if", "obj", "!=", "None", ":", "cycle_detect", "=", "[", "]", "RecursiveObjectReader", ".", "_perform_get_property_names", "(", "obj", ",", "None", ",", "property_names", ",", "cycle_detect", ")", "return", "property_names" ]
Recursively gets names of all properties implemented in specified object and its subobjects. The object can be a user defined object, map or array. Returned property name correspondently are object properties, map keys or array indexes. :param obj: an object to introspect. :return: a list with property names.
[ "Recursively", "gets", "names", "of", "all", "properties", "implemented", "in", "specified", "object", "and", "its", "subobjects", "." ]
22cbbb3e91e49717f65c083d36147fdb07ba9e3b
https://github.com/pip-services3-python/pip-services3-commons-python/blob/22cbbb3e91e49717f65c083d36147fdb07ba9e3b/pip_services3_commons/reflect/RecursiveObjectReader.py#L130-L147
238,765
pip-services3-python/pip-services3-commons-python
pip_services3_commons/reflect/RecursiveObjectReader.py
RecursiveObjectReader.get_properties
def get_properties(obj): """ Get values of all properties in specified object and its subobjects and returns them as a map. The object can be a user defined object, map or array. Returned properties correspondently are object properties, map key-pairs or array elements with their indexes. :param obj: an object to get properties from. :return: a map, containing the names of the object's properties and their values. """ properties = {} if obj != None: cycle_detect = [] RecursiveObjectReader._perform_get_properties(obj, None, properties, cycle_detect) return properties
python
def get_properties(obj): """ Get values of all properties in specified object and its subobjects and returns them as a map. The object can be a user defined object, map or array. Returned properties correspondently are object properties, map key-pairs or array elements with their indexes. :param obj: an object to get properties from. :return: a map, containing the names of the object's properties and their values. """ properties = {} if obj != None: cycle_detect = [] RecursiveObjectReader._perform_get_properties(obj, None, properties, cycle_detect) return properties
[ "def", "get_properties", "(", "obj", ")", ":", "properties", "=", "{", "}", "if", "obj", "!=", "None", ":", "cycle_detect", "=", "[", "]", "RecursiveObjectReader", ".", "_perform_get_properties", "(", "obj", ",", "None", ",", "properties", ",", "cycle_detect", ")", "return", "properties" ]
Get values of all properties in specified object and its subobjects and returns them as a map. The object can be a user defined object, map or array. Returned properties correspondently are object properties, map key-pairs or array elements with their indexes. :param obj: an object to get properties from. :return: a map, containing the names of the object's properties and their values.
[ "Get", "values", "of", "all", "properties", "in", "specified", "object", "and", "its", "subobjects", "and", "returns", "them", "as", "a", "map", "." ]
22cbbb3e91e49717f65c083d36147fdb07ba9e3b
https://github.com/pip-services3-python/pip-services3-commons-python/blob/22cbbb3e91e49717f65c083d36147fdb07ba9e3b/pip_services3_commons/reflect/RecursiveObjectReader.py#L177-L194
238,766
jbasko/hookery
hookery/base.py
hookable
def hookable(cls): """ Initialise hookery in a class that declares hooks by decorating it with this decorator. This replaces the class with another one which has the same name, but also inherits Hookable which has HookableMeta set as metaclass so that sub-classes of cls will have hook descriptors initialised properly. When you say: @hookable class My: before = Hook() then @hookable changes My.before to be a HookDescriptor which is then changed into Hook if anyone accesses it. There is no need to decorate sub-classes of cls with @hookable. """ assert isinstance(cls, type) # For classes that won't have descriptors initialised by metaclass, need to do it here. hook_definitions = [] if not issubclass(cls, Hookable): for k, v in list(cls.__dict__.items()): if isinstance(v, (ClassHook, InstanceHook)): delattr(cls, k) if v.name is None: v.name = k hook_definitions.append((k, v)) hookable_cls = type(cls.__name__, (cls, Hookable), {}) for k, v in hook_definitions: setattr(hookable_cls, k, HookDescriptor(defining_hook=v, defining_class=hookable_cls)) return hookable_cls
python
def hookable(cls): """ Initialise hookery in a class that declares hooks by decorating it with this decorator. This replaces the class with another one which has the same name, but also inherits Hookable which has HookableMeta set as metaclass so that sub-classes of cls will have hook descriptors initialised properly. When you say: @hookable class My: before = Hook() then @hookable changes My.before to be a HookDescriptor which is then changed into Hook if anyone accesses it. There is no need to decorate sub-classes of cls with @hookable. """ assert isinstance(cls, type) # For classes that won't have descriptors initialised by metaclass, need to do it here. hook_definitions = [] if not issubclass(cls, Hookable): for k, v in list(cls.__dict__.items()): if isinstance(v, (ClassHook, InstanceHook)): delattr(cls, k) if v.name is None: v.name = k hook_definitions.append((k, v)) hookable_cls = type(cls.__name__, (cls, Hookable), {}) for k, v in hook_definitions: setattr(hookable_cls, k, HookDescriptor(defining_hook=v, defining_class=hookable_cls)) return hookable_cls
[ "def", "hookable", "(", "cls", ")", ":", "assert", "isinstance", "(", "cls", ",", "type", ")", "# For classes that won't have descriptors initialised by metaclass, need to do it here.", "hook_definitions", "=", "[", "]", "if", "not", "issubclass", "(", "cls", ",", "Hookable", ")", ":", "for", "k", ",", "v", "in", "list", "(", "cls", ".", "__dict__", ".", "items", "(", ")", ")", ":", "if", "isinstance", "(", "v", ",", "(", "ClassHook", ",", "InstanceHook", ")", ")", ":", "delattr", "(", "cls", ",", "k", ")", "if", "v", ".", "name", "is", "None", ":", "v", ".", "name", "=", "k", "hook_definitions", ".", "append", "(", "(", "k", ",", "v", ")", ")", "hookable_cls", "=", "type", "(", "cls", ".", "__name__", ",", "(", "cls", ",", "Hookable", ")", ",", "{", "}", ")", "for", "k", ",", "v", "in", "hook_definitions", ":", "setattr", "(", "hookable_cls", ",", "k", ",", "HookDescriptor", "(", "defining_hook", "=", "v", ",", "defining_class", "=", "hookable_cls", ")", ")", "return", "hookable_cls" ]
Initialise hookery in a class that declares hooks by decorating it with this decorator. This replaces the class with another one which has the same name, but also inherits Hookable which has HookableMeta set as metaclass so that sub-classes of cls will have hook descriptors initialised properly. When you say: @hookable class My: before = Hook() then @hookable changes My.before to be a HookDescriptor which is then changed into Hook if anyone accesses it. There is no need to decorate sub-classes of cls with @hookable.
[ "Initialise", "hookery", "in", "a", "class", "that", "declares", "hooks", "by", "decorating", "it", "with", "this", "decorator", "." ]
5638de2999ad533f83bc9a03110f85e5a0404257
https://github.com/jbasko/hookery/blob/5638de2999ad533f83bc9a03110f85e5a0404257/hookery/base.py#L452-L487
238,767
jbasko/hookery
hookery/base.py
Hook._triggering_ctx
def _triggering_ctx(self): """ Context manager that ensures that a hook is not re-triggered by one of its handlers. """ if self._is_triggering: raise RuntimeError('{} cannot be triggered while it is being handled'.format(self)) self._is_triggering = True try: yield self finally: self._is_triggering = False
python
def _triggering_ctx(self): """ Context manager that ensures that a hook is not re-triggered by one of its handlers. """ if self._is_triggering: raise RuntimeError('{} cannot be triggered while it is being handled'.format(self)) self._is_triggering = True try: yield self finally: self._is_triggering = False
[ "def", "_triggering_ctx", "(", "self", ")", ":", "if", "self", ".", "_is_triggering", ":", "raise", "RuntimeError", "(", "'{} cannot be triggered while it is being handled'", ".", "format", "(", "self", ")", ")", "self", ".", "_is_triggering", "=", "True", "try", ":", "yield", "self", "finally", ":", "self", ".", "_is_triggering", "=", "False" ]
Context manager that ensures that a hook is not re-triggered by one of its handlers.
[ "Context", "manager", "that", "ensures", "that", "a", "hook", "is", "not", "re", "-", "triggered", "by", "one", "of", "its", "handlers", "." ]
5638de2999ad533f83bc9a03110f85e5a0404257
https://github.com/jbasko/hookery/blob/5638de2999ad533f83bc9a03110f85e5a0404257/hookery/base.py#L157-L167
238,768
jbasko/hookery
hookery/base.py
Hook.unregister_handler
def unregister_handler(self, handler_or_func): """ Remove the handler from this hook's list of handlers. This does not give up until the handler is found in the class hierarchy. """ index = -1 for i, handler in enumerate(self._direct_handlers): if handler is handler_or_func or handler._original_func is handler_or_func: index = i break if index >= 0: self._direct_handlers.pop(index) self._cached_handlers = None elif self.parent_class_hook is not None and self.parent_class_hook.has_handler(handler_or_func): self.parent_class_hook.unregister_handler(handler_or_func) self._cached_handlers = None elif self.instance_class_hook is not None and self.instance_class_hook.has_handler(handler_or_func): self.instance_class_hook.unregister_handler(handler_or_func) self._cached_handlers = None else: raise ValueError('{} is not a registered handler of {}'.format(handler_or_func, self))
python
def unregister_handler(self, handler_or_func): """ Remove the handler from this hook's list of handlers. This does not give up until the handler is found in the class hierarchy. """ index = -1 for i, handler in enumerate(self._direct_handlers): if handler is handler_or_func or handler._original_func is handler_or_func: index = i break if index >= 0: self._direct_handlers.pop(index) self._cached_handlers = None elif self.parent_class_hook is not None and self.parent_class_hook.has_handler(handler_or_func): self.parent_class_hook.unregister_handler(handler_or_func) self._cached_handlers = None elif self.instance_class_hook is not None and self.instance_class_hook.has_handler(handler_or_func): self.instance_class_hook.unregister_handler(handler_or_func) self._cached_handlers = None else: raise ValueError('{} is not a registered handler of {}'.format(handler_or_func, self))
[ "def", "unregister_handler", "(", "self", ",", "handler_or_func", ")", ":", "index", "=", "-", "1", "for", "i", ",", "handler", "in", "enumerate", "(", "self", ".", "_direct_handlers", ")", ":", "if", "handler", "is", "handler_or_func", "or", "handler", ".", "_original_func", "is", "handler_or_func", ":", "index", "=", "i", "break", "if", "index", ">=", "0", ":", "self", ".", "_direct_handlers", ".", "pop", "(", "index", ")", "self", ".", "_cached_handlers", "=", "None", "elif", "self", ".", "parent_class_hook", "is", "not", "None", "and", "self", ".", "parent_class_hook", ".", "has_handler", "(", "handler_or_func", ")", ":", "self", ".", "parent_class_hook", ".", "unregister_handler", "(", "handler_or_func", ")", "self", ".", "_cached_handlers", "=", "None", "elif", "self", ".", "instance_class_hook", "is", "not", "None", "and", "self", ".", "instance_class_hook", ".", "has_handler", "(", "handler_or_func", ")", ":", "self", ".", "instance_class_hook", ".", "unregister_handler", "(", "handler_or_func", ")", "self", ".", "_cached_handlers", "=", "None", "else", ":", "raise", "ValueError", "(", "'{} is not a registered handler of {}'", ".", "format", "(", "handler_or_func", ",", "self", ")", ")" ]
Remove the handler from this hook's list of handlers. This does not give up until the handler is found in the class hierarchy.
[ "Remove", "the", "handler", "from", "this", "hook", "s", "list", "of", "handlers", ".", "This", "does", "not", "give", "up", "until", "the", "handler", "is", "found", "in", "the", "class", "hierarchy", "." ]
5638de2999ad533f83bc9a03110f85e5a0404257
https://github.com/jbasko/hookery/blob/5638de2999ad533f83bc9a03110f85e5a0404257/hookery/base.py#L240-L263
238,769
crypto101/arthur
arthur/exercises.py
ExercisesLocator.notifySolved
def notifySolved(self, identifier, title): """Notifies the user that a particular exercise has been solved. """ notify(self.workbench, u"Congratulations", u"Congratulations! You " "have completed the '{title}' exercise.".format(title=title)) return {}
python
def notifySolved(self, identifier, title): """Notifies the user that a particular exercise has been solved. """ notify(self.workbench, u"Congratulations", u"Congratulations! You " "have completed the '{title}' exercise.".format(title=title)) return {}
[ "def", "notifySolved", "(", "self", ",", "identifier", ",", "title", ")", ":", "notify", "(", "self", ".", "workbench", ",", "u\"Congratulations\"", ",", "u\"Congratulations! You \"", "\"have completed the '{title}' exercise.\"", ".", "format", "(", "title", "=", "title", ")", ")", "return", "{", "}" ]
Notifies the user that a particular exercise has been solved.
[ "Notifies", "the", "user", "that", "a", "particular", "exercise", "has", "been", "solved", "." ]
c32e693fb5af17eac010e3b20f7653ed6e11eb6a
https://github.com/crypto101/arthur/blob/c32e693fb5af17eac010e3b20f7653ed6e11eb6a/arthur/exercises.py#L29-L35
238,770
ROGUE-JCTD/django-tilebundler
tilebundler/api.py
TilesetResource.prepend_urls
def prepend_urls(self): """ Add the following array of urls to the Tileset base urls """ return [ url(r"^(?P<resource_name>%s)/(?P<pk>\w[\w/-]*)/generate%s$" % (self._meta.resource_name, trailing_slash()), self.wrap_view('generate'), name="api_tileset_generate"), url(r"^(?P<resource_name>%s)/(?P<pk>\w[\w/-]*)/download%s$" % (self._meta.resource_name, trailing_slash()), self.wrap_view('download'), name="api_tileset_download"), url(r"^(?P<resource_name>%s)/(?P<pk>\w[\w/-]*)/status%s$" % (self._meta.resource_name, trailing_slash()), self.wrap_view('status'), name="api_tileset_status"), url(r"^(?P<resource_name>%s)/(?P<pk>\w[\w/-]*)/stop%s$" % (self._meta.resource_name, trailing_slash()), self.wrap_view('stop'), name="api_tileset_stop"), ]
python
def prepend_urls(self): """ Add the following array of urls to the Tileset base urls """ return [ url(r"^(?P<resource_name>%s)/(?P<pk>\w[\w/-]*)/generate%s$" % (self._meta.resource_name, trailing_slash()), self.wrap_view('generate'), name="api_tileset_generate"), url(r"^(?P<resource_name>%s)/(?P<pk>\w[\w/-]*)/download%s$" % (self._meta.resource_name, trailing_slash()), self.wrap_view('download'), name="api_tileset_download"), url(r"^(?P<resource_name>%s)/(?P<pk>\w[\w/-]*)/status%s$" % (self._meta.resource_name, trailing_slash()), self.wrap_view('status'), name="api_tileset_status"), url(r"^(?P<resource_name>%s)/(?P<pk>\w[\w/-]*)/stop%s$" % (self._meta.resource_name, trailing_slash()), self.wrap_view('stop'), name="api_tileset_stop"), ]
[ "def", "prepend_urls", "(", "self", ")", ":", "return", "[", "url", "(", "r\"^(?P<resource_name>%s)/(?P<pk>\\w[\\w/-]*)/generate%s$\"", "%", "(", "self", ".", "_meta", ".", "resource_name", ",", "trailing_slash", "(", ")", ")", ",", "self", ".", "wrap_view", "(", "'generate'", ")", ",", "name", "=", "\"api_tileset_generate\"", ")", ",", "url", "(", "r\"^(?P<resource_name>%s)/(?P<pk>\\w[\\w/-]*)/download%s$\"", "%", "(", "self", ".", "_meta", ".", "resource_name", ",", "trailing_slash", "(", ")", ")", ",", "self", ".", "wrap_view", "(", "'download'", ")", ",", "name", "=", "\"api_tileset_download\"", ")", ",", "url", "(", "r\"^(?P<resource_name>%s)/(?P<pk>\\w[\\w/-]*)/status%s$\"", "%", "(", "self", ".", "_meta", ".", "resource_name", ",", "trailing_slash", "(", ")", ")", ",", "self", ".", "wrap_view", "(", "'status'", ")", ",", "name", "=", "\"api_tileset_status\"", ")", ",", "url", "(", "r\"^(?P<resource_name>%s)/(?P<pk>\\w[\\w/-]*)/stop%s$\"", "%", "(", "self", ".", "_meta", ".", "resource_name", ",", "trailing_slash", "(", ")", ")", ",", "self", ".", "wrap_view", "(", "'stop'", ")", ",", "name", "=", "\"api_tileset_stop\"", ")", ",", "]" ]
Add the following array of urls to the Tileset base urls
[ "Add", "the", "following", "array", "of", "urls", "to", "the", "Tileset", "base", "urls" ]
72bc25293c9d0e3608f9dba16eb6de5df8d679ee
https://github.com/ROGUE-JCTD/django-tilebundler/blob/72bc25293c9d0e3608f9dba16eb6de5df8d679ee/tilebundler/api.py#L32-L47
238,771
ROGUE-JCTD/django-tilebundler
tilebundler/api.py
TilesetResource.generate
def generate(self, request, **kwargs): """ proxy for the tileset.generate method """ # method check to avoid bad requests self.method_check(request, allowed=['get']) # create a basic bundle object for self.get_cached_obj_get. basic_bundle = self.build_bundle(request=request) # using the primary key defined in the url, obtain the tileset tileset = self.cached_obj_get( bundle=basic_bundle, **self.remove_api_resource_names(kwargs)) # Return what the method output, tastypie will handle the serialization return self.create_response(request, tileset.generate())
python
def generate(self, request, **kwargs): """ proxy for the tileset.generate method """ # method check to avoid bad requests self.method_check(request, allowed=['get']) # create a basic bundle object for self.get_cached_obj_get. basic_bundle = self.build_bundle(request=request) # using the primary key defined in the url, obtain the tileset tileset = self.cached_obj_get( bundle=basic_bundle, **self.remove_api_resource_names(kwargs)) # Return what the method output, tastypie will handle the serialization return self.create_response(request, tileset.generate())
[ "def", "generate", "(", "self", ",", "request", ",", "*", "*", "kwargs", ")", ":", "# method check to avoid bad requests", "self", ".", "method_check", "(", "request", ",", "allowed", "=", "[", "'get'", "]", ")", "# create a basic bundle object for self.get_cached_obj_get.", "basic_bundle", "=", "self", ".", "build_bundle", "(", "request", "=", "request", ")", "# using the primary key defined in the url, obtain the tileset", "tileset", "=", "self", ".", "cached_obj_get", "(", "bundle", "=", "basic_bundle", ",", "*", "*", "self", ".", "remove_api_resource_names", "(", "kwargs", ")", ")", "# Return what the method output, tastypie will handle the serialization", "return", "self", ".", "create_response", "(", "request", ",", "tileset", ".", "generate", "(", ")", ")" ]
proxy for the tileset.generate method
[ "proxy", "for", "the", "tileset", ".", "generate", "method" ]
72bc25293c9d0e3608f9dba16eb6de5df8d679ee
https://github.com/ROGUE-JCTD/django-tilebundler/blob/72bc25293c9d0e3608f9dba16eb6de5df8d679ee/tilebundler/api.py#L60-L75
238,772
ROGUE-JCTD/django-tilebundler
tilebundler/api.py
TilesetResource.download
def download(self, request, **kwargs): """ proxy for the helpers.tileset_download method """ # method check to avoid bad requests self.method_check(request, allowed=['get']) # create a basic bundle object for self.get_cached_obj_get. basic_bundle = self.build_bundle(request=request) # using the primary key defined in the url, obtain the tileset tileset = self.cached_obj_get( bundle=basic_bundle, **self.remove_api_resource_names(kwargs)) filename = helpers.get_tileset_filename(tileset) filename = os.path.abspath(filename) if os.path.isfile(filename): response = serve(request, os.path.basename(filename), os.path.dirname(filename)) response['Content-Disposition'] = 'attachment; filename="{}"'.format(os.path.basename(filename)) else: response = self.create_response(request, {'status': 'not generated'}) return response
python
def download(self, request, **kwargs): """ proxy for the helpers.tileset_download method """ # method check to avoid bad requests self.method_check(request, allowed=['get']) # create a basic bundle object for self.get_cached_obj_get. basic_bundle = self.build_bundle(request=request) # using the primary key defined in the url, obtain the tileset tileset = self.cached_obj_get( bundle=basic_bundle, **self.remove_api_resource_names(kwargs)) filename = helpers.get_tileset_filename(tileset) filename = os.path.abspath(filename) if os.path.isfile(filename): response = serve(request, os.path.basename(filename), os.path.dirname(filename)) response['Content-Disposition'] = 'attachment; filename="{}"'.format(os.path.basename(filename)) else: response = self.create_response(request, {'status': 'not generated'}) return response
[ "def", "download", "(", "self", ",", "request", ",", "*", "*", "kwargs", ")", ":", "# method check to avoid bad requests", "self", ".", "method_check", "(", "request", ",", "allowed", "=", "[", "'get'", "]", ")", "# create a basic bundle object for self.get_cached_obj_get.", "basic_bundle", "=", "self", ".", "build_bundle", "(", "request", "=", "request", ")", "# using the primary key defined in the url, obtain the tileset", "tileset", "=", "self", ".", "cached_obj_get", "(", "bundle", "=", "basic_bundle", ",", "*", "*", "self", ".", "remove_api_resource_names", "(", "kwargs", ")", ")", "filename", "=", "helpers", ".", "get_tileset_filename", "(", "tileset", ")", "filename", "=", "os", ".", "path", ".", "abspath", "(", "filename", ")", "if", "os", ".", "path", ".", "isfile", "(", "filename", ")", ":", "response", "=", "serve", "(", "request", ",", "os", ".", "path", ".", "basename", "(", "filename", ")", ",", "os", ".", "path", ".", "dirname", "(", "filename", ")", ")", "response", "[", "'Content-Disposition'", "]", "=", "'attachment; filename=\"{}\"'", ".", "format", "(", "os", ".", "path", ".", "basename", "(", "filename", ")", ")", "else", ":", "response", "=", "self", ".", "create_response", "(", "request", ",", "{", "'status'", ":", "'not generated'", "}", ")", "return", "response" ]
proxy for the helpers.tileset_download method
[ "proxy", "for", "the", "helpers", ".", "tileset_download", "method" ]
72bc25293c9d0e3608f9dba16eb6de5df8d679ee
https://github.com/ROGUE-JCTD/django-tilebundler/blob/72bc25293c9d0e3608f9dba16eb6de5df8d679ee/tilebundler/api.py#L77-L98
238,773
pip-services3-python/pip-services3-commons-python
pip_services3_commons/refer/DependencyResolver.py
DependencyResolver.configure
def configure(self, config): """ Configures the component with specified parameters. :param config: configuration parameters to set. """ dependencies = config.get_section("dependencies") names = dependencies.get_key_names() for name in names: locator = dependencies.get(name) if locator == None: continue try: descriptor = Descriptor.from_string(locator) if descriptor != None: self._dependencies[name] = descriptor else: self._dependencies[name] = locator except Exception as ex: self._dependencies[name] = locator
python
def configure(self, config): """ Configures the component with specified parameters. :param config: configuration parameters to set. """ dependencies = config.get_section("dependencies") names = dependencies.get_key_names() for name in names: locator = dependencies.get(name) if locator == None: continue try: descriptor = Descriptor.from_string(locator) if descriptor != None: self._dependencies[name] = descriptor else: self._dependencies[name] = locator except Exception as ex: self._dependencies[name] = locator
[ "def", "configure", "(", "self", ",", "config", ")", ":", "dependencies", "=", "config", ".", "get_section", "(", "\"dependencies\"", ")", "names", "=", "dependencies", ".", "get_key_names", "(", ")", "for", "name", "in", "names", ":", "locator", "=", "dependencies", ".", "get", "(", "name", ")", "if", "locator", "==", "None", ":", "continue", "try", ":", "descriptor", "=", "Descriptor", ".", "from_string", "(", "locator", ")", "if", "descriptor", "!=", "None", ":", "self", ".", "_dependencies", "[", "name", "]", "=", "descriptor", "else", ":", "self", ".", "_dependencies", "[", "name", "]", "=", "locator", "except", "Exception", "as", "ex", ":", "self", ".", "_dependencies", "[", "name", "]", "=", "locator" ]
Configures the component with specified parameters. :param config: configuration parameters to set.
[ "Configures", "the", "component", "with", "specified", "parameters", "." ]
22cbbb3e91e49717f65c083d36147fdb07ba9e3b
https://github.com/pip-services3-python/pip-services3-commons-python/blob/22cbbb3e91e49717f65c083d36147fdb07ba9e3b/pip_services3_commons/refer/DependencyResolver.py#L81-L101
238,774
pip-services3-python/pip-services3-commons-python
pip_services3_commons/refer/DependencyResolver.py
DependencyResolver._locate
def _locate(self, name): """ Gets a dependency locator by its name. :param name: the name of the dependency to locate. :return: the dependency locator or null if locator was not configured. """ if name == None: raise Exception("Dependency name cannot be null") if self._references == None: raise Exception("References shall be set") return self._dependencies.get(name)
python
def _locate(self, name): """ Gets a dependency locator by its name. :param name: the name of the dependency to locate. :return: the dependency locator or null if locator was not configured. """ if name == None: raise Exception("Dependency name cannot be null") if self._references == None: raise Exception("References shall be set") return self._dependencies.get(name)
[ "def", "_locate", "(", "self", ",", "name", ")", ":", "if", "name", "==", "None", ":", "raise", "Exception", "(", "\"Dependency name cannot be null\"", ")", "if", "self", ".", "_references", "==", "None", ":", "raise", "Exception", "(", "\"References shall be set\"", ")", "return", "self", ".", "_dependencies", ".", "get", "(", "name", ")" ]
Gets a dependency locator by its name. :param name: the name of the dependency to locate. :return: the dependency locator or null if locator was not configured.
[ "Gets", "a", "dependency", "locator", "by", "its", "name", "." ]
22cbbb3e91e49717f65c083d36147fdb07ba9e3b
https://github.com/pip-services3-python/pip-services3-commons-python/blob/22cbbb3e91e49717f65c083d36147fdb07ba9e3b/pip_services3_commons/refer/DependencyResolver.py#L124-L136
238,775
pip-services3-python/pip-services3-commons-python
pip_services3_commons/refer/DependencyResolver.py
DependencyResolver.get_optional
def get_optional(self, name): """ Gets all optional dependencies by their name. :param name: the dependency name to locate. :return: a list with found dependencies or empty list of no dependencies was found. """ locator = self._locate(name) return self._references.get_optional(locator) if locator != None else None
python
def get_optional(self, name): """ Gets all optional dependencies by their name. :param name: the dependency name to locate. :return: a list with found dependencies or empty list of no dependencies was found. """ locator = self._locate(name) return self._references.get_optional(locator) if locator != None else None
[ "def", "get_optional", "(", "self", ",", "name", ")", ":", "locator", "=", "self", ".", "_locate", "(", "name", ")", "return", "self", ".", "_references", ".", "get_optional", "(", "locator", ")", "if", "locator", "!=", "None", "else", "None" ]
Gets all optional dependencies by their name. :param name: the dependency name to locate. :return: a list with found dependencies or empty list of no dependencies was found.
[ "Gets", "all", "optional", "dependencies", "by", "their", "name", "." ]
22cbbb3e91e49717f65c083d36147fdb07ba9e3b
https://github.com/pip-services3-python/pip-services3-commons-python/blob/22cbbb3e91e49717f65c083d36147fdb07ba9e3b/pip_services3_commons/refer/DependencyResolver.py#L139-L148
238,776
pip-services3-python/pip-services3-commons-python
pip_services3_commons/refer/DependencyResolver.py
DependencyResolver.get_one_optional
def get_one_optional(self, name): """ Gets one optional dependency by its name. :param name: the dependency name to locate. :return: a dependency reference or null of the dependency was not found """ locator = self._locate(name) return self._references.get_one_optional(locator) if locator != None else None
python
def get_one_optional(self, name): """ Gets one optional dependency by its name. :param name: the dependency name to locate. :return: a dependency reference or null of the dependency was not found """ locator = self._locate(name) return self._references.get_one_optional(locator) if locator != None else None
[ "def", "get_one_optional", "(", "self", ",", "name", ")", ":", "locator", "=", "self", ".", "_locate", "(", "name", ")", "return", "self", ".", "_references", ".", "get_one_optional", "(", "locator", ")", "if", "locator", "!=", "None", "else", "None" ]
Gets one optional dependency by its name. :param name: the dependency name to locate. :return: a dependency reference or null of the dependency was not found
[ "Gets", "one", "optional", "dependency", "by", "its", "name", "." ]
22cbbb3e91e49717f65c083d36147fdb07ba9e3b
https://github.com/pip-services3-python/pip-services3-commons-python/blob/22cbbb3e91e49717f65c083d36147fdb07ba9e3b/pip_services3_commons/refer/DependencyResolver.py#L167-L176
238,777
pip-services3-python/pip-services3-commons-python
pip_services3_commons/refer/DependencyResolver.py
DependencyResolver.find
def find(self, name, required): """ Finds all matching dependencies by their name. :param name: the dependency name to locate. :param required: true to raise an exception when no dependencies are found. :return: a list of found dependencies """ if name == None: raise Exception("Name cannot be null") locator = self._locate(name) if locator == None: if required: raise ReferenceException(None, name) return None return self._references.find(locator, required)
python
def find(self, name, required): """ Finds all matching dependencies by their name. :param name: the dependency name to locate. :param required: true to raise an exception when no dependencies are found. :return: a list of found dependencies """ if name == None: raise Exception("Name cannot be null") locator = self._locate(name) if locator == None: if required: raise ReferenceException(None, name) return None return self._references.find(locator, required)
[ "def", "find", "(", "self", ",", "name", ",", "required", ")", ":", "if", "name", "==", "None", ":", "raise", "Exception", "(", "\"Name cannot be null\"", ")", "locator", "=", "self", ".", "_locate", "(", "name", ")", "if", "locator", "==", "None", ":", "if", "required", ":", "raise", "ReferenceException", "(", "None", ",", "name", ")", "return", "None", "return", "self", ".", "_references", ".", "find", "(", "locator", ",", "required", ")" ]
Finds all matching dependencies by their name. :param name: the dependency name to locate. :param required: true to raise an exception when no dependencies are found. :return: a list of found dependencies
[ "Finds", "all", "matching", "dependencies", "by", "their", "name", "." ]
22cbbb3e91e49717f65c083d36147fdb07ba9e3b
https://github.com/pip-services3-python/pip-services3-commons-python/blob/22cbbb3e91e49717f65c083d36147fdb07ba9e3b/pip_services3_commons/refer/DependencyResolver.py#L195-L214
238,778
gersolar/noaadem
noaadem/instrument.py
obtain_to
def obtain_to(filename): """ Return the digital elevation map projected to the lat lon matrix coordenates. Keyword arguments: filename -- the name of a netcdf file. """ root, _ = nc.open(filename) lat, lon = nc.getvar(root, 'lat')[0,:], nc.getvar(root, 'lon')[0,:] nc.close(root) return obtain(lat, lon)
python
def obtain_to(filename): """ Return the digital elevation map projected to the lat lon matrix coordenates. Keyword arguments: filename -- the name of a netcdf file. """ root, _ = nc.open(filename) lat, lon = nc.getvar(root, 'lat')[0,:], nc.getvar(root, 'lon')[0,:] nc.close(root) return obtain(lat, lon)
[ "def", "obtain_to", "(", "filename", ")", ":", "root", ",", "_", "=", "nc", ".", "open", "(", "filename", ")", "lat", ",", "lon", "=", "nc", ".", "getvar", "(", "root", ",", "'lat'", ")", "[", "0", ",", ":", "]", ",", "nc", ".", "getvar", "(", "root", ",", "'lon'", ")", "[", "0", ",", ":", "]", "nc", ".", "close", "(", "root", ")", "return", "obtain", "(", "lat", ",", "lon", ")" ]
Return the digital elevation map projected to the lat lon matrix coordenates. Keyword arguments: filename -- the name of a netcdf file.
[ "Return", "the", "digital", "elevation", "map", "projected", "to", "the", "lat", "lon", "matrix", "coordenates", "." ]
924ccc968818314cf6ac8231a77bbf7f5259fa19
https://github.com/gersolar/noaadem/blob/924ccc968818314cf6ac8231a77bbf7f5259fa19/noaadem/instrument.py#L21-L31
238,779
pip-services3-python/pip-services3-commons-python
pip_services3_commons/config/OptionsResolver.py
OptionsResolver.resolve
def resolve(config, config_as_default = False): """ Resolves an "options" configuration section from component configuration parameters. :param config: configuration parameters :param config_as_default: (optional) When set true the method returns the entire parameter set when "options" section is not found. Default: false :return: configuration parameters from "options" section """ options = config.get_section("options") if len(options) == 0 and config_as_default: options = config return options
python
def resolve(config, config_as_default = False): """ Resolves an "options" configuration section from component configuration parameters. :param config: configuration parameters :param config_as_default: (optional) When set true the method returns the entire parameter set when "options" section is not found. Default: false :return: configuration parameters from "options" section """ options = config.get_section("options") if len(options) == 0 and config_as_default: options = config return options
[ "def", "resolve", "(", "config", ",", "config_as_default", "=", "False", ")", ":", "options", "=", "config", ".", "get_section", "(", "\"options\"", ")", "if", "len", "(", "options", ")", "==", "0", "and", "config_as_default", ":", "options", "=", "config", "return", "options" ]
Resolves an "options" configuration section from component configuration parameters. :param config: configuration parameters :param config_as_default: (optional) When set true the method returns the entire parameter set when "options" section is not found. Default: false :return: configuration parameters from "options" section
[ "Resolves", "an", "options", "configuration", "section", "from", "component", "configuration", "parameters", "." ]
22cbbb3e91e49717f65c083d36147fdb07ba9e3b
https://github.com/pip-services3-python/pip-services3-commons-python/blob/22cbbb3e91e49717f65c083d36147fdb07ba9e3b/pip_services3_commons/config/OptionsResolver.py#L30-L46
238,780
frascoweb/frasco-forms
frasco_forms/__init__.py
FormsFeature.init_form_view
def init_form_view(self, view, opts): """Checks if the form referenced in the view exists or attempts to create it by parsing the template """ name = opts.get("name", opts.get("form")) if isinstance(name, Form): return template = opts.get("template", getattr(view, "template", None)) if not template: if not name: raise NoFormError("No form name specified in the form action and no template") return try: as_ = opts.get("var_name", getattr(self.form, "as_", "form")) form_class = create_from_template(current_app, template, var_name=as_) except NoFormError: if not name: raise return if not name: name = view.name self.forms[name] = form_class self.form_created_from_view_signal.send(self, view=view, form_class=form_class) return form_class
python
def init_form_view(self, view, opts): """Checks if the form referenced in the view exists or attempts to create it by parsing the template """ name = opts.get("name", opts.get("form")) if isinstance(name, Form): return template = opts.get("template", getattr(view, "template", None)) if not template: if not name: raise NoFormError("No form name specified in the form action and no template") return try: as_ = opts.get("var_name", getattr(self.form, "as_", "form")) form_class = create_from_template(current_app, template, var_name=as_) except NoFormError: if not name: raise return if not name: name = view.name self.forms[name] = form_class self.form_created_from_view_signal.send(self, view=view, form_class=form_class) return form_class
[ "def", "init_form_view", "(", "self", ",", "view", ",", "opts", ")", ":", "name", "=", "opts", ".", "get", "(", "\"name\"", ",", "opts", ".", "get", "(", "\"form\"", ")", ")", "if", "isinstance", "(", "name", ",", "Form", ")", ":", "return", "template", "=", "opts", ".", "get", "(", "\"template\"", ",", "getattr", "(", "view", ",", "\"template\"", ",", "None", ")", ")", "if", "not", "template", ":", "if", "not", "name", ":", "raise", "NoFormError", "(", "\"No form name specified in the form action and no template\"", ")", "return", "try", ":", "as_", "=", "opts", ".", "get", "(", "\"var_name\"", ",", "getattr", "(", "self", ".", "form", ",", "\"as_\"", ",", "\"form\"", ")", ")", "form_class", "=", "create_from_template", "(", "current_app", ",", "template", ",", "var_name", "=", "as_", ")", "except", "NoFormError", ":", "if", "not", "name", ":", "raise", "return", "if", "not", "name", ":", "name", "=", "view", ".", "name", "self", ".", "forms", "[", "name", "]", "=", "form_class", "self", ".", "form_created_from_view_signal", ".", "send", "(", "self", ",", "view", "=", "view", ",", "form_class", "=", "form_class", ")", "return", "form_class" ]
Checks if the form referenced in the view exists or attempts to create it by parsing the template
[ "Checks", "if", "the", "form", "referenced", "in", "the", "view", "exists", "or", "attempts", "to", "create", "it", "by", "parsing", "the", "template" ]
e304117a934d3a24cff526aa9e84c2ca95f87f66
https://github.com/frascoweb/frasco-forms/blob/e304117a934d3a24cff526aa9e84c2ca95f87f66/frasco_forms/__init__.py#L86-L113
238,781
frascoweb/frasco-forms
frasco_forms/__init__.py
FormsFeature.populate_obj
def populate_obj(self, obj=None, form=None): """Populates an object with the form's data """ if not form: form = current_context.data.form if obj is None: obj = AttrDict() form.populate_obj(obj) return obj
python
def populate_obj(self, obj=None, form=None): """Populates an object with the form's data """ if not form: form = current_context.data.form if obj is None: obj = AttrDict() form.populate_obj(obj) return obj
[ "def", "populate_obj", "(", "self", ",", "obj", "=", "None", ",", "form", "=", "None", ")", ":", "if", "not", "form", ":", "form", "=", "current_context", ".", "data", ".", "form", "if", "obj", "is", "None", ":", "obj", "=", "AttrDict", "(", ")", "form", ".", "populate_obj", "(", "obj", ")", "return", "obj" ]
Populates an object with the form's data
[ "Populates", "an", "object", "with", "the", "form", "s", "data" ]
e304117a934d3a24cff526aa9e84c2ca95f87f66
https://github.com/frascoweb/frasco-forms/blob/e304117a934d3a24cff526aa9e84c2ca95f87f66/frasco_forms/__init__.py#L137-L145
238,782
Brazelton-Lab/bio_utils
bio_utils/iterators/gff3.py
GFF3Entry.overlap
def overlap(self, feature, stranded: bool=False): """Determine if a feature's position overlaps with the entry Args: feature (class): GFF3Entry object stranded (bool): allow features to overlap on different strands if True [default: False] Returns: bool: True if features overlap, else False """ # Allow features to overlap on different strands feature_strand = feature.strand strand = self.strand if stranded and ((strand == '.') or (strand == '+' and \ feature_strand in ['-', '.']) or (strand == '-' and \ feature_strand in ['+', '.'])): return False iv_1 = set(range(feature.start, feature.end + 1)) iv_2 = set(range(self.start, self.end + 1)) if len(iv_1.intersection(iv_2)) > 0: return True else: return False
python
def overlap(self, feature, stranded: bool=False): """Determine if a feature's position overlaps with the entry Args: feature (class): GFF3Entry object stranded (bool): allow features to overlap on different strands if True [default: False] Returns: bool: True if features overlap, else False """ # Allow features to overlap on different strands feature_strand = feature.strand strand = self.strand if stranded and ((strand == '.') or (strand == '+' and \ feature_strand in ['-', '.']) or (strand == '-' and \ feature_strand in ['+', '.'])): return False iv_1 = set(range(feature.start, feature.end + 1)) iv_2 = set(range(self.start, self.end + 1)) if len(iv_1.intersection(iv_2)) > 0: return True else: return False
[ "def", "overlap", "(", "self", ",", "feature", ",", "stranded", ":", "bool", "=", "False", ")", ":", "# Allow features to overlap on different strands", "feature_strand", "=", "feature", ".", "strand", "strand", "=", "self", ".", "strand", "if", "stranded", "and", "(", "(", "strand", "==", "'.'", ")", "or", "(", "strand", "==", "'+'", "and", "feature_strand", "in", "[", "'-'", ",", "'.'", "]", ")", "or", "(", "strand", "==", "'-'", "and", "feature_strand", "in", "[", "'+'", ",", "'.'", "]", ")", ")", ":", "return", "False", "iv_1", "=", "set", "(", "range", "(", "feature", ".", "start", ",", "feature", ".", "end", "+", "1", ")", ")", "iv_2", "=", "set", "(", "range", "(", "self", ".", "start", ",", "self", ".", "end", "+", "1", ")", ")", "if", "len", "(", "iv_1", ".", "intersection", "(", "iv_2", ")", ")", ">", "0", ":", "return", "True", "else", ":", "return", "False" ]
Determine if a feature's position overlaps with the entry Args: feature (class): GFF3Entry object stranded (bool): allow features to overlap on different strands if True [default: False] Returns: bool: True if features overlap, else False
[ "Determine", "if", "a", "feature", "s", "position", "overlaps", "with", "the", "entry" ]
5a7ddf13ee0bf4baaaeb6b2b99e01bf74aa132b7
https://github.com/Brazelton-Lab/bio_utils/blob/5a7ddf13ee0bf4baaaeb6b2b99e01bf74aa132b7/bio_utils/iterators/gff3.py#L102-L130
238,783
Brazelton-Lab/bio_utils
bio_utils/iterators/gff3.py
GFF3Entry.write
def write(self): """Restore GFF3 entry to original format Returns: str: properly formatted string containing the GFF3 entry """ none_type = type(None) # Format attributes for writing attrs = self.attribute_string() # Place holder if field value is NoneType for attr in self.__dict__.keys(): if type(attr) == none_type: setattr(self, attr, '.') # Format entry for writing fstr = '{0}\t{1}\t{2}\t{3}\t{4}\t{5}\t{6}\t{7}\t{8}{9}'\ .format(self.seqid, self.source, self.type, str(self.start), str(self.end), self._score_str, self.strand, self.phase, attrs, os.linesep) return fstr
python
def write(self): """Restore GFF3 entry to original format Returns: str: properly formatted string containing the GFF3 entry """ none_type = type(None) # Format attributes for writing attrs = self.attribute_string() # Place holder if field value is NoneType for attr in self.__dict__.keys(): if type(attr) == none_type: setattr(self, attr, '.') # Format entry for writing fstr = '{0}\t{1}\t{2}\t{3}\t{4}\t{5}\t{6}\t{7}\t{8}{9}'\ .format(self.seqid, self.source, self.type, str(self.start), str(self.end), self._score_str, self.strand, self.phase, attrs, os.linesep) return fstr
[ "def", "write", "(", "self", ")", ":", "none_type", "=", "type", "(", "None", ")", "# Format attributes for writing", "attrs", "=", "self", ".", "attribute_string", "(", ")", "# Place holder if field value is NoneType", "for", "attr", "in", "self", ".", "__dict__", ".", "keys", "(", ")", ":", "if", "type", "(", "attr", ")", "==", "none_type", ":", "setattr", "(", "self", ",", "attr", ",", "'.'", ")", "# Format entry for writing", "fstr", "=", "'{0}\\t{1}\\t{2}\\t{3}\\t{4}\\t{5}\\t{6}\\t{7}\\t{8}{9}'", ".", "format", "(", "self", ".", "seqid", ",", "self", ".", "source", ",", "self", ".", "type", ",", "str", "(", "self", ".", "start", ")", ",", "str", "(", "self", ".", "end", ")", ",", "self", ".", "_score_str", ",", "self", ".", "strand", ",", "self", ".", "phase", ",", "attrs", ",", "os", ".", "linesep", ")", "return", "fstr" ]
Restore GFF3 entry to original format Returns: str: properly formatted string containing the GFF3 entry
[ "Restore", "GFF3", "entry", "to", "original", "format" ]
5a7ddf13ee0bf4baaaeb6b2b99e01bf74aa132b7
https://github.com/Brazelton-Lab/bio_utils/blob/5a7ddf13ee0bf4baaaeb6b2b99e01bf74aa132b7/bio_utils/iterators/gff3.py#L132-L155
238,784
Brazelton-Lab/bio_utils
bio_utils/iterators/gff3.py
GFF3Entry.attribute_string
def attribute_string(self): """Restore an entries attributes in original format, escaping reserved characters when necessary Returns: str: escaped attributes as tag=value pairs, separated by semi-colon """ escape_map = {ord('='): '%3D', ord(','): '%2C', ord(';'): '%3B', ord('&'): '%26', ord('\t'): '%09', } list_type = type(list()) attrs = self.attributes if type(attrs) is OrderedDict: reserved_attrs = [] other_attrs = [] for name, value in attrs.items(): # Escape reserved characters name = name.translate(escape_map) if type(value) == list_type: value = ','.join([i.translate(escape_map) for i in value]) else: value = value.translate(escape_map) # Regain original formatting of attribute column out_attr = '{0}={1}'.format(name, value) # Order attributes so that reserved tags are output first if name[0].isupper(): reserved_attrs.append(out_attr) else: other_attrs.append(out_attr) out_attrs = ';'.join(reserved_attrs + other_attrs) else: out_attrs = attrs return out_attrs
python
def attribute_string(self): """Restore an entries attributes in original format, escaping reserved characters when necessary Returns: str: escaped attributes as tag=value pairs, separated by semi-colon """ escape_map = {ord('='): '%3D', ord(','): '%2C', ord(';'): '%3B', ord('&'): '%26', ord('\t'): '%09', } list_type = type(list()) attrs = self.attributes if type(attrs) is OrderedDict: reserved_attrs = [] other_attrs = [] for name, value in attrs.items(): # Escape reserved characters name = name.translate(escape_map) if type(value) == list_type: value = ','.join([i.translate(escape_map) for i in value]) else: value = value.translate(escape_map) # Regain original formatting of attribute column out_attr = '{0}={1}'.format(name, value) # Order attributes so that reserved tags are output first if name[0].isupper(): reserved_attrs.append(out_attr) else: other_attrs.append(out_attr) out_attrs = ';'.join(reserved_attrs + other_attrs) else: out_attrs = attrs return out_attrs
[ "def", "attribute_string", "(", "self", ")", ":", "escape_map", "=", "{", "ord", "(", "'='", ")", ":", "'%3D'", ",", "ord", "(", "','", ")", ":", "'%2C'", ",", "ord", "(", "';'", ")", ":", "'%3B'", ",", "ord", "(", "'&'", ")", ":", "'%26'", ",", "ord", "(", "'\\t'", ")", ":", "'%09'", ",", "}", "list_type", "=", "type", "(", "list", "(", ")", ")", "attrs", "=", "self", ".", "attributes", "if", "type", "(", "attrs", ")", "is", "OrderedDict", ":", "reserved_attrs", "=", "[", "]", "other_attrs", "=", "[", "]", "for", "name", ",", "value", "in", "attrs", ".", "items", "(", ")", ":", "# Escape reserved characters", "name", "=", "name", ".", "translate", "(", "escape_map", ")", "if", "type", "(", "value", ")", "==", "list_type", ":", "value", "=", "','", ".", "join", "(", "[", "i", ".", "translate", "(", "escape_map", ")", "for", "i", "in", "value", "]", ")", "else", ":", "value", "=", "value", ".", "translate", "(", "escape_map", ")", "# Regain original formatting of attribute column", "out_attr", "=", "'{0}={1}'", ".", "format", "(", "name", ",", "value", ")", "# Order attributes so that reserved tags are output first", "if", "name", "[", "0", "]", ".", "isupper", "(", ")", ":", "reserved_attrs", ".", "append", "(", "out_attr", ")", "else", ":", "other_attrs", ".", "append", "(", "out_attr", ")", "out_attrs", "=", "';'", ".", "join", "(", "reserved_attrs", "+", "other_attrs", ")", "else", ":", "out_attrs", "=", "attrs", "return", "out_attrs" ]
Restore an entries attributes in original format, escaping reserved characters when necessary Returns: str: escaped attributes as tag=value pairs, separated by semi-colon
[ "Restore", "an", "entries", "attributes", "in", "original", "format", "escaping", "reserved", "characters", "when", "necessary" ]
5a7ddf13ee0bf4baaaeb6b2b99e01bf74aa132b7
https://github.com/Brazelton-Lab/bio_utils/blob/5a7ddf13ee0bf4baaaeb6b2b99e01bf74aa132b7/bio_utils/iterators/gff3.py#L157-L201
238,785
Brazelton-Lab/bio_utils
bio_utils/iterators/gff3.py
GFF3Reader.iterate
def iterate(self, start_line=None, parse_attr=True, headers=False, comments=False): """Iterate over GFF3 file, returning GFF3 entries Args: start_line (str): Next GFF3 entry. If 'handle' has been partially read and you want to start iterating at the next entry, read the next GFF3 entry and pass it to this variable when calling gff3_iter. See 'Examples' for proper usage. parse_attr (bool): Parse attributes column into a dictionary such that the string "tag1=value1;tag2=value2" becomes: tag1: value1 tag2: value2 headers (bool): Yields headers if True, else skips lines starting with "##" comments (bool): Yields comments if True, else skips lines starting with "#" Yields: GFF3Entry: class containing all GFF3 data, yields str for headers if headers options is True then yields GFF3Entry for entries Examples: The following three examples demonstrate how to use gff3_iter. Note: These doctests will not pass, examples are only in doctest format as per convention. bio_utils uses pytests for testing. >>> for entry in gff3_iter(open('test.gff3')): ... print(entry.seqid) # Sequence ID ... print(entry.source) # Software that performed annotation ... print(entry.type) # Type of annotation ... print(entry.start) # Start position of annotation ... print(entry.end) # End position of annotation ... print(entry.score) # Confidence score of annotation ... print(entry.strand) # Strand annotation is on ... print(entry.phase) # Bases until next codon ... print(entry.attributes) # Attributes of annotation ... print(entry.write()) # Reconstituted GFF3 entry >>> gff3_handle = open('test.gff3') >>> next(gff3_handle) # Skip first line/entry >>> next_line = next(gff3_handle) # Store next entry >>> for entry in gff3_iter(gff3_handle, start_line=next_line): ... print(entry.seqid) # Sequence ID ... print(entry.source) # Software that performed annotation ... print(entry.type) # Type of annotation ... print(entry.start) # Start position of annotation ... print(entry.end) # End position of annotation ... print(entry.score) # Confidence score of annotation ... print(entry.strand) # Strand annotation is on ... print(entry.phase) # Bases until next codon ... print(entry.attributes) # Attributes of annotation ... print(entry.write()) # Reconstituted GFF3 entry >>> for entry in gff3_iter(open('test.gff3'), parse_attr=True): ... print(entry.seqid) # Sequence ID ... print(entry.source) # Software that performed annotation ... print(entry.type) # Type of annotation ... print(entry.start) # Start position of annotation ... print(entry.end) # End position of annotation ... print(entry.score) # Confidence score of annotation ... print(entry.strand) # Strand annotation is on ... print(entry.phase) # Bases until next codon ... print(entry.attributes['attr1']) # Print attribute 'attr1' ... print(entry.attributes['attr2']) # Print attribute 'attr2' ... print(entry.write()) # Reconstituted GFF3 entry """ handle = self.handle # Speed tricks: reduces function calls split = str.split strip = str.strip if start_line is None: line = next(handle) # Read first GFF3 else: line = start_line # Set header to given header # Check if input is text or bytestream if (isinstance(line, bytes)): def next_line(i): return next(i).decode('utf-8') line = strip(line.decode('utf-8')) else: next_line = next line = strip(line) # Manual 'for' loop isn't needed to read the file properly and quickly, # unlike fasta_iter and fastq_iter, but it is necessary begin iterating # partway through a file when the user gives a starting line. try: # Manually construct a for loop to improve speed by using 'next' while True: # Loop until StopIteration Exception raised self.current_line += 1 data = GFF3Entry() # Initialize early to prevent access error if line.startswith('##FASTA'): # Skip FASTA entries raise FastaFound if line.startswith('##') and not headers: line = strip(next_line(handle)) continue elif line.startswith('##') and headers: yield line line = strip(next_line(handle)) continue if line.startswith('#') and not comments: line = strip(next_line(handle)) continue elif line.startswith('#') and comments: yield line line = strip(next_line(handle)) continue split_line = split(line, '\t') data.origline = line data.seqid = split_line[0] data.source = split_line[1] data.type = split_line[2] data.start = int(split_line[3]) data.end = int(split_line[4]) try: # Make float unless dot data.score = float(split_line[5]) except ValueError: data.score = split_line[5] data._score_str = split_line[5] data.strand = split_line[6] try: # Get phase as int unless phase not given data.phase = int(split_line[7]) except ValueError: data.phase = split_line[7] data.attributes = split_line[8] if parse_attr: attributes = split(data.attributes, ';') data.attributes = OrderedDict() for attribute in attributes: split_attribute = attribute.split('=') key = split_attribute[0] value = split_attribute[-1].split(',') if ',' in \ split_attribute[-1] else split_attribute[-1] if not key == '': # Avoid semicolon split at end data.attributes[key] = value line = strip(next_line(handle)) # Raises StopIteration at EOF yield data except StopIteration: # Yield last GFF3 entry if data.origline: yield data else: #handle case where GFF ends in comment pass except FastaFound: # When FASTA found, last entry is repeat so pass pass
python
def iterate(self, start_line=None, parse_attr=True, headers=False, comments=False): """Iterate over GFF3 file, returning GFF3 entries Args: start_line (str): Next GFF3 entry. If 'handle' has been partially read and you want to start iterating at the next entry, read the next GFF3 entry and pass it to this variable when calling gff3_iter. See 'Examples' for proper usage. parse_attr (bool): Parse attributes column into a dictionary such that the string "tag1=value1;tag2=value2" becomes: tag1: value1 tag2: value2 headers (bool): Yields headers if True, else skips lines starting with "##" comments (bool): Yields comments if True, else skips lines starting with "#" Yields: GFF3Entry: class containing all GFF3 data, yields str for headers if headers options is True then yields GFF3Entry for entries Examples: The following three examples demonstrate how to use gff3_iter. Note: These doctests will not pass, examples are only in doctest format as per convention. bio_utils uses pytests for testing. >>> for entry in gff3_iter(open('test.gff3')): ... print(entry.seqid) # Sequence ID ... print(entry.source) # Software that performed annotation ... print(entry.type) # Type of annotation ... print(entry.start) # Start position of annotation ... print(entry.end) # End position of annotation ... print(entry.score) # Confidence score of annotation ... print(entry.strand) # Strand annotation is on ... print(entry.phase) # Bases until next codon ... print(entry.attributes) # Attributes of annotation ... print(entry.write()) # Reconstituted GFF3 entry >>> gff3_handle = open('test.gff3') >>> next(gff3_handle) # Skip first line/entry >>> next_line = next(gff3_handle) # Store next entry >>> for entry in gff3_iter(gff3_handle, start_line=next_line): ... print(entry.seqid) # Sequence ID ... print(entry.source) # Software that performed annotation ... print(entry.type) # Type of annotation ... print(entry.start) # Start position of annotation ... print(entry.end) # End position of annotation ... print(entry.score) # Confidence score of annotation ... print(entry.strand) # Strand annotation is on ... print(entry.phase) # Bases until next codon ... print(entry.attributes) # Attributes of annotation ... print(entry.write()) # Reconstituted GFF3 entry >>> for entry in gff3_iter(open('test.gff3'), parse_attr=True): ... print(entry.seqid) # Sequence ID ... print(entry.source) # Software that performed annotation ... print(entry.type) # Type of annotation ... print(entry.start) # Start position of annotation ... print(entry.end) # End position of annotation ... print(entry.score) # Confidence score of annotation ... print(entry.strand) # Strand annotation is on ... print(entry.phase) # Bases until next codon ... print(entry.attributes['attr1']) # Print attribute 'attr1' ... print(entry.attributes['attr2']) # Print attribute 'attr2' ... print(entry.write()) # Reconstituted GFF3 entry """ handle = self.handle # Speed tricks: reduces function calls split = str.split strip = str.strip if start_line is None: line = next(handle) # Read first GFF3 else: line = start_line # Set header to given header # Check if input is text or bytestream if (isinstance(line, bytes)): def next_line(i): return next(i).decode('utf-8') line = strip(line.decode('utf-8')) else: next_line = next line = strip(line) # Manual 'for' loop isn't needed to read the file properly and quickly, # unlike fasta_iter and fastq_iter, but it is necessary begin iterating # partway through a file when the user gives a starting line. try: # Manually construct a for loop to improve speed by using 'next' while True: # Loop until StopIteration Exception raised self.current_line += 1 data = GFF3Entry() # Initialize early to prevent access error if line.startswith('##FASTA'): # Skip FASTA entries raise FastaFound if line.startswith('##') and not headers: line = strip(next_line(handle)) continue elif line.startswith('##') and headers: yield line line = strip(next_line(handle)) continue if line.startswith('#') and not comments: line = strip(next_line(handle)) continue elif line.startswith('#') and comments: yield line line = strip(next_line(handle)) continue split_line = split(line, '\t') data.origline = line data.seqid = split_line[0] data.source = split_line[1] data.type = split_line[2] data.start = int(split_line[3]) data.end = int(split_line[4]) try: # Make float unless dot data.score = float(split_line[5]) except ValueError: data.score = split_line[5] data._score_str = split_line[5] data.strand = split_line[6] try: # Get phase as int unless phase not given data.phase = int(split_line[7]) except ValueError: data.phase = split_line[7] data.attributes = split_line[8] if parse_attr: attributes = split(data.attributes, ';') data.attributes = OrderedDict() for attribute in attributes: split_attribute = attribute.split('=') key = split_attribute[0] value = split_attribute[-1].split(',') if ',' in \ split_attribute[-1] else split_attribute[-1] if not key == '': # Avoid semicolon split at end data.attributes[key] = value line = strip(next_line(handle)) # Raises StopIteration at EOF yield data except StopIteration: # Yield last GFF3 entry if data.origline: yield data else: #handle case where GFF ends in comment pass except FastaFound: # When FASTA found, last entry is repeat so pass pass
[ "def", "iterate", "(", "self", ",", "start_line", "=", "None", ",", "parse_attr", "=", "True", ",", "headers", "=", "False", ",", "comments", "=", "False", ")", ":", "handle", "=", "self", ".", "handle", "# Speed tricks: reduces function calls", "split", "=", "str", ".", "split", "strip", "=", "str", ".", "strip", "if", "start_line", "is", "None", ":", "line", "=", "next", "(", "handle", ")", "# Read first GFF3", "else", ":", "line", "=", "start_line", "# Set header to given header", "# Check if input is text or bytestream", "if", "(", "isinstance", "(", "line", ",", "bytes", ")", ")", ":", "def", "next_line", "(", "i", ")", ":", "return", "next", "(", "i", ")", ".", "decode", "(", "'utf-8'", ")", "line", "=", "strip", "(", "line", ".", "decode", "(", "'utf-8'", ")", ")", "else", ":", "next_line", "=", "next", "line", "=", "strip", "(", "line", ")", "# Manual 'for' loop isn't needed to read the file properly and quickly,", "# unlike fasta_iter and fastq_iter, but it is necessary begin iterating", "# partway through a file when the user gives a starting line.", "try", ":", "# Manually construct a for loop to improve speed by using 'next'", "while", "True", ":", "# Loop until StopIteration Exception raised", "self", ".", "current_line", "+=", "1", "data", "=", "GFF3Entry", "(", ")", "# Initialize early to prevent access error", "if", "line", ".", "startswith", "(", "'##FASTA'", ")", ":", "# Skip FASTA entries", "raise", "FastaFound", "if", "line", ".", "startswith", "(", "'##'", ")", "and", "not", "headers", ":", "line", "=", "strip", "(", "next_line", "(", "handle", ")", ")", "continue", "elif", "line", ".", "startswith", "(", "'##'", ")", "and", "headers", ":", "yield", "line", "line", "=", "strip", "(", "next_line", "(", "handle", ")", ")", "continue", "if", "line", ".", "startswith", "(", "'#'", ")", "and", "not", "comments", ":", "line", "=", "strip", "(", "next_line", "(", "handle", ")", ")", "continue", "elif", "line", ".", "startswith", "(", "'#'", ")", "and", "comments", ":", "yield", "line", "line", "=", "strip", "(", "next_line", "(", "handle", ")", ")", "continue", "split_line", "=", "split", "(", "line", ",", "'\\t'", ")", "data", ".", "origline", "=", "line", "data", ".", "seqid", "=", "split_line", "[", "0", "]", "data", ".", "source", "=", "split_line", "[", "1", "]", "data", ".", "type", "=", "split_line", "[", "2", "]", "data", ".", "start", "=", "int", "(", "split_line", "[", "3", "]", ")", "data", ".", "end", "=", "int", "(", "split_line", "[", "4", "]", ")", "try", ":", "# Make float unless dot", "data", ".", "score", "=", "float", "(", "split_line", "[", "5", "]", ")", "except", "ValueError", ":", "data", ".", "score", "=", "split_line", "[", "5", "]", "data", ".", "_score_str", "=", "split_line", "[", "5", "]", "data", ".", "strand", "=", "split_line", "[", "6", "]", "try", ":", "# Get phase as int unless phase not given", "data", ".", "phase", "=", "int", "(", "split_line", "[", "7", "]", ")", "except", "ValueError", ":", "data", ".", "phase", "=", "split_line", "[", "7", "]", "data", ".", "attributes", "=", "split_line", "[", "8", "]", "if", "parse_attr", ":", "attributes", "=", "split", "(", "data", ".", "attributes", ",", "';'", ")", "data", ".", "attributes", "=", "OrderedDict", "(", ")", "for", "attribute", "in", "attributes", ":", "split_attribute", "=", "attribute", ".", "split", "(", "'='", ")", "key", "=", "split_attribute", "[", "0", "]", "value", "=", "split_attribute", "[", "-", "1", "]", ".", "split", "(", "','", ")", "if", "','", "in", "split_attribute", "[", "-", "1", "]", "else", "split_attribute", "[", "-", "1", "]", "if", "not", "key", "==", "''", ":", "# Avoid semicolon split at end", "data", ".", "attributes", "[", "key", "]", "=", "value", "line", "=", "strip", "(", "next_line", "(", "handle", ")", ")", "# Raises StopIteration at EOF", "yield", "data", "except", "StopIteration", ":", "# Yield last GFF3 entry", "if", "data", ".", "origline", ":", "yield", "data", "else", ":", "#handle case where GFF ends in comment", "pass", "except", "FastaFound", ":", "# When FASTA found, last entry is repeat so pass", "pass" ]
Iterate over GFF3 file, returning GFF3 entries Args: start_line (str): Next GFF3 entry. If 'handle' has been partially read and you want to start iterating at the next entry, read the next GFF3 entry and pass it to this variable when calling gff3_iter. See 'Examples' for proper usage. parse_attr (bool): Parse attributes column into a dictionary such that the string "tag1=value1;tag2=value2" becomes: tag1: value1 tag2: value2 headers (bool): Yields headers if True, else skips lines starting with "##" comments (bool): Yields comments if True, else skips lines starting with "#" Yields: GFF3Entry: class containing all GFF3 data, yields str for headers if headers options is True then yields GFF3Entry for entries Examples: The following three examples demonstrate how to use gff3_iter. Note: These doctests will not pass, examples are only in doctest format as per convention. bio_utils uses pytests for testing. >>> for entry in gff3_iter(open('test.gff3')): ... print(entry.seqid) # Sequence ID ... print(entry.source) # Software that performed annotation ... print(entry.type) # Type of annotation ... print(entry.start) # Start position of annotation ... print(entry.end) # End position of annotation ... print(entry.score) # Confidence score of annotation ... print(entry.strand) # Strand annotation is on ... print(entry.phase) # Bases until next codon ... print(entry.attributes) # Attributes of annotation ... print(entry.write()) # Reconstituted GFF3 entry >>> gff3_handle = open('test.gff3') >>> next(gff3_handle) # Skip first line/entry >>> next_line = next(gff3_handle) # Store next entry >>> for entry in gff3_iter(gff3_handle, start_line=next_line): ... print(entry.seqid) # Sequence ID ... print(entry.source) # Software that performed annotation ... print(entry.type) # Type of annotation ... print(entry.start) # Start position of annotation ... print(entry.end) # End position of annotation ... print(entry.score) # Confidence score of annotation ... print(entry.strand) # Strand annotation is on ... print(entry.phase) # Bases until next codon ... print(entry.attributes) # Attributes of annotation ... print(entry.write()) # Reconstituted GFF3 entry >>> for entry in gff3_iter(open('test.gff3'), parse_attr=True): ... print(entry.seqid) # Sequence ID ... print(entry.source) # Software that performed annotation ... print(entry.type) # Type of annotation ... print(entry.start) # Start position of annotation ... print(entry.end) # End position of annotation ... print(entry.score) # Confidence score of annotation ... print(entry.strand) # Strand annotation is on ... print(entry.phase) # Bases until next codon ... print(entry.attributes['attr1']) # Print attribute 'attr1' ... print(entry.attributes['attr2']) # Print attribute 'attr2' ... print(entry.write()) # Reconstituted GFF3 entry
[ "Iterate", "over", "GFF3", "file", "returning", "GFF3", "entries" ]
5a7ddf13ee0bf4baaaeb6b2b99e01bf74aa132b7
https://github.com/Brazelton-Lab/bio_utils/blob/5a7ddf13ee0bf4baaaeb6b2b99e01bf74aa132b7/bio_utils/iterators/gff3.py#L223-L387
238,786
pip-services3-python/pip-services3-commons-python
pip_services3_commons/refer/References.py
References.put
def put(self, locator = None, component = None): """ Puts a new reference into this reference map. :param locator: a component reference to be added. :param component: a locator to find the reference by. """ if component == None: raise Exception("Component cannot be null") self._lock.acquire() try: self._references.append(Reference(locator, component)) finally: self._lock.release()
python
def put(self, locator = None, component = None): """ Puts a new reference into this reference map. :param locator: a component reference to be added. :param component: a locator to find the reference by. """ if component == None: raise Exception("Component cannot be null") self._lock.acquire() try: self._references.append(Reference(locator, component)) finally: self._lock.release()
[ "def", "put", "(", "self", ",", "locator", "=", "None", ",", "component", "=", "None", ")", ":", "if", "component", "==", "None", ":", "raise", "Exception", "(", "\"Component cannot be null\"", ")", "self", ".", "_lock", ".", "acquire", "(", ")", "try", ":", "self", ".", "_references", ".", "append", "(", "Reference", "(", "locator", ",", "component", ")", ")", "finally", ":", "self", ".", "_lock", ".", "release", "(", ")" ]
Puts a new reference into this reference map. :param locator: a component reference to be added. :param component: a locator to find the reference by.
[ "Puts", "a", "new", "reference", "into", "this", "reference", "map", "." ]
22cbbb3e91e49717f65c083d36147fdb07ba9e3b
https://github.com/pip-services3-python/pip-services3-commons-python/blob/22cbbb3e91e49717f65c083d36147fdb07ba9e3b/pip_services3_commons/refer/References.py#L64-L79
238,787
pip-services3-python/pip-services3-commons-python
pip_services3_commons/refer/References.py
References.remove_all
def remove_all(self, locator): """ Removes all component references that match the specified locator. :param locator: a locator to remove reference by. :return: a list, containing all removed references. """ components = [] if locator == None: return components self._lock.acquire() try: for reference in reversed(self._references): if reference.match(locator): self._references.remove(reference) components.append(reference.get_component()) finally: self._lock.release() return components
python
def remove_all(self, locator): """ Removes all component references that match the specified locator. :param locator: a locator to remove reference by. :return: a list, containing all removed references. """ components = [] if locator == None: return components self._lock.acquire() try: for reference in reversed(self._references): if reference.match(locator): self._references.remove(reference) components.append(reference.get_component()) finally: self._lock.release() return components
[ "def", "remove_all", "(", "self", ",", "locator", ")", ":", "components", "=", "[", "]", "if", "locator", "==", "None", ":", "return", "components", "self", ".", "_lock", ".", "acquire", "(", ")", "try", ":", "for", "reference", "in", "reversed", "(", "self", ".", "_references", ")", ":", "if", "reference", ".", "match", "(", "locator", ")", ":", "self", ".", "_references", ".", "remove", "(", "reference", ")", "components", ".", "append", "(", "reference", ".", "get_component", "(", ")", ")", "finally", ":", "self", ".", "_lock", ".", "release", "(", ")", "return", "components" ]
Removes all component references that match the specified locator. :param locator: a locator to remove reference by. :return: a list, containing all removed references.
[ "Removes", "all", "component", "references", "that", "match", "the", "specified", "locator", "." ]
22cbbb3e91e49717f65c083d36147fdb07ba9e3b
https://github.com/pip-services3-python/pip-services3-commons-python/blob/22cbbb3e91e49717f65c083d36147fdb07ba9e3b/pip_services3_commons/refer/References.py#L106-L128
238,788
pip-services3-python/pip-services3-commons-python
pip_services3_commons/refer/References.py
References.get_all_locators
def get_all_locators(self): """ Gets locators for all registered component references in this reference map. :return: a list with component locators. """ locators = [] self._lock.acquire() try: for reference in self._references: locators.append(reference.get_locator()) finally: self._lock.release() return locators
python
def get_all_locators(self): """ Gets locators for all registered component references in this reference map. :return: a list with component locators. """ locators = [] self._lock.acquire() try: for reference in self._references: locators.append(reference.get_locator()) finally: self._lock.release() return locators
[ "def", "get_all_locators", "(", "self", ")", ":", "locators", "=", "[", "]", "self", ".", "_lock", ".", "acquire", "(", ")", "try", ":", "for", "reference", "in", "self", ".", "_references", ":", "locators", ".", "append", "(", "reference", ".", "get_locator", "(", ")", ")", "finally", ":", "self", ".", "_lock", ".", "release", "(", ")", "return", "locators" ]
Gets locators for all registered component references in this reference map. :return: a list with component locators.
[ "Gets", "locators", "for", "all", "registered", "component", "references", "in", "this", "reference", "map", "." ]
22cbbb3e91e49717f65c083d36147fdb07ba9e3b
https://github.com/pip-services3-python/pip-services3-commons-python/blob/22cbbb3e91e49717f65c083d36147fdb07ba9e3b/pip_services3_commons/refer/References.py#L130-L145
238,789
pip-services3-python/pip-services3-commons-python
pip_services3_commons/refer/References.py
References.get_all
def get_all(self): """ Gets all component references registered in this reference map. :return: a list with component references. """ components = [] self._lock.acquire() try: for reference in self._references: components.append(reference.get_component()) finally: self._lock.release() return components
python
def get_all(self): """ Gets all component references registered in this reference map. :return: a list with component references. """ components = [] self._lock.acquire() try: for reference in self._references: components.append(reference.get_component()) finally: self._lock.release() return components
[ "def", "get_all", "(", "self", ")", ":", "components", "=", "[", "]", "self", ".", "_lock", ".", "acquire", "(", ")", "try", ":", "for", "reference", "in", "self", ".", "_references", ":", "components", ".", "append", "(", "reference", ".", "get_component", "(", ")", ")", "finally", ":", "self", ".", "_lock", ".", "release", "(", ")", "return", "components" ]
Gets all component references registered in this reference map. :return: a list with component references.
[ "Gets", "all", "component", "references", "registered", "in", "this", "reference", "map", "." ]
22cbbb3e91e49717f65c083d36147fdb07ba9e3b
https://github.com/pip-services3-python/pip-services3-commons-python/blob/22cbbb3e91e49717f65c083d36147fdb07ba9e3b/pip_services3_commons/refer/References.py#L147-L162
238,790
pip-services3-python/pip-services3-commons-python
pip_services3_commons/refer/References.py
References.get_one_optional
def get_one_optional(self, locator): """ Gets an optional component reference that matches specified locator. :param locator: the locator to find references by. :return: a matching component reference or null if nothing was found. """ try: components = self.find(locator, False) return components[0] if len(components) > 0 else None except Exception as ex: return None
python
def get_one_optional(self, locator): """ Gets an optional component reference that matches specified locator. :param locator: the locator to find references by. :return: a matching component reference or null if nothing was found. """ try: components = self.find(locator, False) return components[0] if len(components) > 0 else None except Exception as ex: return None
[ "def", "get_one_optional", "(", "self", ",", "locator", ")", ":", "try", ":", "components", "=", "self", ".", "find", "(", "locator", ",", "False", ")", "return", "components", "[", "0", "]", "if", "len", "(", "components", ")", ">", "0", "else", "None", "except", "Exception", "as", "ex", ":", "return", "None" ]
Gets an optional component reference that matches specified locator. :param locator: the locator to find references by. :return: a matching component reference or null if nothing was found.
[ "Gets", "an", "optional", "component", "reference", "that", "matches", "specified", "locator", "." ]
22cbbb3e91e49717f65c083d36147fdb07ba9e3b
https://github.com/pip-services3-python/pip-services3-commons-python/blob/22cbbb3e91e49717f65c083d36147fdb07ba9e3b/pip_services3_commons/refer/References.py#L193-L205
238,791
pip-services3-python/pip-services3-commons-python
pip_services3_commons/refer/References.py
References.get_one_required
def get_one_required(self, locator): """ Gets a required component reference that matches specified locator. :param locator: the locator to find a reference by. :return: a matching component reference. :raises: a [[ReferenceException]] when no references found. """ components = self.find(locator, True) return components[0] if len(components) > 0 else None
python
def get_one_required(self, locator): """ Gets a required component reference that matches specified locator. :param locator: the locator to find a reference by. :return: a matching component reference. :raises: a [[ReferenceException]] when no references found. """ components = self.find(locator, True) return components[0] if len(components) > 0 else None
[ "def", "get_one_required", "(", "self", ",", "locator", ")", ":", "components", "=", "self", ".", "find", "(", "locator", ",", "True", ")", "return", "components", "[", "0", "]", "if", "len", "(", "components", ")", ">", "0", "else", "None" ]
Gets a required component reference that matches specified locator. :param locator: the locator to find a reference by. :return: a matching component reference. :raises: a [[ReferenceException]] when no references found.
[ "Gets", "a", "required", "component", "reference", "that", "matches", "specified", "locator", "." ]
22cbbb3e91e49717f65c083d36147fdb07ba9e3b
https://github.com/pip-services3-python/pip-services3-commons-python/blob/22cbbb3e91e49717f65c083d36147fdb07ba9e3b/pip_services3_commons/refer/References.py#L208-L219
238,792
zabertech/python-izaber
izaber/zconfig.py
initialize
def initialize(**kwargs): """ Loads the globally shared YAML configuration """ global config config_opts = kwargs.setdefault('config',{}) if isinstance(config_opts,basestring): config_opts = {'config_filename':config_opts} kwargs['config'] = config_opts if 'environment' in kwargs: config_opts['environment'] = kwargs['environment'] config.load_config(**config_opts) # Overlay the subconfig if kwargs.get('name'): subconfig = config.get(kwargs.get('name'),{}) config.overlay_add(subconfig) config.overlay_add(app_config)
python
def initialize(**kwargs): """ Loads the globally shared YAML configuration """ global config config_opts = kwargs.setdefault('config',{}) if isinstance(config_opts,basestring): config_opts = {'config_filename':config_opts} kwargs['config'] = config_opts if 'environment' in kwargs: config_opts['environment'] = kwargs['environment'] config.load_config(**config_opts) # Overlay the subconfig if kwargs.get('name'): subconfig = config.get(kwargs.get('name'),{}) config.overlay_add(subconfig) config.overlay_add(app_config)
[ "def", "initialize", "(", "*", "*", "kwargs", ")", ":", "global", "config", "config_opts", "=", "kwargs", ".", "setdefault", "(", "'config'", ",", "{", "}", ")", "if", "isinstance", "(", "config_opts", ",", "basestring", ")", ":", "config_opts", "=", "{", "'config_filename'", ":", "config_opts", "}", "kwargs", "[", "'config'", "]", "=", "config_opts", "if", "'environment'", "in", "kwargs", ":", "config_opts", "[", "'environment'", "]", "=", "kwargs", "[", "'environment'", "]", "config", ".", "load_config", "(", "*", "*", "config_opts", ")", "# Overlay the subconfig", "if", "kwargs", ".", "get", "(", "'name'", ")", ":", "subconfig", "=", "config", ".", "get", "(", "kwargs", ".", "get", "(", "'name'", ")", ",", "{", "}", ")", "config", ".", "overlay_add", "(", "subconfig", ")", "config", ".", "overlay_add", "(", "app_config", ")" ]
Loads the globally shared YAML configuration
[ "Loads", "the", "globally", "shared", "YAML", "configuration" ]
729bf9ef637e084c8ab3cc16c34cf659d3a79ee4
https://github.com/zabertech/python-izaber/blob/729bf9ef637e084c8ab3cc16c34cf659d3a79ee4/izaber/zconfig.py#L427-L448
238,793
zabertech/python-izaber
izaber/zconfig.py
YAMLConfig.config_amend_key_
def config_amend_key_(self,key,value): """ This will take a stringified key representation and value and load it into the configuration file for furthur usage. The good part about this method is that it doesn't clobber, only appends when keys are missing. """ cfg_i = self._cfg keys = key.split('.') last_key = keys.pop() trail = [] for e in keys: cfg_i.setdefault(e,{}) cfg_i = cfg_i[e] trail.append(e) if not isinstance(cfg_i,dict): raise Exception('.'.join(trail) + ' has conflicting dict/scalar types!') cfg_i.setdefault(last_key,value)
python
def config_amend_key_(self,key,value): """ This will take a stringified key representation and value and load it into the configuration file for furthur usage. The good part about this method is that it doesn't clobber, only appends when keys are missing. """ cfg_i = self._cfg keys = key.split('.') last_key = keys.pop() trail = [] for e in keys: cfg_i.setdefault(e,{}) cfg_i = cfg_i[e] trail.append(e) if not isinstance(cfg_i,dict): raise Exception('.'.join(trail) + ' has conflicting dict/scalar types!') cfg_i.setdefault(last_key,value)
[ "def", "config_amend_key_", "(", "self", ",", "key", ",", "value", ")", ":", "cfg_i", "=", "self", ".", "_cfg", "keys", "=", "key", ".", "split", "(", "'.'", ")", "last_key", "=", "keys", ".", "pop", "(", ")", "trail", "=", "[", "]", "for", "e", "in", "keys", ":", "cfg_i", ".", "setdefault", "(", "e", ",", "{", "}", ")", "cfg_i", "=", "cfg_i", "[", "e", "]", "trail", ".", "append", "(", "e", ")", "if", "not", "isinstance", "(", "cfg_i", ",", "dict", ")", ":", "raise", "Exception", "(", "'.'", ".", "join", "(", "trail", ")", "+", "' has conflicting dict/scalar types!'", ")", "cfg_i", ".", "setdefault", "(", "last_key", ",", "value", ")" ]
This will take a stringified key representation and value and load it into the configuration file for furthur usage. The good part about this method is that it doesn't clobber, only appends when keys are missing.
[ "This", "will", "take", "a", "stringified", "key", "representation", "and", "value", "and", "load", "it", "into", "the", "configuration", "file", "for", "furthur", "usage", ".", "The", "good", "part", "about", "this", "method", "is", "that", "it", "doesn", "t", "clobber", "only", "appends", "when", "keys", "are", "missing", "." ]
729bf9ef637e084c8ab3cc16c34cf659d3a79ee4
https://github.com/zabertech/python-izaber/blob/729bf9ef637e084c8ab3cc16c34cf659d3a79ee4/izaber/zconfig.py#L192-L208
238,794
zabertech/python-izaber
izaber/zconfig.py
YAMLConfig.config_amend_
def config_amend_(self,config_amend): """ This will take a YAML or dict configuration and load it into the configuration file for furthur usage. The good part about this method is that it doesn't clobber, only appends when keys are missing. This should provide a value in dictionary format like: { 'default': { 'togglsync': { 'dsn': 'sqlite:///zerp-toggl.db', 'default': { 'username': 'abced', 'toggl_api_key': 'arfarfarf', }, 'dev': { 'cache': False } } } OR at user's preference can also use yaml format: default: togglsync: dsn: 'sqlite:///zerp-toggl.db' default: username: 'abced' toggl_api_key: 'arfarfarf' dev: cache: False Then the code will append the key/values where they may be missing. If there is a conflict between a dict key and a value, this function will throw an exception. IMPORTANT: after making the change to the configuration, remember to save the changes with cfg.save_() """ if not isinstance(config_amend,dict): config_amend = yaml.load(config_amend) def merge_dicts(source,target,breadcrumbs=None): """ Function to update the configuration if required. Returns True if a change was made. """ changed = False if breadcrumbs is None: breadcrumbs = [] # Don't descend if we're not a dict if not isinstance(source,dict): return source # Let's start iterating over things for k,v in source.items(): # New key, simply add. if k not in target: target[k] = v changed = True continue # Not new key.... so is it a dict? elif isinstance(target[k],dict): trail = breadcrumbs+[k] if isinstance(v,dict): if merge_dicts(v,target[k],trail): changed = True else: raise Exception('.'.join(trail) + ' has conflicting dict/scalar types!') else: trail = breadcrumbs+[k] if isinstance(v,dict): raise Exception('.'.join(trail) + ' has conflicting dict/scalar types!') return changed if merge_dicts(config_amend,self._cfg): self.overlay_load() return self._cfg
python
def config_amend_(self,config_amend): """ This will take a YAML or dict configuration and load it into the configuration file for furthur usage. The good part about this method is that it doesn't clobber, only appends when keys are missing. This should provide a value in dictionary format like: { 'default': { 'togglsync': { 'dsn': 'sqlite:///zerp-toggl.db', 'default': { 'username': 'abced', 'toggl_api_key': 'arfarfarf', }, 'dev': { 'cache': False } } } OR at user's preference can also use yaml format: default: togglsync: dsn: 'sqlite:///zerp-toggl.db' default: username: 'abced' toggl_api_key: 'arfarfarf' dev: cache: False Then the code will append the key/values where they may be missing. If there is a conflict between a dict key and a value, this function will throw an exception. IMPORTANT: after making the change to the configuration, remember to save the changes with cfg.save_() """ if not isinstance(config_amend,dict): config_amend = yaml.load(config_amend) def merge_dicts(source,target,breadcrumbs=None): """ Function to update the configuration if required. Returns True if a change was made. """ changed = False if breadcrumbs is None: breadcrumbs = [] # Don't descend if we're not a dict if not isinstance(source,dict): return source # Let's start iterating over things for k,v in source.items(): # New key, simply add. if k not in target: target[k] = v changed = True continue # Not new key.... so is it a dict? elif isinstance(target[k],dict): trail = breadcrumbs+[k] if isinstance(v,dict): if merge_dicts(v,target[k],trail): changed = True else: raise Exception('.'.join(trail) + ' has conflicting dict/scalar types!') else: trail = breadcrumbs+[k] if isinstance(v,dict): raise Exception('.'.join(trail) + ' has conflicting dict/scalar types!') return changed if merge_dicts(config_amend,self._cfg): self.overlay_load() return self._cfg
[ "def", "config_amend_", "(", "self", ",", "config_amend", ")", ":", "if", "not", "isinstance", "(", "config_amend", ",", "dict", ")", ":", "config_amend", "=", "yaml", ".", "load", "(", "config_amend", ")", "def", "merge_dicts", "(", "source", ",", "target", ",", "breadcrumbs", "=", "None", ")", ":", "\"\"\"\n Function to update the configuration if required. Returns\n True if a change was made.\n \"\"\"", "changed", "=", "False", "if", "breadcrumbs", "is", "None", ":", "breadcrumbs", "=", "[", "]", "# Don't descend if we're not a dict", "if", "not", "isinstance", "(", "source", ",", "dict", ")", ":", "return", "source", "# Let's start iterating over things", "for", "k", ",", "v", "in", "source", ".", "items", "(", ")", ":", "# New key, simply add.", "if", "k", "not", "in", "target", ":", "target", "[", "k", "]", "=", "v", "changed", "=", "True", "continue", "# Not new key.... so is it a dict?", "elif", "isinstance", "(", "target", "[", "k", "]", ",", "dict", ")", ":", "trail", "=", "breadcrumbs", "+", "[", "k", "]", "if", "isinstance", "(", "v", ",", "dict", ")", ":", "if", "merge_dicts", "(", "v", ",", "target", "[", "k", "]", ",", "trail", ")", ":", "changed", "=", "True", "else", ":", "raise", "Exception", "(", "'.'", ".", "join", "(", "trail", ")", "+", "' has conflicting dict/scalar types!'", ")", "else", ":", "trail", "=", "breadcrumbs", "+", "[", "k", "]", "if", "isinstance", "(", "v", ",", "dict", ")", ":", "raise", "Exception", "(", "'.'", ".", "join", "(", "trail", ")", "+", "' has conflicting dict/scalar types!'", ")", "return", "changed", "if", "merge_dicts", "(", "config_amend", ",", "self", ".", "_cfg", ")", ":", "self", ".", "overlay_load", "(", ")", "return", "self", ".", "_cfg" ]
This will take a YAML or dict configuration and load it into the configuration file for furthur usage. The good part about this method is that it doesn't clobber, only appends when keys are missing. This should provide a value in dictionary format like: { 'default': { 'togglsync': { 'dsn': 'sqlite:///zerp-toggl.db', 'default': { 'username': 'abced', 'toggl_api_key': 'arfarfarf', }, 'dev': { 'cache': False } } } OR at user's preference can also use yaml format: default: togglsync: dsn: 'sqlite:///zerp-toggl.db' default: username: 'abced' toggl_api_key: 'arfarfarf' dev: cache: False Then the code will append the key/values where they may be missing. If there is a conflict between a dict key and a value, this function will throw an exception. IMPORTANT: after making the change to the configuration, remember to save the changes with cfg.save_()
[ "This", "will", "take", "a", "YAML", "or", "dict", "configuration", "and", "load", "it", "into", "the", "configuration", "file", "for", "furthur", "usage", ".", "The", "good", "part", "about", "this", "method", "is", "that", "it", "doesn", "t", "clobber", "only", "appends", "when", "keys", "are", "missing", "." ]
729bf9ef637e084c8ab3cc16c34cf659d3a79ee4
https://github.com/zabertech/python-izaber/blob/729bf9ef637e084c8ab3cc16c34cf659d3a79ee4/izaber/zconfig.py#L210-L299
238,795
rvswift/EB
EB/builder/slowheuristic/slowheuristic_io.py
ParseArgs.get_string
def get_string(self, input_string): """ Return string type user input """ if input_string in ('--input', '--outname', '--framework'): # was the flag set? try: index = self.args.index(input_string) + 1 except ValueError: # it wasn't, so if it's required, exit if input_string in self.required: print("\n {flag} is required".format(input_string)) print_short_help() sys.exit(1) # it wasn't, if its optional, return the default else: return None # the flag was set, so check if a value was set, otherwise exit try: if self.args[index] in self.flags: print("\n {flag} was set but a value was not specified".format(flag=input_string)) print_short_help() sys.exit(1) except IndexError: print("\n {flag} was set but a value was not specified".format(input_string)) print_short_help() sys.exit(1) # a value was set, so check and assign the appropriate value or exit if input_string == '--input': return os.path.abspath(self.args[index]) elif input_string == '--outname': return format(self.args[index])
python
def get_string(self, input_string): """ Return string type user input """ if input_string in ('--input', '--outname', '--framework'): # was the flag set? try: index = self.args.index(input_string) + 1 except ValueError: # it wasn't, so if it's required, exit if input_string in self.required: print("\n {flag} is required".format(input_string)) print_short_help() sys.exit(1) # it wasn't, if its optional, return the default else: return None # the flag was set, so check if a value was set, otherwise exit try: if self.args[index] in self.flags: print("\n {flag} was set but a value was not specified".format(flag=input_string)) print_short_help() sys.exit(1) except IndexError: print("\n {flag} was set but a value was not specified".format(input_string)) print_short_help() sys.exit(1) # a value was set, so check and assign the appropriate value or exit if input_string == '--input': return os.path.abspath(self.args[index]) elif input_string == '--outname': return format(self.args[index])
[ "def", "get_string", "(", "self", ",", "input_string", ")", ":", "if", "input_string", "in", "(", "'--input'", ",", "'--outname'", ",", "'--framework'", ")", ":", "# was the flag set?", "try", ":", "index", "=", "self", ".", "args", ".", "index", "(", "input_string", ")", "+", "1", "except", "ValueError", ":", "# it wasn't, so if it's required, exit", "if", "input_string", "in", "self", ".", "required", ":", "print", "(", "\"\\n {flag} is required\"", ".", "format", "(", "input_string", ")", ")", "print_short_help", "(", ")", "sys", ".", "exit", "(", "1", ")", "# it wasn't, if its optional, return the default", "else", ":", "return", "None", "# the flag was set, so check if a value was set, otherwise exit", "try", ":", "if", "self", ".", "args", "[", "index", "]", "in", "self", ".", "flags", ":", "print", "(", "\"\\n {flag} was set but a value was not specified\"", ".", "format", "(", "flag", "=", "input_string", ")", ")", "print_short_help", "(", ")", "sys", ".", "exit", "(", "1", ")", "except", "IndexError", ":", "print", "(", "\"\\n {flag} was set but a value was not specified\"", ".", "format", "(", "input_string", ")", ")", "print_short_help", "(", ")", "sys", ".", "exit", "(", "1", ")", "# a value was set, so check and assign the appropriate value or exit", "if", "input_string", "==", "'--input'", ":", "return", "os", ".", "path", ".", "abspath", "(", "self", ".", "args", "[", "index", "]", ")", "elif", "input_string", "==", "'--outname'", ":", "return", "format", "(", "self", ".", "args", "[", "index", "]", ")" ]
Return string type user input
[ "Return", "string", "type", "user", "input" ]
341880b79faf8147dc9fa6e90438531cd09fabcc
https://github.com/rvswift/EB/blob/341880b79faf8147dc9fa6e90438531cd09fabcc/EB/builder/slowheuristic/slowheuristic_io.py#L93-L128
238,796
shoeffner/pandoc-source-exec
pandoc_source_exec.py
select_executor
def select_executor(elem, doc): """Determines the executor for the code in `elem.text`. The elem attributes and classes select the executor in this order (highest to lowest): - custom commands (cmd=...) - runas (runas=...) takes a key for the executors - first element class (.class) determines language and thus executor Args: elem The AST element. doc The document. Returns: The command to execute code. """ executor = EXECUTORS['default'] if 'cmd' in elem.attributes.keys(): executor = elem.attributes['cmd'] elif 'runas' in elem.attributes.keys(): executor = EXECUTORS[elem.attributes['runas']] elif elem.classes[0] != 'exec': executor = EXECUTORS[elem.classes[0]] return executor
python
def select_executor(elem, doc): """Determines the executor for the code in `elem.text`. The elem attributes and classes select the executor in this order (highest to lowest): - custom commands (cmd=...) - runas (runas=...) takes a key for the executors - first element class (.class) determines language and thus executor Args: elem The AST element. doc The document. Returns: The command to execute code. """ executor = EXECUTORS['default'] if 'cmd' in elem.attributes.keys(): executor = elem.attributes['cmd'] elif 'runas' in elem.attributes.keys(): executor = EXECUTORS[elem.attributes['runas']] elif elem.classes[0] != 'exec': executor = EXECUTORS[elem.classes[0]] return executor
[ "def", "select_executor", "(", "elem", ",", "doc", ")", ":", "executor", "=", "EXECUTORS", "[", "'default'", "]", "if", "'cmd'", "in", "elem", ".", "attributes", ".", "keys", "(", ")", ":", "executor", "=", "elem", ".", "attributes", "[", "'cmd'", "]", "elif", "'runas'", "in", "elem", ".", "attributes", ".", "keys", "(", ")", ":", "executor", "=", "EXECUTORS", "[", "elem", ".", "attributes", "[", "'runas'", "]", "]", "elif", "elem", ".", "classes", "[", "0", "]", "!=", "'exec'", ":", "executor", "=", "EXECUTORS", "[", "elem", ".", "classes", "[", "0", "]", "]", "return", "executor" ]
Determines the executor for the code in `elem.text`. The elem attributes and classes select the executor in this order (highest to lowest): - custom commands (cmd=...) - runas (runas=...) takes a key for the executors - first element class (.class) determines language and thus executor Args: elem The AST element. doc The document. Returns: The command to execute code.
[ "Determines", "the", "executor", "for", "the", "code", "in", "elem", ".", "text", "." ]
9a13b9054d629a60b63196a906fafe2673722d13
https://github.com/shoeffner/pandoc-source-exec/blob/9a13b9054d629a60b63196a906fafe2673722d13/pandoc_source_exec.py#L32-L57
238,797
shoeffner/pandoc-source-exec
pandoc_source_exec.py
execute_code_block
def execute_code_block(elem, doc): """Executes a code block by passing it to the executor. Args: elem The AST element. doc The document. Returns: The output of the command. """ command = select_executor(elem, doc).split(' ') code = elem.text if 'plt' in elem.attributes or 'plt' in elem.classes: code = save_plot(code, elem) command.append(code) if 'args' in elem.attributes: for arg in elem.attributes['args'].split(): command.append(arg) cwd = elem.attributes['wd'] if 'wd' in elem.attributes else None return subprocess.run(command, encoding='utf8', stdout=subprocess.PIPE, stderr=subprocess.STDOUT, cwd=cwd).stdout
python
def execute_code_block(elem, doc): """Executes a code block by passing it to the executor. Args: elem The AST element. doc The document. Returns: The output of the command. """ command = select_executor(elem, doc).split(' ') code = elem.text if 'plt' in elem.attributes or 'plt' in elem.classes: code = save_plot(code, elem) command.append(code) if 'args' in elem.attributes: for arg in elem.attributes['args'].split(): command.append(arg) cwd = elem.attributes['wd'] if 'wd' in elem.attributes else None return subprocess.run(command, encoding='utf8', stdout=subprocess.PIPE, stderr=subprocess.STDOUT, cwd=cwd).stdout
[ "def", "execute_code_block", "(", "elem", ",", "doc", ")", ":", "command", "=", "select_executor", "(", "elem", ",", "doc", ")", ".", "split", "(", "' '", ")", "code", "=", "elem", ".", "text", "if", "'plt'", "in", "elem", ".", "attributes", "or", "'plt'", "in", "elem", ".", "classes", ":", "code", "=", "save_plot", "(", "code", ",", "elem", ")", "command", ".", "append", "(", "code", ")", "if", "'args'", "in", "elem", ".", "attributes", ":", "for", "arg", "in", "elem", ".", "attributes", "[", "'args'", "]", ".", "split", "(", ")", ":", "command", ".", "append", "(", "arg", ")", "cwd", "=", "elem", ".", "attributes", "[", "'wd'", "]", "if", "'wd'", "in", "elem", ".", "attributes", "else", "None", "return", "subprocess", ".", "run", "(", "command", ",", "encoding", "=", "'utf8'", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "stderr", "=", "subprocess", ".", "STDOUT", ",", "cwd", "=", "cwd", ")", ".", "stdout" ]
Executes a code block by passing it to the executor. Args: elem The AST element. doc The document. Returns: The output of the command.
[ "Executes", "a", "code", "block", "by", "passing", "it", "to", "the", "executor", "." ]
9a13b9054d629a60b63196a906fafe2673722d13
https://github.com/shoeffner/pandoc-source-exec/blob/9a13b9054d629a60b63196a906fafe2673722d13/pandoc_source_exec.py#L60-L85
238,798
shoeffner/pandoc-source-exec
pandoc_source_exec.py
execute_interactive_code
def execute_interactive_code(elem, doc): """Executes code blocks for a python shell. Parses the code in `elem.text` into blocks and executes them. Args: elem The AST element. doc The document. Return: The code with inline results. """ code_lines = [l[4:] for l in elem.text.split('\n')] code_blocks = [[code_lines[0]]] for line in code_lines[1:]: if line.startswith(' ') or line == '': code_blocks[-1].append(line) else: code_blocks.append([line]) final_code = [] try: child = replwrap.REPLWrapper("python", ">>> ", None) except NameError: pf.debug('Can not run interactive session. No output produced ' + '(Code was:\n{!s}\n)' .format(elem)) pf.debug('Please pip install pexpect.') return '' for code_block in code_blocks: result = child.run_command('\n'.join(code_block) + '\n').rstrip('\r\n') final_code += [('>>> ' if i == 0 else '... ') + l for i, l in enumerate(code_block)] if result: final_code += [r for r in result.split('\n') if r.strip() not in code_block] return '\n'.join(final_code)
python
def execute_interactive_code(elem, doc): """Executes code blocks for a python shell. Parses the code in `elem.text` into blocks and executes them. Args: elem The AST element. doc The document. Return: The code with inline results. """ code_lines = [l[4:] for l in elem.text.split('\n')] code_blocks = [[code_lines[0]]] for line in code_lines[1:]: if line.startswith(' ') or line == '': code_blocks[-1].append(line) else: code_blocks.append([line]) final_code = [] try: child = replwrap.REPLWrapper("python", ">>> ", None) except NameError: pf.debug('Can not run interactive session. No output produced ' + '(Code was:\n{!s}\n)' .format(elem)) pf.debug('Please pip install pexpect.') return '' for code_block in code_blocks: result = child.run_command('\n'.join(code_block) + '\n').rstrip('\r\n') final_code += [('>>> ' if i == 0 else '... ') + l for i, l in enumerate(code_block)] if result: final_code += [r for r in result.split('\n') if r.strip() not in code_block] return '\n'.join(final_code)
[ "def", "execute_interactive_code", "(", "elem", ",", "doc", ")", ":", "code_lines", "=", "[", "l", "[", "4", ":", "]", "for", "l", "in", "elem", ".", "text", ".", "split", "(", "'\\n'", ")", "]", "code_blocks", "=", "[", "[", "code_lines", "[", "0", "]", "]", "]", "for", "line", "in", "code_lines", "[", "1", ":", "]", ":", "if", "line", ".", "startswith", "(", "' '", ")", "or", "line", "==", "''", ":", "code_blocks", "[", "-", "1", "]", ".", "append", "(", "line", ")", "else", ":", "code_blocks", ".", "append", "(", "[", "line", "]", ")", "final_code", "=", "[", "]", "try", ":", "child", "=", "replwrap", ".", "REPLWrapper", "(", "\"python\"", ",", "\">>> \"", ",", "None", ")", "except", "NameError", ":", "pf", ".", "debug", "(", "'Can not run interactive session. No output produced '", "+", "'(Code was:\\n{!s}\\n)'", ".", "format", "(", "elem", ")", ")", "pf", ".", "debug", "(", "'Please pip install pexpect.'", ")", "return", "''", "for", "code_block", "in", "code_blocks", ":", "result", "=", "child", ".", "run_command", "(", "'\\n'", ".", "join", "(", "code_block", ")", "+", "'\\n'", ")", ".", "rstrip", "(", "'\\r\\n'", ")", "final_code", "+=", "[", "(", "'>>> '", "if", "i", "==", "0", "else", "'... '", ")", "+", "l", "for", "i", ",", "l", "in", "enumerate", "(", "code_block", ")", "]", "if", "result", ":", "final_code", "+=", "[", "r", "for", "r", "in", "result", ".", "split", "(", "'\\n'", ")", "if", "r", ".", "strip", "(", ")", "not", "in", "code_block", "]", "return", "'\\n'", ".", "join", "(", "final_code", ")" ]
Executes code blocks for a python shell. Parses the code in `elem.text` into blocks and executes them. Args: elem The AST element. doc The document. Return: The code with inline results.
[ "Executes", "code", "blocks", "for", "a", "python", "shell", "." ]
9a13b9054d629a60b63196a906fafe2673722d13
https://github.com/shoeffner/pandoc-source-exec/blob/9a13b9054d629a60b63196a906fafe2673722d13/pandoc_source_exec.py#L88-L126
238,799
shoeffner/pandoc-source-exec
pandoc_source_exec.py
read_file
def read_file(filename): """Reads a file which matches the pattern `filename`. Args: filename The filename pattern Returns: The file content or the empty string, if the file is not found. """ hits = glob.glob('**/{}'.format(filename), recursive=True) if not len(hits): pf.debug('No file "{}" found.'.format(filename)) return '' elif len(hits) > 1: pf.debug('File pattern "{}" ambiguous. Using first.'.format(filename)) with open(hits[0], 'r') as f: return f.read()
python
def read_file(filename): """Reads a file which matches the pattern `filename`. Args: filename The filename pattern Returns: The file content or the empty string, if the file is not found. """ hits = glob.glob('**/{}'.format(filename), recursive=True) if not len(hits): pf.debug('No file "{}" found.'.format(filename)) return '' elif len(hits) > 1: pf.debug('File pattern "{}" ambiguous. Using first.'.format(filename)) with open(hits[0], 'r') as f: return f.read()
[ "def", "read_file", "(", "filename", ")", ":", "hits", "=", "glob", ".", "glob", "(", "'**/{}'", ".", "format", "(", "filename", ")", ",", "recursive", "=", "True", ")", "if", "not", "len", "(", "hits", ")", ":", "pf", ".", "debug", "(", "'No file \"{}\" found.'", ".", "format", "(", "filename", ")", ")", "return", "''", "elif", "len", "(", "hits", ")", ">", "1", ":", "pf", ".", "debug", "(", "'File pattern \"{}\" ambiguous. Using first.'", ".", "format", "(", "filename", ")", ")", "with", "open", "(", "hits", "[", "0", "]", ",", "'r'", ")", "as", "f", ":", "return", "f", ".", "read", "(", ")" ]
Reads a file which matches the pattern `filename`. Args: filename The filename pattern Returns: The file content or the empty string, if the file is not found.
[ "Reads", "a", "file", "which", "matches", "the", "pattern", "filename", "." ]
9a13b9054d629a60b63196a906fafe2673722d13
https://github.com/shoeffner/pandoc-source-exec/blob/9a13b9054d629a60b63196a906fafe2673722d13/pandoc_source_exec.py#L129-L146