repo
stringlengths
7
55
path
stringlengths
4
223
func_name
stringlengths
1
134
original_string
stringlengths
75
104k
language
stringclasses
1 value
code
stringlengths
75
104k
code_tokens
listlengths
19
28.4k
docstring
stringlengths
1
46.9k
docstring_tokens
listlengths
1
1.97k
sha
stringlengths
40
40
url
stringlengths
87
315
partition
stringclasses
3 values
summary
stringlengths
4
350
rsgalloway/grit
grit/repo/version.py
Item.versions
def versions(self, rev=None, index=None): """:return: List of Versions for this Item""" raise NotImplementedError _revisions = [line.split()[0] for line in self.log.split('\n') if line] _versions = [Version(self.obj.repo.commit(r)) for r in _revisions if rev is None or r.startswith(rev)]...
python
def versions(self, rev=None, index=None): """:return: List of Versions for this Item""" raise NotImplementedError _revisions = [line.split()[0] for line in self.log.split('\n') if line] _versions = [Version(self.obj.repo.commit(r)) for r in _revisions if rev is None or r.startswith(rev)]...
[ "def", "versions", "(", "self", ",", "rev", "=", "None", ",", "index", "=", "None", ")", ":", "raise", "NotImplementedError", "_revisions", "=", "[", "line", ".", "split", "(", ")", "[", "0", "]", "for", "line", "in", "self", ".", "log", ".", "spli...
:return: List of Versions for this Item
[ ":", "return", ":", "List", "of", "Versions", "for", "this", "Item" ]
e6434ad8a1f4ac5d0903ebad630c81f8a5164d78
https://github.com/rsgalloway/grit/blob/e6434ad8a1f4ac5d0903ebad630c81f8a5164d78/grit/repo/version.py#L224-L231
train
Return a list of Versions for this Item
rsgalloway/grit
grit/repo/version.py
Version.save
def save(self, message): """ Add version to repo object store, set repo head to version sha. :param message: Message string. """ self.commit.message = message self.commit.tree = self.tree #TODO: store new blobs only for item in self.tree.items(): ...
python
def save(self, message): """ Add version to repo object store, set repo head to version sha. :param message: Message string. """ self.commit.message = message self.commit.tree = self.tree #TODO: store new blobs only for item in self.tree.items(): ...
[ "def", "save", "(", "self", ",", "message", ")", ":", "self", ".", "commit", ".", "message", "=", "message", "self", ".", "commit", ".", "tree", "=", "self", ".", "tree", "#TODO: store new blobs only", "for", "item", "in", "self", ".", "tree", ".", "it...
Add version to repo object store, set repo head to version sha. :param message: Message string.
[ "Add", "version", "to", "repo", "object", "store", "set", "repo", "head", "to", "version", "sha", "." ]
e6434ad8a1f4ac5d0903ebad630c81f8a5164d78
https://github.com/rsgalloway/grit/blob/e6434ad8a1f4ac5d0903ebad630c81f8a5164d78/grit/repo/version.py#L336-L351
train
Save the current tree and tree to the object store.
rsgalloway/grit
grit/repo/version.py
Version.new
def new(self, repo): """ Create a new version of a repo.Local object. :param repo: Instance of repo.Local. :return: New Version instance. """ #TODO: subclass Commit, pass parent as init param try: # create new commit instance and set metadata ...
python
def new(self, repo): """ Create a new version of a repo.Local object. :param repo: Instance of repo.Local. :return: New Version instance. """ #TODO: subclass Commit, pass parent as init param try: # create new commit instance and set metadata ...
[ "def", "new", "(", "self", ",", "repo", ")", ":", "#TODO: subclass Commit, pass parent as init param", "try", ":", "# create new commit instance and set metadata", "commit", "=", "Commit", "(", ")", "author", "=", "os", ".", "environ", ".", "get", "(", "'USER'", "...
Create a new version of a repo.Local object. :param repo: Instance of repo.Local. :return: New Version instance.
[ "Create", "a", "new", "version", "of", "a", "repo", ".", "Local", "object", "." ]
e6434ad8a1f4ac5d0903ebad630c81f8a5164d78
https://github.com/rsgalloway/grit/blob/e6434ad8a1f4ac5d0903ebad630c81f8a5164d78/grit/repo/version.py#L354-L393
train
Create a new version of a repo. Local object.
rsgalloway/grit
grit/cmd/cli.py
confirm
def confirm(prompt=None, resp=False): """ Prompts user for confirmation. :param prompt: String to display to user. :param resp: Default response value. :return: Boolean response from user, or default value. """ if prompt is None: prompt = 'Confirm' if resp: prompt = '%...
python
def confirm(prompt=None, resp=False): """ Prompts user for confirmation. :param prompt: String to display to user. :param resp: Default response value. :return: Boolean response from user, or default value. """ if prompt is None: prompt = 'Confirm' if resp: prompt = '%...
[ "def", "confirm", "(", "prompt", "=", "None", ",", "resp", "=", "False", ")", ":", "if", "prompt", "is", "None", ":", "prompt", "=", "'Confirm'", "if", "resp", ":", "prompt", "=", "'%s [%s]|%s: '", "%", "(", "prompt", ",", "'y'", ",", "'n'", ")", "...
Prompts user for confirmation. :param prompt: String to display to user. :param resp: Default response value. :return: Boolean response from user, or default value.
[ "Prompts", "user", "for", "confirmation", "." ]
e6434ad8a1f4ac5d0903ebad630c81f8a5164d78
https://github.com/rsgalloway/grit/blob/e6434ad8a1f4ac5d0903ebad630c81f8a5164d78/grit/cmd/cli.py#L17-L44
train
Prompts user for confirmation.
rsgalloway/grit
grit/cmd/cli.py
prompt
def prompt(name, default): """ Prompts user for raw input. :return: Raw input value from user. """ value = raw_input('%s [%s]: ' %(name, default)) if not value: value = default return value
python
def prompt(name, default): """ Prompts user for raw input. :return: Raw input value from user. """ value = raw_input('%s [%s]: ' %(name, default)) if not value: value = default return value
[ "def", "prompt", "(", "name", ",", "default", ")", ":", "value", "=", "raw_input", "(", "'%s [%s]: '", "%", "(", "name", ",", "default", ")", ")", "if", "not", "value", ":", "value", "=", "default", "return", "value" ]
Prompts user for raw input. :return: Raw input value from user.
[ "Prompts", "user", "for", "raw", "input", "." ]
e6434ad8a1f4ac5d0903ebad630c81f8a5164d78
https://github.com/rsgalloway/grit/blob/e6434ad8a1f4ac5d0903ebad630c81f8a5164d78/grit/cmd/cli.py#L46-L55
train
Prompts user for raw input.
rsgalloway/grit
grit/cmd/cli.py
new
def new(url): """ Creates a new Repo class instance at url. :param url: URL of new repo :return: new Repo class instance. """ from grit import Repo return Repo.new(url=url, bare=True)
python
def new(url): """ Creates a new Repo class instance at url. :param url: URL of new repo :return: new Repo class instance. """ from grit import Repo return Repo.new(url=url, bare=True)
[ "def", "new", "(", "url", ")", ":", "from", "grit", "import", "Repo", "return", "Repo", ".", "new", "(", "url", "=", "url", ",", "bare", "=", "True", ")" ]
Creates a new Repo class instance at url. :param url: URL of new repo :return: new Repo class instance.
[ "Creates", "a", "new", "Repo", "class", "instance", "at", "url", "." ]
e6434ad8a1f4ac5d0903ebad630c81f8a5164d78
https://github.com/rsgalloway/grit/blob/e6434ad8a1f4ac5d0903ebad630c81f8a5164d78/grit/cmd/cli.py#L57-L66
train
Creates a new Repo class instance at url.
rsgalloway/grit
grit/cmd/cli.py
checkout
def checkout(url, version=None): """ Checks out latest version of item or repository. :param url: URL of repo or item to check out. :param version: Version number to check out. """ from grit import Repo r = Repo(url) def _write(item): log.debug('writing: %s' % item.name) ...
python
def checkout(url, version=None): """ Checks out latest version of item or repository. :param url: URL of repo or item to check out. :param version: Version number to check out. """ from grit import Repo r = Repo(url) def _write(item): log.debug('writing: %s' % item.name) ...
[ "def", "checkout", "(", "url", ",", "version", "=", "None", ")", ":", "from", "grit", "import", "Repo", "r", "=", "Repo", "(", "url", ")", "def", "_write", "(", "item", ")", ":", "log", ".", "debug", "(", "'writing: %s'", "%", "item", ".", "name", ...
Checks out latest version of item or repository. :param url: URL of repo or item to check out. :param version: Version number to check out.
[ "Checks", "out", "latest", "version", "of", "item", "or", "repository", "." ]
e6434ad8a1f4ac5d0903ebad630c81f8a5164d78
https://github.com/rsgalloway/grit/blob/e6434ad8a1f4ac5d0903ebad630c81f8a5164d78/grit/cmd/cli.py#L68-L105
train
Checks out latest version of item or repository.
rsgalloway/grit
grit/cmd/cli.py
checkin
def checkin(url, files, message=None): """ Check in files to a repository. :param url: URL of repo to check files into. :param message: Optional commit message. """ from grit import Repo, Item r = Repo(url) if not files: raise GritError('No files') def _write(path): ...
python
def checkin(url, files, message=None): """ Check in files to a repository. :param url: URL of repo to check files into. :param message: Optional commit message. """ from grit import Repo, Item r = Repo(url) if not files: raise GritError('No files') def _write(path): ...
[ "def", "checkin", "(", "url", ",", "files", ",", "message", "=", "None", ")", ":", "from", "grit", "import", "Repo", ",", "Item", "r", "=", "Repo", "(", "url", ")", "if", "not", "files", ":", "raise", "GritError", "(", "'No files'", ")", "def", "_w...
Check in files to a repository. :param url: URL of repo to check files into. :param message: Optional commit message.
[ "Check", "in", "files", "to", "a", "repository", "." ]
e6434ad8a1f4ac5d0903ebad630c81f8a5164d78
https://github.com/rsgalloway/grit/blob/e6434ad8a1f4ac5d0903ebad630c81f8a5164d78/grit/cmd/cli.py#L107-L140
train
Check in files to a repository.
transifex/transifex-python-library
txlib/api/base.py
BaseModel.get
def get(cls, **kwargs): """Retrieve an object by making a GET request to Transifex. Each value in `kwargs` that corresponds to a field defined in `self.url_fields` will be used in the URL path of the request, so that a particular entry of this model is identified and retrieved. ...
python
def get(cls, **kwargs): """Retrieve an object by making a GET request to Transifex. Each value in `kwargs` that corresponds to a field defined in `self.url_fields` will be used in the URL path of the request, so that a particular entry of this model is identified and retrieved. ...
[ "def", "get", "(", "cls", ",", "*", "*", "kwargs", ")", ":", "fields", "=", "{", "}", "for", "field", "in", "cls", ".", "url_fields", ":", "value", "=", "kwargs", ".", "pop", "(", "field", ",", "None", ")", "if", "value", "is", "None", ":", "cl...
Retrieve an object by making a GET request to Transifex. Each value in `kwargs` that corresponds to a field defined in `self.url_fields` will be used in the URL path of the request, so that a particular entry of this model is identified and retrieved. Raises: Attrib...
[ "Retrieve", "an", "object", "by", "making", "a", "GET", "request", "to", "Transifex", "." ]
9fea86b718973de35ccca6d54bd1f445c9632406
https://github.com/transifex/transifex-python-library/blob/9fea86b718973de35ccca6d54bd1f445c9632406/txlib/api/base.py#L109-L139
train
Retrieve an object from Transifex by making a GET request to Transifex.
transifex/transifex-python-library
txlib/api/base.py
BaseModel.save
def save(self, **fields): """Save the instance to the remote Transifex server. If it was pre-populated, it updates the instance on the server, otherwise it creates a new object. Any values given in `fields` will be attempted to be saved on the object. The same goes for any othe...
python
def save(self, **fields): """Save the instance to the remote Transifex server. If it was pre-populated, it updates the instance on the server, otherwise it creates a new object. Any values given in `fields` will be attempted to be saved on the object. The same goes for any othe...
[ "def", "save", "(", "self", ",", "*", "*", "fields", ")", ":", "for", "field", "in", "fields", ":", "if", "field", "in", "self", ".", "writable_fields", ":", "setattr", "(", "self", ",", "field", ",", "fields", "[", "field", "]", ")", "else", ":", ...
Save the instance to the remote Transifex server. If it was pre-populated, it updates the instance on the server, otherwise it creates a new object. Any values given in `fields` will be attempted to be saved on the object. The same goes for any other values already set to the o...
[ "Save", "the", "instance", "to", "the", "remote", "Transifex", "server", "." ]
9fea86b718973de35ccca6d54bd1f445c9632406
https://github.com/transifex/transifex-python-library/blob/9fea86b718973de35ccca6d54bd1f445c9632406/txlib/api/base.py#L213-L236
train
Save the instance to the remote Transifex server.
transifex/transifex-python-library
txlib/api/base.py
BaseModel._get
def _get(self, **kwargs): """Get the resource from a remote Transifex server.""" path = self._construct_path_to_item() return self._http.get(path)
python
def _get(self, **kwargs): """Get the resource from a remote Transifex server.""" path = self._construct_path_to_item() return self._http.get(path)
[ "def", "_get", "(", "self", ",", "*", "*", "kwargs", ")", ":", "path", "=", "self", ".", "_construct_path_to_item", "(", ")", "return", "self", ".", "_http", ".", "get", "(", "path", ")" ]
Get the resource from a remote Transifex server.
[ "Get", "the", "resource", "from", "a", "remote", "Transifex", "server", "." ]
9fea86b718973de35ccca6d54bd1f445c9632406
https://github.com/transifex/transifex-python-library/blob/9fea86b718973de35ccca6d54bd1f445c9632406/txlib/api/base.py#L246-L249
train
Get the resource from a remote Transifex server.
transifex/transifex-python-library
txlib/api/base.py
BaseModel._create
def _create(self, **kwargs): """Create a resource in the remote Transifex server.""" path = self._construct_path_to_collection() # Use the fields for which we have values for field in self.writable_fields: try: value = getattr(self, field) kwa...
python
def _create(self, **kwargs): """Create a resource in the remote Transifex server.""" path = self._construct_path_to_collection() # Use the fields for which we have values for field in self.writable_fields: try: value = getattr(self, field) kwa...
[ "def", "_create", "(", "self", ",", "*", "*", "kwargs", ")", ":", "path", "=", "self", ".", "_construct_path_to_collection", "(", ")", "# Use the fields for which we have values", "for", "field", "in", "self", ".", "writable_fields", ":", "try", ":", "value", ...
Create a resource in the remote Transifex server.
[ "Create", "a", "resource", "in", "the", "remote", "Transifex", "server", "." ]
9fea86b718973de35ccca6d54bd1f445c9632406
https://github.com/transifex/transifex-python-library/blob/9fea86b718973de35ccca6d54bd1f445c9632406/txlib/api/base.py#L251-L262
train
Create a resource in the remote Transifex server.
transifex/transifex-python-library
txlib/api/base.py
BaseModel._update
def _update(self, **kwargs): """Update a resource in a remote Transifex server.""" path = self._construct_path_to_item() if not kwargs: return return self._http.put(path, json.dumps(kwargs))
python
def _update(self, **kwargs): """Update a resource in a remote Transifex server.""" path = self._construct_path_to_item() if not kwargs: return return self._http.put(path, json.dumps(kwargs))
[ "def", "_update", "(", "self", ",", "*", "*", "kwargs", ")", ":", "path", "=", "self", ".", "_construct_path_to_item", "(", ")", "if", "not", "kwargs", ":", "return", "return", "self", ".", "_http", ".", "put", "(", "path", ",", "json", ".", "dumps",...
Update a resource in a remote Transifex server.
[ "Update", "a", "resource", "in", "a", "remote", "Transifex", "server", "." ]
9fea86b718973de35ccca6d54bd1f445c9632406
https://github.com/transifex/transifex-python-library/blob/9fea86b718973de35ccca6d54bd1f445c9632406/txlib/api/base.py#L264-L269
train
Update a resource in a remote Transifex server.
transifex/transifex-python-library
txlib/api/base.py
BaseModel._delete
def _delete(self, **kwargs): """Delete a resource from a remote Transifex server.""" path = self._construct_path_to_item() return self._http.delete(path)
python
def _delete(self, **kwargs): """Delete a resource from a remote Transifex server.""" path = self._construct_path_to_item() return self._http.delete(path)
[ "def", "_delete", "(", "self", ",", "*", "*", "kwargs", ")", ":", "path", "=", "self", ".", "_construct_path_to_item", "(", ")", "return", "self", ".", "_http", ".", "delete", "(", "path", ")" ]
Delete a resource from a remote Transifex server.
[ "Delete", "a", "resource", "from", "a", "remote", "Transifex", "server", "." ]
9fea86b718973de35ccca6d54bd1f445c9632406
https://github.com/transifex/transifex-python-library/blob/9fea86b718973de35ccca6d54bd1f445c9632406/txlib/api/base.py#L271-L274
train
Delete a resource from a remote Transifex server.
transifex/transifex-python-library
txlib/api/base.py
BaseModel.get_url_parameters
def get_url_parameters(self): """Create a dictionary of parameters used in URLs for this model.""" url_fields = {} for field in self.url_fields: url_fields[field] = getattr(self, field) return url_fields
python
def get_url_parameters(self): """Create a dictionary of parameters used in URLs for this model.""" url_fields = {} for field in self.url_fields: url_fields[field] = getattr(self, field) return url_fields
[ "def", "get_url_parameters", "(", "self", ")", ":", "url_fields", "=", "{", "}", "for", "field", "in", "self", ".", "url_fields", ":", "url_fields", "[", "field", "]", "=", "getattr", "(", "self", ",", "field", ")", "return", "url_fields" ]
Create a dictionary of parameters used in URLs for this model.
[ "Create", "a", "dictionary", "of", "parameters", "used", "in", "URLs", "for", "this", "model", "." ]
9fea86b718973de35ccca6d54bd1f445c9632406
https://github.com/transifex/transifex-python-library/blob/9fea86b718973de35ccca6d54bd1f445c9632406/txlib/api/base.py#L285-L290
train
Create a dictionary of parameters used in URLs for this model.
transifex/transifex-python-library
txlib/api/base.py
BaseModel._handle_wrong_field
def _handle_wrong_field(cls, field_name, field_type): """Raise an exception whenever an invalid attribute with the given name was attempted to be set to or retrieved from this model class. Assumes that the given field is invalid, without making any checks. Also adds an entry to...
python
def _handle_wrong_field(cls, field_name, field_type): """Raise an exception whenever an invalid attribute with the given name was attempted to be set to or retrieved from this model class. Assumes that the given field is invalid, without making any checks. Also adds an entry to...
[ "def", "_handle_wrong_field", "(", "cls", ",", "field_name", ",", "field_type", ")", ":", "if", "field_type", "==", "ATTR_TYPE_READ", ":", "field_type", "=", "'readable'", "elif", "field_type", "==", "ATTR_TYPE_WRITE", ":", "field_type", "=", "'writable'", "elif",...
Raise an exception whenever an invalid attribute with the given name was attempted to be set to or retrieved from this model class. Assumes that the given field is invalid, without making any checks. Also adds an entry to the logs.
[ "Raise", "an", "exception", "whenever", "an", "invalid", "attribute", "with", "the", "given", "name", "was", "attempted", "to", "be", "set", "to", "or", "retrieved", "from", "this", "model", "class", "." ]
9fea86b718973de35ccca6d54bd1f445c9632406
https://github.com/transifex/transifex-python-library/blob/9fea86b718973de35ccca6d54bd1f445c9632406/txlib/api/base.py#L307-L333
train
Raise an exception whenever an invalid attribute with the given name was attempted to be set to or retrieved from the base class.
peopledoc/mock-services
mock_services/rules.py
update_http_rules
def update_http_rules(rules, content_type='text/plain'): """Adds rules to global http mock. It permits to set mock in a more global way than decorators, cf.: https://github.com/openstack/requests-mock Here we assume urls in the passed dict are regex we recompile before adding a rule. Rules ex...
python
def update_http_rules(rules, content_type='text/plain'): """Adds rules to global http mock. It permits to set mock in a more global way than decorators, cf.: https://github.com/openstack/requests-mock Here we assume urls in the passed dict are regex we recompile before adding a rule. Rules ex...
[ "def", "update_http_rules", "(", "rules", ",", "content_type", "=", "'text/plain'", ")", ":", "for", "kw", "in", "deepcopy", "(", "rules", ")", ":", "kw", "[", "'url'", "]", "=", "re", ".", "compile", "(", "kw", "[", "'url'", "]", ")", "# ensure header...
Adds rules to global http mock. It permits to set mock in a more global way than decorators, cf.: https://github.com/openstack/requests-mock Here we assume urls in the passed dict are regex we recompile before adding a rule. Rules example: >>> def fake_duckduckgo_cb(request): ... ret...
[ "Adds", "rules", "to", "global", "http", "mock", "." ]
fd3838280df8869725b538768357435eedf299c1
https://github.com/peopledoc/mock-services/blob/fd3838280df8869725b538768357435eedf299c1/mock_services/rules.py#L33-L75
train
Adds rules to global http mock.
obilaniu/Nauka
src/nauka/ap.py
_parseSpec
def _parseSpec(values): """ Split the argument string. Example: --arg name:value0,value1,key2=value2,key3=value3 gets split into name, args, kwargs = ( "name", (value0, value1), {"key2":value2, "key3":value3}, ) """ split = values.split(":", 1) name = split[0].strip() rest = split[1]...
python
def _parseSpec(values): """ Split the argument string. Example: --arg name:value0,value1,key2=value2,key3=value3 gets split into name, args, kwargs = ( "name", (value0, value1), {"key2":value2, "key3":value3}, ) """ split = values.split(":", 1) name = split[0].strip() rest = split[1]...
[ "def", "_parseSpec", "(", "values", ")", ":", "split", "=", "values", ".", "split", "(", "\":\"", ",", "1", ")", "name", "=", "split", "[", "0", "]", ".", "strip", "(", ")", "rest", "=", "split", "[", "1", "]", "if", "len", "(", "split", ")", ...
Split the argument string. Example: --arg name:value0,value1,key2=value2,key3=value3 gets split into name, args, kwargs = ( "name", (value0, value1), {"key2":value2, "key3":value3}, )
[ "Split", "the", "argument", "string", ".", "Example", ":", "--", "arg", "name", ":", "value0", "value1", "key2", "=", "value2", "key3", "=", "value3", "gets", "split", "into", "name", "args", "kwargs", "=", "(", "name", "(", "value0", "value1", ")", "{...
1492a4f9d204a868c1a8a1d327bd108490b856b4
https://github.com/obilaniu/Nauka/blob/1492a4f9d204a868c1a8a1d327bd108490b856b4/src/nauka/ap.py#L13-L92
train
Parse the spec string into name args kwargs and return the value.
inveniosoftware-contrib/invenio-workflows
invenio_workflows/utils.py
get_task_history
def get_task_history(last_task): """Append last task to task history.""" if hasattr(last_task, 'branch') and last_task.branch: return elif hasattr(last_task, 'hide') and last_task.hide: return else: return get_func_info(last_task)
python
def get_task_history(last_task): """Append last task to task history.""" if hasattr(last_task, 'branch') and last_task.branch: return elif hasattr(last_task, 'hide') and last_task.hide: return else: return get_func_info(last_task)
[ "def", "get_task_history", "(", "last_task", ")", ":", "if", "hasattr", "(", "last_task", ",", "'branch'", ")", "and", "last_task", ".", "branch", ":", "return", "elif", "hasattr", "(", "last_task", ",", "'hide'", ")", "and", "last_task", ".", "hide", ":",...
Append last task to task history.
[ "Append", "last", "task", "to", "task", "history", "." ]
9c09fd29509a3db975ac2aba337e6760d8cfd3c2
https://github.com/inveniosoftware-contrib/invenio-workflows/blob/9c09fd29509a3db975ac2aba337e6760d8cfd3c2/invenio_workflows/utils.py#L30-L37
train
Append last task to task history.
inveniosoftware-contrib/invenio-workflows
invenio_workflows/utils.py
get_func_info
def get_func_info(func): """Retrieve a function's information.""" name = func.__name__ doc = func.__doc__ or "" try: nicename = func.description except AttributeError: if doc: nicename = doc.split('\n')[0] if len(nicename) > 80: nicename = name...
python
def get_func_info(func): """Retrieve a function's information.""" name = func.__name__ doc = func.__doc__ or "" try: nicename = func.description except AttributeError: if doc: nicename = doc.split('\n')[0] if len(nicename) > 80: nicename = name...
[ "def", "get_func_info", "(", "func", ")", ":", "name", "=", "func", ".", "__name__", "doc", "=", "func", ".", "__doc__", "or", "\"\"", "try", ":", "nicename", "=", "func", ".", "description", "except", "AttributeError", ":", "if", "doc", ":", "nicename",...
Retrieve a function's information.
[ "Retrieve", "a", "function", "s", "information", "." ]
9c09fd29509a3db975ac2aba337e6760d8cfd3c2
https://github.com/inveniosoftware-contrib/invenio-workflows/blob/9c09fd29509a3db975ac2aba337e6760d8cfd3c2/invenio_workflows/utils.py#L40-L75
train
Retrieve a function s information.
inveniosoftware-contrib/invenio-workflows
invenio_workflows/utils.py
get_workflow_info
def get_workflow_info(func_list): """Return function info, go through lists recursively.""" funcs = [] for item in func_list: if item is None: continue if isinstance(item, list): funcs.append(get_workflow_info(item)) else: funcs.append(get_func_inf...
python
def get_workflow_info(func_list): """Return function info, go through lists recursively.""" funcs = [] for item in func_list: if item is None: continue if isinstance(item, list): funcs.append(get_workflow_info(item)) else: funcs.append(get_func_inf...
[ "def", "get_workflow_info", "(", "func_list", ")", ":", "funcs", "=", "[", "]", "for", "item", "in", "func_list", ":", "if", "item", "is", "None", ":", "continue", "if", "isinstance", "(", "item", ",", "list", ")", ":", "funcs", ".", "append", "(", "...
Return function info, go through lists recursively.
[ "Return", "function", "info", "go", "through", "lists", "recursively", "." ]
9c09fd29509a3db975ac2aba337e6760d8cfd3c2
https://github.com/inveniosoftware-contrib/invenio-workflows/blob/9c09fd29509a3db975ac2aba337e6760d8cfd3c2/invenio_workflows/utils.py#L78-L88
train
Return function info go through lists recursively.
COALAIP/pycoalaip
coalaip/data_formats.py
_copy_context_into_mutable
def _copy_context_into_mutable(context): """Copy a properly formatted context into a mutable data structure. """ def make_mutable(val): if isinstance(val, Mapping): return dict(val) else: return val if not isinstance(context, (str, Mapping)): try: ...
python
def _copy_context_into_mutable(context): """Copy a properly formatted context into a mutable data structure. """ def make_mutable(val): if isinstance(val, Mapping): return dict(val) else: return val if not isinstance(context, (str, Mapping)): try: ...
[ "def", "_copy_context_into_mutable", "(", "context", ")", ":", "def", "make_mutable", "(", "val", ")", ":", "if", "isinstance", "(", "val", ",", "Mapping", ")", ":", "return", "dict", "(", "val", ")", "else", ":", "return", "val", "if", "not", "isinstanc...
Copy a properly formatted context into a mutable data structure.
[ "Copy", "a", "properly", "formatted", "context", "into", "a", "mutable", "data", "structure", "." ]
cecc8f6ff4733f0525fafcee63647753e832f0be
https://github.com/COALAIP/pycoalaip/blob/cecc8f6ff4733f0525fafcee63647753e832f0be/coalaip/data_formats.py#L17-L31
train
Copy a properly formatted context into a mutable data structure.
COALAIP/pycoalaip
coalaip/data_formats.py
_make_context_immutable
def _make_context_immutable(context): """Best effort attempt at turning a properly formatted context (either a string, dict, or array of strings and dicts) into an immutable data structure. If we get an array, make it immutable by creating a tuple; if we get a dict, copy it into a MappingProxyType....
python
def _make_context_immutable(context): """Best effort attempt at turning a properly formatted context (either a string, dict, or array of strings and dicts) into an immutable data structure. If we get an array, make it immutable by creating a tuple; if we get a dict, copy it into a MappingProxyType....
[ "def", "_make_context_immutable", "(", "context", ")", ":", "def", "make_immutable", "(", "val", ")", ":", "if", "isinstance", "(", "val", ",", "Mapping", ")", ":", "return", "MappingProxyType", "(", "val", ")", "else", ":", "return", "val", "if", "not", ...
Best effort attempt at turning a properly formatted context (either a string, dict, or array of strings and dicts) into an immutable data structure. If we get an array, make it immutable by creating a tuple; if we get a dict, copy it into a MappingProxyType. Otherwise, return as-is.
[ "Best", "effort", "attempt", "at", "turning", "a", "properly", "formatted", "context", "(", "either", "a", "string", "dict", "or", "array", "of", "strings", "and", "dicts", ")", "into", "an", "immutable", "data", "structure", "." ]
cecc8f6ff4733f0525fafcee63647753e832f0be
https://github.com/COALAIP/pycoalaip/blob/cecc8f6ff4733f0525fafcee63647753e832f0be/coalaip/data_formats.py#L34-L53
train
Make a properly formatted context immutable data structure.
COALAIP/pycoalaip
coalaip/data_formats.py
_data_format_resolver
def _data_format_resolver(data_format, resolver_dict): """Resolve a value from :attr:`resolver_dict` based on the :attr:`data_format`. Args: data_format (:class:`~.DataFormat` or str): The data format; must be a member of :class:`~.DataFormat` or a string equivalent. ...
python
def _data_format_resolver(data_format, resolver_dict): """Resolve a value from :attr:`resolver_dict` based on the :attr:`data_format`. Args: data_format (:class:`~.DataFormat` or str): The data format; must be a member of :class:`~.DataFormat` or a string equivalent. ...
[ "def", "_data_format_resolver", "(", "data_format", ",", "resolver_dict", ")", ":", "try", ":", "data_format", "=", "DataFormat", "(", "data_format", ")", "except", "ValueError", ":", "supported_formats", "=", "', '", ".", "join", "(", "[", "\"'{}'\"", ".", "f...
Resolve a value from :attr:`resolver_dict` based on the :attr:`data_format`. Args: data_format (:class:`~.DataFormat` or str): The data format; must be a member of :class:`~.DataFormat` or a string equivalent. resolver_dict (dict): the resolving dict. Can hold any value ...
[ "Resolve", "a", "value", "from", ":", "attr", ":", "resolver_dict", "based", "on", "the", ":", "attr", ":", "data_format", "." ]
cecc8f6ff4733f0525fafcee63647753e832f0be
https://github.com/COALAIP/pycoalaip/blob/cecc8f6ff4733f0525fafcee63647753e832f0be/coalaip/data_formats.py#L56-L80
train
Resolve a value from the resolver_dict based on the data_format.
COALAIP/pycoalaip
coalaip/data_formats.py
_extract_ld_data
def _extract_ld_data(data, data_format=None, **kwargs): """Extract the given :attr:`data` into a :class:`~.ExtractedLinkedDataResult` with the resulting data stripped of any Linked Data specifics. Any missing Linked Data properties are returned as ``None`` in the resulting :class:`~.ExtractLinkedDat...
python
def _extract_ld_data(data, data_format=None, **kwargs): """Extract the given :attr:`data` into a :class:`~.ExtractedLinkedDataResult` with the resulting data stripped of any Linked Data specifics. Any missing Linked Data properties are returned as ``None`` in the resulting :class:`~.ExtractLinkedDat...
[ "def", "_extract_ld_data", "(", "data", ",", "data_format", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "not", "data_format", ":", "data_format", "=", "_get_format_from_data", "(", "data", ")", "extract_ld_data_fn", "=", "_data_format_resolver", "(", ...
Extract the given :attr:`data` into a :class:`~.ExtractedLinkedDataResult` with the resulting data stripped of any Linked Data specifics. Any missing Linked Data properties are returned as ``None`` in the resulting :class:`~.ExtractLinkedDataResult`. Does not modify the given :attr:`data`.
[ "Extract", "the", "given", ":", "attr", ":", "data", "into", "a", ":", "class", ":", "~", ".", "ExtractedLinkedDataResult", "with", "the", "resulting", "data", "stripped", "of", "any", "Linked", "Data", "specifics", ".", "Any", "missing", "Linked", "Data", ...
cecc8f6ff4733f0525fafcee63647753e832f0be
https://github.com/COALAIP/pycoalaip/blob/cecc8f6ff4733f0525fafcee63647753e832f0be/coalaip/data_formats.py#L91-L108
train
Extracts the given data into a with the resulting data stripped of any Missing Linked Data specifics.
seung-lab/EMAnnotationSchemas
emannotationschemas/models.py
validate_types
def validate_types(schemas_and_tables): '''normalize a list of desired annotation types if passed None returns all types, otherwise checks that types exist Parameters ---------- types: list[str] or None Returns ------- list[str] list of types Raises ------ UnknownAn...
python
def validate_types(schemas_and_tables): '''normalize a list of desired annotation types if passed None returns all types, otherwise checks that types exist Parameters ---------- types: list[str] or None Returns ------- list[str] list of types Raises ------ UnknownAn...
[ "def", "validate_types", "(", "schemas_and_tables", ")", ":", "all_types", "=", "get_types", "(", ")", "if", "not", "(", "all", "(", "sn", "in", "all_types", "for", "sn", ",", "tn", "in", "schemas_and_tables", ")", ")", ":", "bad_types", "=", "[", "sn", ...
normalize a list of desired annotation types if passed None returns all types, otherwise checks that types exist Parameters ---------- types: list[str] or None Returns ------- list[str] list of types Raises ------ UnknownAnnotationTypeException If types contains...
[ "normalize", "a", "list", "of", "desired", "annotation", "types", "if", "passed", "None", "returns", "all", "types", "otherwise", "checks", "that", "types", "exist", "Parameters", "----------", "types", ":", "list", "[", "str", "]", "or", "None" ]
ca81eff0f449bd7eb0392e0982db8f3636446a9e
https://github.com/seung-lab/EMAnnotationSchemas/blob/ca81eff0f449bd7eb0392e0982db8f3636446a9e/emannotationschemas/models.py#L86-L109
train
normalize a list of desired annotation types if passed None returns all types otherwise checks that types exist
seung-lab/EMAnnotationSchemas
emannotationschemas/models.py
make_dataset_models
def make_dataset_models(dataset, schemas_and_tables, metadata_dict = None, version: int = 1, include_contacts=False): """make all the models for a dataset Parameters ---------- dataset: str name of dataset table_and_types: list[(schema_name, table_name)] list of tuples with types an...
python
def make_dataset_models(dataset, schemas_and_tables, metadata_dict = None, version: int = 1, include_contacts=False): """make all the models for a dataset Parameters ---------- dataset: str name of dataset table_and_types: list[(schema_name, table_name)] list of tuples with types an...
[ "def", "make_dataset_models", "(", "dataset", ",", "schemas_and_tables", ",", "metadata_dict", "=", "None", ",", "version", ":", "int", "=", "1", ",", "include_contacts", "=", "False", ")", ":", "if", "metadata_dict", "is", "None", ":", "metadata_dict", "=", ...
make all the models for a dataset Parameters ---------- dataset: str name of dataset table_and_types: list[(schema_name, table_name)] list of tuples with types and model names to make metadata_dict: a dictionary with keys of table_names and values of metadata dicts needed ...
[ "make", "all", "the", "models", "for", "a", "dataset" ]
ca81eff0f449bd7eb0392e0982db8f3636446a9e
https://github.com/seung-lab/EMAnnotationSchemas/blob/ca81eff0f449bd7eb0392e0982db8f3636446a9e/emannotationschemas/models.py#L112-L158
train
make all the models needed for a dataset
dropseed/configyaml
configyaml/config/base.py
AbstractNode._key_name
def _key_name(self): # type: () -> str """Return the key referring to this object The default value is the lower case version of the class name :rtype: str """ if self._key is not None: return self._key return self.__class__.__name__.lower()
python
def _key_name(self): # type: () -> str """Return the key referring to this object The default value is the lower case version of the class name :rtype: str """ if self._key is not None: return self._key return self.__class__.__name__.lower()
[ "def", "_key_name", "(", "self", ")", ":", "# type: () -> str", "if", "self", ".", "_key", "is", "not", "None", ":", "return", "self", ".", "_key", "return", "self", ".", "__class__", ".", "__name__", ".", "lower", "(", ")" ]
Return the key referring to this object The default value is the lower case version of the class name :rtype: str
[ "Return", "the", "key", "referring", "to", "this", "object" ]
d008f251530d054c2d1fb3e8ac1a9030436134c8
https://github.com/dropseed/configyaml/blob/d008f251530d054c2d1fb3e8ac1a9030436134c8/configyaml/config/base.py#L77-L87
train
Return the key name of this object
dropseed/configyaml
configyaml/config/base.py
AbstractNode._path
def _path(self): # type: () -> str """Return the dotted path representation of this object :rtype: str """ if self._parent: return '{}.{}'.format(self._parent._path(), self._key_name()) return self._key_name()
python
def _path(self): # type: () -> str """Return the dotted path representation of this object :rtype: str """ if self._parent: return '{}.{}'.format(self._parent._path(), self._key_name()) return self._key_name()
[ "def", "_path", "(", "self", ")", ":", "# type: () -> str", "if", "self", ".", "_parent", ":", "return", "'{}.{}'", ".", "format", "(", "self", ".", "_parent", ".", "_path", "(", ")", ",", "self", ".", "_key_name", "(", ")", ")", "return", "self", "....
Return the dotted path representation of this object :rtype: str
[ "Return", "the", "dotted", "path", "representation", "of", "this", "object" ]
d008f251530d054c2d1fb3e8ac1a9030436134c8
https://github.com/dropseed/configyaml/blob/d008f251530d054c2d1fb3e8ac1a9030436134c8/configyaml/config/base.py#L103-L111
train
Return the dotted path representation of this object.
dropseed/configyaml
configyaml/config/base.py
AbstractNode._add_error
def _add_error(self, *args, **kwargs): # type: () -> None """Convenience function to add an error to this object, with line numbers An error title or description should not accidentally leak self._value, for privacy/redaction purposes. :rtype: None """ if kwargs.get('node', No...
python
def _add_error(self, *args, **kwargs): # type: () -> None """Convenience function to add an error to this object, with line numbers An error title or description should not accidentally leak self._value, for privacy/redaction purposes. :rtype: None """ if kwargs.get('node', No...
[ "def", "_add_error", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# type: () -> None", "if", "kwargs", ".", "get", "(", "'node'", ",", "None", ")", ":", "# if node specified and not none", "error", "=", "ConfigError", ".", "create_from_...
Convenience function to add an error to this object, with line numbers An error title or description should not accidentally leak self._value, for privacy/redaction purposes. :rtype: None
[ "Convenience", "function", "to", "add", "an", "error", "to", "this", "object", "with", "line", "numbers" ]
d008f251530d054c2d1fb3e8ac1a9030436134c8
https://github.com/dropseed/configyaml/blob/d008f251530d054c2d1fb3e8ac1a9030436134c8/configyaml/config/base.py#L113-L137
train
Convenience function to add an error to this object with line numbers.
dropseed/configyaml
configyaml/config/base.py
AbstractNode._get_descendants_errors
def _get_descendants_errors(self): # type: () -> List(ConfigError) """Recursively get errors from descendants :rtype: list of :ConfigErrors:""" descendants_errors = [] if hasattr(self, '_children'): if isinstance(self._children, (list, tuple)): for c in self...
python
def _get_descendants_errors(self): # type: () -> List(ConfigError) """Recursively get errors from descendants :rtype: list of :ConfigErrors:""" descendants_errors = [] if hasattr(self, '_children'): if isinstance(self._children, (list, tuple)): for c in self...
[ "def", "_get_descendants_errors", "(", "self", ")", ":", "# type: () -> List(ConfigError)", "descendants_errors", "=", "[", "]", "if", "hasattr", "(", "self", ",", "'_children'", ")", ":", "if", "isinstance", "(", "self", ".", "_children", ",", "(", "list", ",...
Recursively get errors from descendants :rtype: list of :ConfigErrors:
[ "Recursively", "get", "errors", "from", "descendants" ]
d008f251530d054c2d1fb3e8ac1a9030436134c8
https://github.com/dropseed/configyaml/blob/d008f251530d054c2d1fb3e8ac1a9030436134c8/configyaml/config/base.py#L139-L152
train
Recursively get errors from descendants xid
dropseed/configyaml
configyaml/config/base.py
AbstractNode._validate
def _validate(self): # type: () -> None """Run validation, save errors to object in self._errors""" # class can specify it's empty obj -- list would have empty of [] self._errors = [] self._validate_type() if self.is_valid(): self._validate_value()
python
def _validate(self): # type: () -> None """Run validation, save errors to object in self._errors""" # class can specify it's empty obj -- list would have empty of [] self._errors = [] self._validate_type() if self.is_valid(): self._validate_value()
[ "def", "_validate", "(", "self", ")", ":", "# type: () -> None", "# class can specify it's empty obj -- list would have empty of []", "self", ".", "_errors", "=", "[", "]", "self", ".", "_validate_type", "(", ")", "if", "self", ".", "is_valid", "(", ")", ":", "sel...
Run validation, save errors to object in self._errors
[ "Run", "validation", "save", "errors", "to", "object", "in", "self", ".", "_errors" ]
d008f251530d054c2d1fb3e8ac1a9030436134c8
https://github.com/dropseed/configyaml/blob/d008f251530d054c2d1fb3e8ac1a9030436134c8/configyaml/config/base.py#L163-L171
train
Run validation on the object
dropseed/configyaml
configyaml/config/base.py
AbstractNode._validate_type
def _validate_type(self): # type: () -> None """Validation to ensure value is the correct type""" if not isinstance(self._value, self._type): title = '{} has an invalid type'.format(self._key_name()) description = '{} must be a {}'.format(self._key_name(), self._type.__name__) ...
python
def _validate_type(self): # type: () -> None """Validation to ensure value is the correct type""" if not isinstance(self._value, self._type): title = '{} has an invalid type'.format(self._key_name()) description = '{} must be a {}'.format(self._key_name(), self._type.__name__) ...
[ "def", "_validate_type", "(", "self", ")", ":", "# type: () -> None", "if", "not", "isinstance", "(", "self", ".", "_value", ",", "self", ".", "_type", ")", ":", "title", "=", "'{} has an invalid type'", ".", "format", "(", "self", ".", "_key_name", "(", "...
Validation to ensure value is the correct type
[ "Validation", "to", "ensure", "value", "is", "the", "correct", "type" ]
d008f251530d054c2d1fb3e8ac1a9030436134c8
https://github.com/dropseed/configyaml/blob/d008f251530d054c2d1fb3e8ac1a9030436134c8/configyaml/config/base.py#L173-L179
train
Validation to ensure value is the correct type.
obilaniu/Nauka
src/nauka/exp/experiment.py
Experiment.haveSnapshots
def haveSnapshots(self): """Check if we have at least one snapshot.""" return os.path.islink(self.latestLink) and os.path.isdir(self.latestLink)
python
def haveSnapshots(self): """Check if we have at least one snapshot.""" return os.path.islink(self.latestLink) and os.path.isdir(self.latestLink)
[ "def", "haveSnapshots", "(", "self", ")", ":", "return", "os", ".", "path", ".", "islink", "(", "self", ".", "latestLink", ")", "and", "os", ".", "path", ".", "isdir", "(", "self", ".", "latestLink", ")" ]
Check if we have at least one snapshot.
[ "Check", "if", "we", "have", "at", "least", "one", "snapshot", "." ]
1492a4f9d204a868c1a8a1d327bd108490b856b4
https://github.com/obilaniu/Nauka/blob/1492a4f9d204a868c1a8a1d327bd108490b856b4/src/nauka/exp/experiment.py#L71-L73
train
Check if we have at least one snapshot.
obilaniu/Nauka
src/nauka/exp/experiment.py
Experiment.fromScratch
def fromScratch(self): """Start a fresh experiment, from scratch. Returns `self`.""" assert(not os.path.lexists(self.latestLink) or os.path.islink (self.latestLink)) self.rmR(self.latestLink) return self
python
def fromScratch(self): """Start a fresh experiment, from scratch. Returns `self`.""" assert(not os.path.lexists(self.latestLink) or os.path.islink (self.latestLink)) self.rmR(self.latestLink) return self
[ "def", "fromScratch", "(", "self", ")", ":", "assert", "(", "not", "os", ".", "path", ".", "lexists", "(", "self", ".", "latestLink", ")", "or", "os", ".", "path", ".", "islink", "(", "self", ".", "latestLink", ")", ")", "self", ".", "rmR", "(", ...
Start a fresh experiment, from scratch. Returns `self`.
[ "Start", "a", "fresh", "experiment", "from", "scratch", ".", "Returns", "self", "." ]
1492a4f9d204a868c1a8a1d327bd108490b856b4
https://github.com/obilaniu/Nauka/blob/1492a4f9d204a868c1a8a1d327bd108490b856b4/src/nauka/exp/experiment.py#L112-L120
train
Start a fresh experiment from scratch.
obilaniu/Nauka
src/nauka/exp/experiment.py
Experiment.snapshot
def snapshot (self): """Take a snapshot of the experiment. Returns `self`.""" nextSnapshotNum = self.nextSnapshotNum nextSnapshotPath = self.getFullPathToSnapshot(nextSnapshotNum) if os.path.lexists(nextSnapshotPath): self.rmR(nextSnapshotPath) self.mkdirp(os.path.join(nextSnapshotPath...
python
def snapshot (self): """Take a snapshot of the experiment. Returns `self`.""" nextSnapshotNum = self.nextSnapshotNum nextSnapshotPath = self.getFullPathToSnapshot(nextSnapshotNum) if os.path.lexists(nextSnapshotPath): self.rmR(nextSnapshotPath) self.mkdirp(os.path.join(nextSnapshotPath...
[ "def", "snapshot", "(", "self", ")", ":", "nextSnapshotNum", "=", "self", ".", "nextSnapshotNum", "nextSnapshotPath", "=", "self", ".", "getFullPathToSnapshot", "(", "nextSnapshotNum", ")", "if", "os", ".", "path", ".", "lexists", "(", "nextSnapshotPath", ")", ...
Take a snapshot of the experiment. Returns `self`.
[ "Take", "a", "snapshot", "of", "the", "experiment", ".", "Returns", "self", "." ]
1492a4f9d204a868c1a8a1d327bd108490b856b4
https://github.com/obilaniu/Nauka/blob/1492a4f9d204a868c1a8a1d327bd108490b856b4/src/nauka/exp/experiment.py#L136-L146
train
Take a snapshot of the experiment. Returns self.
obilaniu/Nauka
src/nauka/exp/experiment.py
Experiment.rollback
def rollback (self, n=None): """Roll back the experiment to the given snapshot number. Returns `self`.""" if n is None: if self.haveSnapshots: return self.fromSnapshot(self.latestLink) else: return self.fromScratch() elif isinstance(n, int): loadSnapshotPath = self.ge...
python
def rollback (self, n=None): """Roll back the experiment to the given snapshot number. Returns `self`.""" if n is None: if self.haveSnapshots: return self.fromSnapshot(self.latestLink) else: return self.fromScratch() elif isinstance(n, int): loadSnapshotPath = self.ge...
[ "def", "rollback", "(", "self", ",", "n", "=", "None", ")", ":", "if", "n", "is", "None", ":", "if", "self", ".", "haveSnapshots", ":", "return", "self", ".", "fromSnapshot", "(", "self", ".", "latestLink", ")", "else", ":", "return", "self", ".", ...
Roll back the experiment to the given snapshot number. Returns `self`.
[ "Roll", "back", "the", "experiment", "to", "the", "given", "snapshot", "number", ".", "Returns", "self", "." ]
1492a4f9d204a868c1a8a1d327bd108490b856b4
https://github.com/obilaniu/Nauka/blob/1492a4f9d204a868c1a8a1d327bd108490b856b4/src/nauka/exp/experiment.py#L148-L161
train
Roll back the experiment to the given snapshot number.
obilaniu/Nauka
src/nauka/exp/experiment.py
Experiment.purge
def purge (self, strategy = "klogn", keep = None, deleteNonSnapshots = False, **kwargs): """Purge snapshot directory of snapshots according to some strategy, preserving ...
python
def purge (self, strategy = "klogn", keep = None, deleteNonSnapshots = False, **kwargs): """Purge snapshot directory of snapshots according to some strategy, preserving ...
[ "def", "purge", "(", "self", ",", "strategy", "=", "\"klogn\"", ",", "keep", "=", "None", ",", "deleteNonSnapshots", "=", "False", ",", "*", "*", "kwargs", ")", ":", "assert", "(", "isinstance", "(", "keep", ",", "(", "list", ",", "set", ")", ")", ...
Purge snapshot directory of snapshots according to some strategy, preserving however a given "keep" list or set of snapshot numbers. Available strategies are: "lastk": Keep last k snapshots (Default: k=10) "klogn": Keep every snapshot in the last k, 2k snapshots in the last k**2, 3k...
[ "Purge", "snapshot", "directory", "of", "snapshots", "according", "to", "some", "strategy", "preserving", "however", "a", "given", "keep", "list", "or", "set", "of", "snapshot", "numbers", ".", "Available", "strategies", "are", ":", "lastk", ":", "Keep", "last...
1492a4f9d204a868c1a8a1d327bd108490b856b4
https://github.com/obilaniu/Nauka/blob/1492a4f9d204a868c1a8a1d327bd108490b856b4/src/nauka/exp/experiment.py#L163-L199
train
Purge all the directories in the archive according to some strategy.
obilaniu/Nauka
src/nauka/exp/experiment.py
Experiment.getFullPathToSnapshot
def getFullPathToSnapshot(self, n): """Get the full path to snapshot n.""" return os.path.join(self.snapDir, str(n))
python
def getFullPathToSnapshot(self, n): """Get the full path to snapshot n.""" return os.path.join(self.snapDir, str(n))
[ "def", "getFullPathToSnapshot", "(", "self", ",", "n", ")", ":", "return", "os", ".", "path", ".", "join", "(", "self", ".", "snapDir", ",", "str", "(", "n", ")", ")" ]
Get the full path to snapshot n.
[ "Get", "the", "full", "path", "to", "snapshot", "n", "." ]
1492a4f9d204a868c1a8a1d327bd108490b856b4
https://github.com/obilaniu/Nauka/blob/1492a4f9d204a868c1a8a1d327bd108490b856b4/src/nauka/exp/experiment.py#L201-L203
train
Get the full path to snapshot n.
obilaniu/Nauka
src/nauka/exp/experiment.py
Experiment.strategyLastK
def strategyLastK(kls, n, k=10): """Return the directory names to preserve under the LastK purge strategy.""" return set(map(str, filter(lambda x:x>=0, range(n, n-k, -1))))
python
def strategyLastK(kls, n, k=10): """Return the directory names to preserve under the LastK purge strategy.""" return set(map(str, filter(lambda x:x>=0, range(n, n-k, -1))))
[ "def", "strategyLastK", "(", "kls", ",", "n", ",", "k", "=", "10", ")", ":", "return", "set", "(", "map", "(", "str", ",", "filter", "(", "lambda", "x", ":", "x", ">=", "0", ",", "range", "(", "n", ",", "n", "-", "k", ",", "-", "1", ")", ...
Return the directory names to preserve under the LastK purge strategy.
[ "Return", "the", "directory", "names", "to", "preserve", "under", "the", "LastK", "purge", "strategy", "." ]
1492a4f9d204a868c1a8a1d327bd108490b856b4
https://github.com/obilaniu/Nauka/blob/1492a4f9d204a868c1a8a1d327bd108490b856b4/src/nauka/exp/experiment.py#L215-L217
train
Return the directory names to preserve under the LastK purge strategy.
obilaniu/Nauka
src/nauka/exp/experiment.py
Experiment.strategyKLogN
def strategyKLogN(kls, n, k=4): """Return the directory names to preserve under the KLogN purge strategy.""" assert(k>1) s = set([n]) i = 0 while k**i <= n: s.update(range(n, n-k*k**i, -k**i)) i += 1 n -= n % k**i return set(map(str, filter(lambda x:x>=0, s)))
python
def strategyKLogN(kls, n, k=4): """Return the directory names to preserve under the KLogN purge strategy.""" assert(k>1) s = set([n]) i = 0 while k**i <= n: s.update(range(n, n-k*k**i, -k**i)) i += 1 n -= n % k**i return set(map(str, filter(lambda x:x>=0, s)))
[ "def", "strategyKLogN", "(", "kls", ",", "n", ",", "k", "=", "4", ")", ":", "assert", "(", "k", ">", "1", ")", "s", "=", "set", "(", "[", "n", "]", ")", "i", "=", "0", "while", "k", "**", "i", "<=", "n", ":", "s", ".", "update", "(", "r...
Return the directory names to preserve under the KLogN purge strategy.
[ "Return", "the", "directory", "names", "to", "preserve", "under", "the", "KLogN", "purge", "strategy", "." ]
1492a4f9d204a868c1a8a1d327bd108490b856b4
https://github.com/obilaniu/Nauka/blob/1492a4f9d204a868c1a8a1d327bd108490b856b4/src/nauka/exp/experiment.py#L220-L231
train
Return the directory names to preserve under the KLogN purge strategy.
obilaniu/Nauka
src/nauka/exp/experiment.py
Experiment.mkdirp
def mkdirp(kls, path, mode=0o755): """`mkdir -p path/to/folder`. Creates a folder and all parent directories if they don't already exist.""" os.makedirs(path, mode=mode, exist_ok=True)
python
def mkdirp(kls, path, mode=0o755): """`mkdir -p path/to/folder`. Creates a folder and all parent directories if they don't already exist.""" os.makedirs(path, mode=mode, exist_ok=True)
[ "def", "mkdirp", "(", "kls", ",", "path", ",", "mode", "=", "0o755", ")", ":", "os", ".", "makedirs", "(", "path", ",", "mode", "=", "mode", ",", "exist_ok", "=", "True", ")" ]
`mkdir -p path/to/folder`. Creates a folder and all parent directories if they don't already exist.
[ "mkdir", "-", "p", "path", "/", "to", "/", "folder", ".", "Creates", "a", "folder", "and", "all", "parent", "directories", "if", "they", "don", "t", "already", "exist", "." ]
1492a4f9d204a868c1a8a1d327bd108490b856b4
https://github.com/obilaniu/Nauka/blob/1492a4f9d204a868c1a8a1d327bd108490b856b4/src/nauka/exp/experiment.py#L237-L240
train
Create a folder and all parent directories.
obilaniu/Nauka
src/nauka/exp/experiment.py
Experiment.listSnapshotDir
def listSnapshotDir(kls, path): """Return the set of snapshot directories and non-snapshot directories under the given path.""" snapshotSet = set() nonsnapshotSet = set() try: entryList = os.listdir(path) for e in entryList: if kls.isFilenameInteger(e): snapshotSet .add(e) else: ...
python
def listSnapshotDir(kls, path): """Return the set of snapshot directories and non-snapshot directories under the given path.""" snapshotSet = set() nonsnapshotSet = set() try: entryList = os.listdir(path) for e in entryList: if kls.isFilenameInteger(e): snapshotSet .add(e) else: ...
[ "def", "listSnapshotDir", "(", "kls", ",", "path", ")", ":", "snapshotSet", "=", "set", "(", ")", "nonsnapshotSet", "=", "set", "(", ")", "try", ":", "entryList", "=", "os", ".", "listdir", "(", "path", ")", "for", "e", "in", "entryList", ":", "if", ...
Return the set of snapshot directories and non-snapshot directories under the given path.
[ "Return", "the", "set", "of", "snapshot", "directories", "and", "non", "-", "snapshot", "directories", "under", "the", "given", "path", "." ]
1492a4f9d204a868c1a8a1d327bd108490b856b4
https://github.com/obilaniu/Nauka/blob/1492a4f9d204a868c1a8a1d327bd108490b856b4/src/nauka/exp/experiment.py#L249-L261
train
Return the set of snapshot directories and non - snapshot directories under the given path.
obilaniu/Nauka
src/nauka/exp/experiment.py
Experiment.rmR
def rmR(kls, path): """`rm -R path`. Deletes, but does not recurse into, symlinks. If the path does not exist, silently return.""" if os.path.islink(path) or os.path.isfile(path): os.unlink(path) elif os.path.isdir(path): walker = os.walk(path, topdown=False, followlinks=False) for dirpath, dirnames,...
python
def rmR(kls, path): """`rm -R path`. Deletes, but does not recurse into, symlinks. If the path does not exist, silently return.""" if os.path.islink(path) or os.path.isfile(path): os.unlink(path) elif os.path.isdir(path): walker = os.walk(path, topdown=False, followlinks=False) for dirpath, dirnames,...
[ "def", "rmR", "(", "kls", ",", "path", ")", ":", "if", "os", ".", "path", ".", "islink", "(", "path", ")", "or", "os", ".", "path", ".", "isfile", "(", "path", ")", ":", "os", ".", "unlink", "(", "path", ")", "elif", "os", ".", "path", ".", ...
`rm -R path`. Deletes, but does not recurse into, symlinks. If the path does not exist, silently return.
[ "rm", "-", "R", "path", ".", "Deletes", "but", "does", "not", "recurse", "into", "symlinks", ".", "If", "the", "path", "does", "not", "exist", "silently", "return", "." ]
1492a4f9d204a868c1a8a1d327bd108490b856b4
https://github.com/obilaniu/Nauka/blob/1492a4f9d204a868c1a8a1d327bd108490b856b4/src/nauka/exp/experiment.py#L264-L276
train
rm - R path. Deletes but does not recurse into symlinks. If the path does not exist silently return. If the path does not exist silently return.
obilaniu/Nauka
src/nauka/exp/experiment.py
Experiment.atomicSymlink
def atomicSymlink(kls, target, name): """Same syntax as os.symlink, except that the new link called `name` will first be created with the `name` and `target` `name.ATOMIC` -> `target` , then be atomically renamed to `name` -> `target` , thus overwriting any previous symlink there. If a f...
python
def atomicSymlink(kls, target, name): """Same syntax as os.symlink, except that the new link called `name` will first be created with the `name` and `target` `name.ATOMIC` -> `target` , then be atomically renamed to `name` -> `target` , thus overwriting any previous symlink there. If a f...
[ "def", "atomicSymlink", "(", "kls", ",", "target", ",", "name", ")", ":", "linkAtomicName", "=", "name", "+", "\".ATOMIC\"", "linkFinalName", "=", "name", "linkTarget", "=", "target", "if", "os", ".", "path", ".", "lexists", "(", "linkAtomicName", ")", ":"...
Same syntax as os.symlink, except that the new link called `name` will first be created with the `name` and `target` `name.ATOMIC` -> `target` , then be atomically renamed to `name` -> `target` , thus overwriting any previous symlink there. If a filesystem entity called `name.ATOMIC` alr...
[ "Same", "syntax", "as", "os", ".", "symlink", "except", "that", "the", "new", "link", "called", "name", "will", "first", "be", "created", "with", "the", "name", "and", "target", "name", ".", "ATOMIC", "-", ">", "target", "then", "be", "atomically", "rena...
1492a4f9d204a868c1a8a1d327bd108490b856b4
https://github.com/obilaniu/Nauka/blob/1492a4f9d204a868c1a8a1d327bd108490b856b4/src/nauka/exp/experiment.py#L279-L304
train
Same syntax as os. symlink except that the new symlink called name will be atomically renamed to target.
giancosta86/Iris
info/gianlucacosta/iris/vars.py
VariablesService.getFlag
def getFlag(self, flagName): """ Creates a flag having path <variables dir path><os.sep><flagName> """ assert (len(flagName) > 0) return Flag(os.path.join(self._variablesDirPath, flagName))
python
def getFlag(self, flagName): """ Creates a flag having path <variables dir path><os.sep><flagName> """ assert (len(flagName) > 0) return Flag(os.path.join(self._variablesDirPath, flagName))
[ "def", "getFlag", "(", "self", ",", "flagName", ")", ":", "assert", "(", "len", "(", "flagName", ")", ">", "0", ")", "return", "Flag", "(", "os", ".", "path", ".", "join", "(", "self", ".", "_variablesDirPath", ",", "flagName", ")", ")" ]
Creates a flag having path <variables dir path><os.sep><flagName>
[ "Creates", "a", "flag", "having", "path", "<variables", "dir", "path", ">", "<os", ".", "sep", ">", "<flagName", ">" ]
b3d92cca5cce3653519bd032346b211c46a57d05
https://github.com/giancosta86/Iris/blob/b3d92cca5cce3653519bd032346b211c46a57d05/info/gianlucacosta/iris/vars.py#L24-L30
train
Returns a flag with the given name
azogue/i2csense
i2csense/bme280.py
BME280._compensate_temperature
def _compensate_temperature(self, adc_t): """Compensate temperature. Formula from datasheet Bosch BME280 Environmental sensor. 8.1 Compensation formulas in double precision floating point Edition BST-BME280-DS001-10 | Revision 1.1 | May 2015 """ var_1 = ((adc_t / 16384.0...
python
def _compensate_temperature(self, adc_t): """Compensate temperature. Formula from datasheet Bosch BME280 Environmental sensor. 8.1 Compensation formulas in double precision floating point Edition BST-BME280-DS001-10 | Revision 1.1 | May 2015 """ var_1 = ((adc_t / 16384.0...
[ "def", "_compensate_temperature", "(", "self", ",", "adc_t", ")", ":", "var_1", "=", "(", "(", "adc_t", "/", "16384.0", "-", "self", ".", "_calibration_t", "[", "0", "]", "/", "1024.0", ")", "*", "self", ".", "_calibration_t", "[", "1", "]", ")", "va...
Compensate temperature. Formula from datasheet Bosch BME280 Environmental sensor. 8.1 Compensation formulas in double precision floating point Edition BST-BME280-DS001-10 | Revision 1.1 | May 2015
[ "Compensate", "temperature", "." ]
ecc6806dcee9de827a5414a9e836d271fedca9b9
https://github.com/azogue/i2csense/blob/ecc6806dcee9de827a5414a9e836d271fedca9b9/i2csense/bme280.py#L61-L79
train
Compensate temperature.
azogue/i2csense
i2csense/bme280.py
BME280._compensate_pressure
def _compensate_pressure(self, adc_p): """Compensate pressure. Formula from datasheet Bosch BME280 Environmental sensor. 8.1 Compensation formulas in double precision floating point Edition BST-BME280-DS001-10 | Revision 1.1 | May 2015. """ var_1 = (self._temp_fine / 2.0...
python
def _compensate_pressure(self, adc_p): """Compensate pressure. Formula from datasheet Bosch BME280 Environmental sensor. 8.1 Compensation formulas in double precision floating point Edition BST-BME280-DS001-10 | Revision 1.1 | May 2015. """ var_1 = (self._temp_fine / 2.0...
[ "def", "_compensate_pressure", "(", "self", ",", "adc_p", ")", ":", "var_1", "=", "(", "self", ".", "_temp_fine", "/", "2.0", ")", "-", "64000.0", "var_2", "=", "(", "(", "var_1", "/", "4.0", ")", "*", "(", "var_1", "/", "4.0", ")", ")", "/", "20...
Compensate pressure. Formula from datasheet Bosch BME280 Environmental sensor. 8.1 Compensation formulas in double precision floating point Edition BST-BME280-DS001-10 | Revision 1.1 | May 2015.
[ "Compensate", "pressure", "." ]
ecc6806dcee9de827a5414a9e836d271fedca9b9
https://github.com/azogue/i2csense/blob/ecc6806dcee9de827a5414a9e836d271fedca9b9/i2csense/bme280.py#L81-L113
train
Compensate pressure.
azogue/i2csense
i2csense/bme280.py
BME280._compensate_humidity
def _compensate_humidity(self, adc_h): """Compensate humidity. Formula from datasheet Bosch BME280 Environmental sensor. 8.1 Compensation formulas in double precision floating point Edition BST-BME280-DS001-10 | Revision 1.1 | May 2015. """ var_h = self._temp_fine - 7680...
python
def _compensate_humidity(self, adc_h): """Compensate humidity. Formula from datasheet Bosch BME280 Environmental sensor. 8.1 Compensation formulas in double precision floating point Edition BST-BME280-DS001-10 | Revision 1.1 | May 2015. """ var_h = self._temp_fine - 7680...
[ "def", "_compensate_humidity", "(", "self", ",", "adc_h", ")", ":", "var_h", "=", "self", ".", "_temp_fine", "-", "76800.0", "if", "var_h", "==", "0", ":", "return", "0", "var_h", "=", "(", "(", "adc_h", "-", "(", "self", ".", "_calibration_h", "[", ...
Compensate humidity. Formula from datasheet Bosch BME280 Environmental sensor. 8.1 Compensation formulas in double precision floating point Edition BST-BME280-DS001-10 | Revision 1.1 | May 2015.
[ "Compensate", "humidity", "." ]
ecc6806dcee9de827a5414a9e836d271fedca9b9
https://github.com/azogue/i2csense/blob/ecc6806dcee9de827a5414a9e836d271fedca9b9/i2csense/bme280.py#L115-L138
train
Compensate humidity.
azogue/i2csense
i2csense/bme280.py
BME280._populate_calibration_data
def _populate_calibration_data(self): """Populate calibration data. From datasheet Bosch BME280 Environmental sensor. """ calibration_t = [] calibration_p = [] calibration_h = [] raw_data = [] try: for i in range(0x88, 0x88 + 24): ...
python
def _populate_calibration_data(self): """Populate calibration data. From datasheet Bosch BME280 Environmental sensor. """ calibration_t = [] calibration_p = [] calibration_h = [] raw_data = [] try: for i in range(0x88, 0x88 + 24): ...
[ "def", "_populate_calibration_data", "(", "self", ")", ":", "calibration_t", "=", "[", "]", "calibration_p", "=", "[", "]", "calibration_h", "=", "[", "]", "raw_data", "=", "[", "]", "try", ":", "for", "i", "in", "range", "(", "0x88", ",", "0x88", "+",...
Populate calibration data. From datasheet Bosch BME280 Environmental sensor.
[ "Populate", "calibration", "data", "." ]
ecc6806dcee9de827a5414a9e836d271fedca9b9
https://github.com/azogue/i2csense/blob/ecc6806dcee9de827a5414a9e836d271fedca9b9/i2csense/bme280.py#L140-L200
train
Populate the calibration data.
azogue/i2csense
i2csense/bme280.py
BME280._take_forced_measurement
def _take_forced_measurement(self): """Take a forced measurement. In forced mode, the BME sensor goes back to sleep after each measurement and we need to set it to forced mode once at this point, so it will take the next measurement and then return to sleep again. In normal mode...
python
def _take_forced_measurement(self): """Take a forced measurement. In forced mode, the BME sensor goes back to sleep after each measurement and we need to set it to forced mode once at this point, so it will take the next measurement and then return to sleep again. In normal mode...
[ "def", "_take_forced_measurement", "(", "self", ")", ":", "# set to forced mode, i.e. \"take next measurement\"", "self", ".", "_bus", ".", "write_byte_data", "(", "self", ".", "_i2c_add", ",", "0xF4", ",", "self", ".", "ctrl_meas_reg", ")", "while", "self", ".", ...
Take a forced measurement. In forced mode, the BME sensor goes back to sleep after each measurement and we need to set it to forced mode once at this point, so it will take the next measurement and then return to sleep again. In normal mode simply does new measurements periodically.
[ "Take", "a", "forced", "measurement", "." ]
ecc6806dcee9de827a5414a9e836d271fedca9b9
https://github.com/azogue/i2csense/blob/ecc6806dcee9de827a5414a9e836d271fedca9b9/i2csense/bme280.py#L202-L213
train
Take a forced measurement.
azogue/i2csense
i2csense/bme280.py
BME280.update
def update(self, first_reading=False): """Read raw data and update compensated variables.""" try: if first_reading or not self._ok: self._bus.write_byte_data(self._i2c_add, 0xF2, self.ctrl_hum_reg) self._bus.write_byte...
python
def update(self, first_reading=False): """Read raw data and update compensated variables.""" try: if first_reading or not self._ok: self._bus.write_byte_data(self._i2c_add, 0xF2, self.ctrl_hum_reg) self._bus.write_byte...
[ "def", "update", "(", "self", ",", "first_reading", "=", "False", ")", ":", "try", ":", "if", "first_reading", "or", "not", "self", ".", "_ok", ":", "self", ".", "_bus", ".", "write_byte_data", "(", "self", ".", "_i2c_add", ",", "0xF2", ",", "self", ...
Read raw data and update compensated variables.
[ "Read", "raw", "data", "and", "update", "compensated", "variables", "." ]
ecc6806dcee9de827a5414a9e836d271fedca9b9
https://github.com/azogue/i2csense/blob/ecc6806dcee9de827a5414a9e836d271fedca9b9/i2csense/bme280.py#L215-L257
train
Read raw data and update compensated variables.
openvax/varlens
varlens/read_evidence/pileup.py
Pileup.append
def append(self, element): ''' Append a PileupElement to this Pileup. If an identical PileupElement is already part of this Pileup, do nothing. ''' assert element.locus == self.locus, ( "Element locus (%s) != Pileup locus (%s)" % (element.locus, self.locus...
python
def append(self, element): ''' Append a PileupElement to this Pileup. If an identical PileupElement is already part of this Pileup, do nothing. ''' assert element.locus == self.locus, ( "Element locus (%s) != Pileup locus (%s)" % (element.locus, self.locus...
[ "def", "append", "(", "self", ",", "element", ")", ":", "assert", "element", ".", "locus", "==", "self", ".", "locus", ",", "(", "\"Element locus (%s) != Pileup locus (%s)\"", "%", "(", "element", ".", "locus", ",", "self", ".", "locus", ")", ")", "self", ...
Append a PileupElement to this Pileup. If an identical PileupElement is already part of this Pileup, do nothing.
[ "Append", "a", "PileupElement", "to", "this", "Pileup", ".", "If", "an", "identical", "PileupElement", "is", "already", "part", "of", "this", "Pileup", "do", "nothing", "." ]
715d3ede5893757b2fcba4117515621bca7b1e5d
https://github.com/openvax/varlens/blob/715d3ede5893757b2fcba4117515621bca7b1e5d/varlens/read_evidence/pileup.py#L55-L63
train
Append a PileupElement to this Pileup.
openvax/varlens
varlens/read_evidence/pileup.py
Pileup.update
def update(self, other): ''' Add all pileup elements from other into self. ''' assert self.locus == other.locus self.elements.update(other.elements)
python
def update(self, other): ''' Add all pileup elements from other into self. ''' assert self.locus == other.locus self.elements.update(other.elements)
[ "def", "update", "(", "self", ",", "other", ")", ":", "assert", "self", ".", "locus", "==", "other", ".", "locus", "self", ".", "elements", ".", "update", "(", "other", ".", "elements", ")" ]
Add all pileup elements from other into self.
[ "Add", "all", "pileup", "elements", "from", "other", "into", "self", "." ]
715d3ede5893757b2fcba4117515621bca7b1e5d
https://github.com/openvax/varlens/blob/715d3ede5893757b2fcba4117515621bca7b1e5d/varlens/read_evidence/pileup.py#L65-L70
train
Update the internal set of pileup elements from another.
openvax/varlens
varlens/read_evidence/pileup.py
Pileup.filter
def filter(self, filters): ''' Apply filters to the pileup elements, and return a new Pileup with the filtered elements removed. Parameters ---------- filters : list of PileupElement -> bool callables A PileupUp element is retained if all filters return True ...
python
def filter(self, filters): ''' Apply filters to the pileup elements, and return a new Pileup with the filtered elements removed. Parameters ---------- filters : list of PileupElement -> bool callables A PileupUp element is retained if all filters return True ...
[ "def", "filter", "(", "self", ",", "filters", ")", ":", "new_elements", "=", "[", "e", "for", "e", "in", "self", ".", "elements", "if", "all", "(", "function", "(", "e", ")", "for", "function", "in", "filters", ")", "]", "return", "Pileup", "(", "s...
Apply filters to the pileup elements, and return a new Pileup with the filtered elements removed. Parameters ---------- filters : list of PileupElement -> bool callables A PileupUp element is retained if all filters return True when called on it.
[ "Apply", "filters", "to", "the", "pileup", "elements", "and", "return", "a", "new", "Pileup", "with", "the", "filtered", "elements", "removed", "." ]
715d3ede5893757b2fcba4117515621bca7b1e5d
https://github.com/openvax/varlens/blob/715d3ede5893757b2fcba4117515621bca7b1e5d/varlens/read_evidence/pileup.py#L72-L86
train
Returns a new Pileup with the filtered elements removed.
BernardFW/bernard
src/bernard/analytics/base.py
new_task
def new_task(func): """ Runs the decorated function in a new task """ @wraps(func) async def wrapper(self, *args, **kwargs): loop = get_event_loop() loop.create_task(func(self, *args, **kwargs)) return wrapper
python
def new_task(func): """ Runs the decorated function in a new task """ @wraps(func) async def wrapper(self, *args, **kwargs): loop = get_event_loop() loop.create_task(func(self, *args, **kwargs)) return wrapper
[ "def", "new_task", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "async", "def", "wrapper", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "loop", "=", "get_event_loop", "(", ")", "loop", ".", "create_task", "(", "func",...
Runs the decorated function in a new task
[ "Runs", "the", "decorated", "function", "in", "a", "new", "task" ]
9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab
https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/analytics/base.py#L65-L74
train
Runs the decorated function in a new task
BernardFW/bernard
src/bernard/analytics/base.py
providers
async def providers(): """ Iterates over all instances of analytics provider found in configuration """ for provider in settings.ANALYTICS_PROVIDERS: cls: BaseAnalytics = import_class(provider['class']) yield await cls.instance(*provider['args'])
python
async def providers(): """ Iterates over all instances of analytics provider found in configuration """ for provider in settings.ANALYTICS_PROVIDERS: cls: BaseAnalytics = import_class(provider['class']) yield await cls.instance(*provider['args'])
[ "async", "def", "providers", "(", ")", ":", "for", "provider", "in", "settings", ".", "ANALYTICS_PROVIDERS", ":", "cls", ":", "BaseAnalytics", "=", "import_class", "(", "provider", "[", "'class'", "]", ")", "yield", "await", "cls", ".", "instance", "(", "*...
Iterates over all instances of analytics provider found in configuration
[ "Iterates", "over", "all", "instances", "of", "analytics", "provider", "found", "in", "configuration" ]
9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab
https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/analytics/base.py#L77-L84
train
Iterate over all analytics providers in configuration
BernardFW/bernard
src/bernard/analytics/base.py
BaseAnalytics.page_view
async def page_view(self, url: str, title: str, user_id: str, user_lang: str='') -> None: """ Track the view of a page """ raise NotImplementedError
python
async def page_view(self, url: str, title: str, user_id: str, user_lang: str='') -> None: """ Track the view of a page """ raise NotImplementedError
[ "async", "def", "page_view", "(", "self", ",", "url", ":", "str", ",", "title", ":", "str", ",", "user_id", ":", "str", ",", "user_lang", ":", "str", "=", "''", ")", "->", "None", ":", "raise", "NotImplementedError" ]
Track the view of a page
[ "Track", "the", "view", "of", "a", "page" ]
9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab
https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/analytics/base.py#L37-L46
train
Track the view of a page
BernardFW/bernard
src/bernard/analytics/base.py
BaseAnalytics.hash_user_id
def hash_user_id(self, user_id: str) -> str: """ As per the law, anonymize user identifier before sending it. """ h = sha256() h.update(user_id.encode()) return h.hexdigest()
python
def hash_user_id(self, user_id: str) -> str: """ As per the law, anonymize user identifier before sending it. """ h = sha256() h.update(user_id.encode()) return h.hexdigest()
[ "def", "hash_user_id", "(", "self", ",", "user_id", ":", "str", ")", "->", "str", ":", "h", "=", "sha256", "(", ")", "h", ".", "update", "(", "user_id", ".", "encode", "(", ")", ")", "return", "h", ".", "hexdigest", "(", ")" ]
As per the law, anonymize user identifier before sending it.
[ "As", "per", "the", "law", "anonymize", "user", "identifier", "before", "sending", "it", "." ]
9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab
https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/analytics/base.py#L48-L55
train
Hash a user identifier.
inveniosoftware-contrib/invenio-workflows
invenio_workflows/models.py
Workflow.delete
def delete(cls, uuid): """Delete a workflow.""" to_delete = Workflow.query.get(uuid) db.session.delete(to_delete)
python
def delete(cls, uuid): """Delete a workflow.""" to_delete = Workflow.query.get(uuid) db.session.delete(to_delete)
[ "def", "delete", "(", "cls", ",", "uuid", ")", ":", "to_delete", "=", "Workflow", ".", "query", ".", "get", "(", "uuid", ")", "db", ".", "session", ".", "delete", "(", "to_delete", ")" ]
Delete a workflow.
[ "Delete", "a", "workflow", "." ]
9c09fd29509a3db975ac2aba337e6760d8cfd3c2
https://github.com/inveniosoftware-contrib/invenio-workflows/blob/9c09fd29509a3db975ac2aba337e6760d8cfd3c2/invenio_workflows/models.py#L96-L99
train
Delete a workflow.
inveniosoftware-contrib/invenio-workflows
invenio_workflows/worker_engine.py
run_worker
def run_worker(wname, data, engine_uuid_hex=None, **kwargs): """Run a workflow by name with list of data objects. The list of data can also contain WorkflowObjects. ``**kwargs`` can be used to pass custom arguments to the engine/object. :param wname: name of workflow to run. :type wname: str ...
python
def run_worker(wname, data, engine_uuid_hex=None, **kwargs): """Run a workflow by name with list of data objects. The list of data can also contain WorkflowObjects. ``**kwargs`` can be used to pass custom arguments to the engine/object. :param wname: name of workflow to run. :type wname: str ...
[ "def", "run_worker", "(", "wname", ",", "data", ",", "engine_uuid_hex", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "'stop_on_halt'", "not", "in", "kwargs", ":", "kwargs", "[", "'stop_on_halt'", "]", "=", "False", "if", "engine_uuid_hex", ":", ...
Run a workflow by name with list of data objects. The list of data can also contain WorkflowObjects. ``**kwargs`` can be used to pass custom arguments to the engine/object. :param wname: name of workflow to run. :type wname: str :param data: objects to run through the workflow. :type data: l...
[ "Run", "a", "workflow", "by", "name", "with", "list", "of", "data", "objects", "." ]
9c09fd29509a3db975ac2aba337e6760d8cfd3c2
https://github.com/inveniosoftware-contrib/invenio-workflows/blob/9c09fd29509a3db975ac2aba337e6760d8cfd3c2/invenio_workflows/worker_engine.py#L30-L62
train
Run a workflow by name with list of data objects.
inveniosoftware-contrib/invenio-workflows
invenio_workflows/worker_engine.py
restart_worker
def restart_worker(uuid, **kwargs): """Restart workflow from beginning with given engine UUID and any data. ``**kwargs`` can be used to pass custom arguments to the engine/object such as ``data``. If ``data`` is not specified then it will load all initial data for the data objects. Data can be spe...
python
def restart_worker(uuid, **kwargs): """Restart workflow from beginning with given engine UUID and any data. ``**kwargs`` can be used to pass custom arguments to the engine/object such as ``data``. If ``data`` is not specified then it will load all initial data for the data objects. Data can be spe...
[ "def", "restart_worker", "(", "uuid", ",", "*", "*", "kwargs", ")", ":", "if", "'stop_on_halt'", "not", "in", "kwargs", ":", "kwargs", "[", "'stop_on_halt'", "]", "=", "False", "engine", "=", "WorkflowEngine", ".", "from_uuid", "(", "uuid", "=", "uuid", ...
Restart workflow from beginning with given engine UUID and any data. ``**kwargs`` can be used to pass custom arguments to the engine/object such as ``data``. If ``data`` is not specified then it will load all initial data for the data objects. Data can be specified as list of objects or single id of ...
[ "Restart", "workflow", "from", "beginning", "with", "given", "engine", "UUID", "and", "any", "data", "." ]
9c09fd29509a3db975ac2aba337e6760d8cfd3c2
https://github.com/inveniosoftware-contrib/invenio-workflows/blob/9c09fd29509a3db975ac2aba337e6760d8cfd3c2/invenio_workflows/worker_engine.py#L65-L95
train
Restarts the workflow from beginning with given engine UUID and any data.
inveniosoftware-contrib/invenio-workflows
invenio_workflows/worker_engine.py
continue_worker
def continue_worker(oid, restart_point="continue_next", **kwargs): """Restart workflow with given id (uuid) at given point. By providing the ``restart_point`` you can change the point of which the workflow will continue from. * restart_prev: will restart from the previous task * continue_next: wil...
python
def continue_worker(oid, restart_point="continue_next", **kwargs): """Restart workflow with given id (uuid) at given point. By providing the ``restart_point`` you can change the point of which the workflow will continue from. * restart_prev: will restart from the previous task * continue_next: wil...
[ "def", "continue_worker", "(", "oid", ",", "restart_point", "=", "\"continue_next\"", ",", "*", "*", "kwargs", ")", ":", "if", "'stop_on_halt'", "not", "in", "kwargs", ":", "kwargs", "[", "'stop_on_halt'", "]", "=", "False", "workflow_object", "=", "workflow_o...
Restart workflow with given id (uuid) at given point. By providing the ``restart_point`` you can change the point of which the workflow will continue from. * restart_prev: will restart from the previous task * continue_next: will continue to the next task (default) * restart_task: will restart the...
[ "Restart", "workflow", "with", "given", "id", "(", "uuid", ")", "at", "given", "point", "." ]
9c09fd29509a3db975ac2aba337e6760d8cfd3c2
https://github.com/inveniosoftware-contrib/invenio-workflows/blob/9c09fd29509a3db975ac2aba337e6760d8cfd3c2/invenio_workflows/worker_engine.py#L98-L133
train
Restarts the workflow with given id at given point.
inveniosoftware-contrib/invenio-workflows
invenio_workflows/worker_engine.py
get_workflow_object_instances
def get_workflow_object_instances(data, engine): """Analyze data and create corresponding WorkflowObjects. Wrap each item in the given list of data objects into WorkflowObject instances - creating appropriate status of objects in the database and returning a list of these objects. This process is ...
python
def get_workflow_object_instances(data, engine): """Analyze data and create corresponding WorkflowObjects. Wrap each item in the given list of data objects into WorkflowObject instances - creating appropriate status of objects in the database and returning a list of these objects. This process is ...
[ "def", "get_workflow_object_instances", "(", "data", ",", "engine", ")", ":", "workflow_objects", "=", "[", "]", "data_type", "=", "engine", ".", "get_default_data_type", "(", ")", "for", "data_object", "in", "data", ":", "if", "isinstance", "(", "data_object", ...
Analyze data and create corresponding WorkflowObjects. Wrap each item in the given list of data objects into WorkflowObject instances - creating appropriate status of objects in the database and returning a list of these objects. This process is necessary to save an initial status of the data before ...
[ "Analyze", "data", "and", "create", "corresponding", "WorkflowObjects", "." ]
9c09fd29509a3db975ac2aba337e6760d8cfd3c2
https://github.com/inveniosoftware-contrib/invenio-workflows/blob/9c09fd29509a3db975ac2aba337e6760d8cfd3c2/invenio_workflows/worker_engine.py#L136-L184
train
Analyze data and create corresponding WorkflowObjects.
inveniosoftware-contrib/invenio-workflows
invenio_workflows/worker_engine.py
create_data_object_from_data
def create_data_object_from_data(data_object, engine, data_type): """Create a new WorkflowObject from given data and return it. Returns a data object wrapped around data_object given. :param data_object: object containing the data :type data_object: object :param engine: Instance of Workflow that...
python
def create_data_object_from_data(data_object, engine, data_type): """Create a new WorkflowObject from given data and return it. Returns a data object wrapped around data_object given. :param data_object: object containing the data :type data_object: object :param engine: Instance of Workflow that...
[ "def", "create_data_object_from_data", "(", "data_object", ",", "engine", ",", "data_type", ")", ":", "# Data is not already a WorkflowObject, we first", "# create an initial object for each data object.", "return", "workflow_object_class", ".", "create", "(", "data", "=", "dat...
Create a new WorkflowObject from given data and return it. Returns a data object wrapped around data_object given. :param data_object: object containing the data :type data_object: object :param engine: Instance of Workflow that is currently running. :type engine: py:class:`.engine.WorkflowEngine...
[ "Create", "a", "new", "WorkflowObject", "from", "given", "data", "and", "return", "it", "." ]
9c09fd29509a3db975ac2aba337e6760d8cfd3c2
https://github.com/inveniosoftware-contrib/invenio-workflows/blob/9c09fd29509a3db975ac2aba337e6760d8cfd3c2/invenio_workflows/worker_engine.py#L187-L210
train
Create a new WorkflowObject from given data and return it.
makerj/heconvert
heconvert/keyboard/ksx5002/core.py
h2e
def h2e(string): """ Convert hangul to english. ('한영타' -> 'gksdudxk') :param string: hangul that actually represent english string :return: converted english string """ result = [] for c in string: ccode = ord(c) # Character code if 0x3131 <= ccode <= 0x3163: # Hangul Comp...
python
def h2e(string): """ Convert hangul to english. ('한영타' -> 'gksdudxk') :param string: hangul that actually represent english string :return: converted english string """ result = [] for c in string: ccode = ord(c) # Character code if 0x3131 <= ccode <= 0x3163: # Hangul Comp...
[ "def", "h2e", "(", "string", ")", ":", "result", "=", "[", "]", "for", "c", "in", "string", ":", "ccode", "=", "ord", "(", "c", ")", "# Character code", "if", "0x3131", "<=", "ccode", "<=", "0x3163", ":", "# Hangul Compatibility Jamo", "result", ".", "...
Convert hangul to english. ('한영타' -> 'gksdudxk') :param string: hangul that actually represent english string :return: converted english string
[ "Convert", "hangul", "to", "english", ".", "(", "한영타", "-", ">", "gksdudxk", ")", ":", "param", "string", ":", "hangul", "that", "actually", "represent", "english", "string", ":", "return", ":", "converted", "english", "string" ]
67c07bc85f122f09a5d55e6dc929afb1d52d2580
https://github.com/makerj/heconvert/blob/67c07bc85f122f09a5d55e6dc929afb1d52d2580/heconvert/keyboard/ksx5002/core.py#L22-L45
train
Convert a string from Hangul to English.
makerj/heconvert
heconvert/keyboard/ksx5002/core.py
e2h
def e2h(string): """ Convert english to hangul. ('gksdudxk' -> '한영타') During processing, state interleaves INIT, LEAD_GIVEN, MEDI_GIVEN and TAIL_GIVEN :param string: english that actually represent hangul string :return: converted hangul string """ ctx = Context(string) for char in ctx....
python
def e2h(string): """ Convert english to hangul. ('gksdudxk' -> '한영타') During processing, state interleaves INIT, LEAD_GIVEN, MEDI_GIVEN and TAIL_GIVEN :param string: english that actually represent hangul string :return: converted hangul string """ ctx = Context(string) for char in ctx....
[ "def", "e2h", "(", "string", ")", ":", "ctx", "=", "Context", "(", "string", ")", "for", "char", "in", "ctx", ".", "input", ":", "hchar", "=", "E2H_MAPPING", ".", "get", "(", "char", ")", "if", "not", "char", ".", "isalpha", "(", ")", "or", "not"...
Convert english to hangul. ('gksdudxk' -> '한영타') During processing, state interleaves INIT, LEAD_GIVEN, MEDI_GIVEN and TAIL_GIVEN :param string: english that actually represent hangul string :return: converted hangul string
[ "Convert", "english", "to", "hangul", ".", "(", "gksdudxk", "-", ">", "한영타", ")", "During", "processing", "state", "interleaves", "INIT", "LEAD_GIVEN", "MEDI_GIVEN", "and", "TAIL_GIVEN" ]
67c07bc85f122f09a5d55e6dc929afb1d52d2580
https://github.com/makerj/heconvert/blob/67c07bc85f122f09a5d55e6dc929afb1d52d2580/heconvert/keyboard/ksx5002/core.py#L48-L129
train
Convert english to hangul.
makerj/heconvert
heconvert/keyboard/ksx5002/core.py
compose
def compose(lead, medi, tail=0): """ Compose hangul using given consonant and vowel :param lead: lead consonant :param medi: medial vowel :param tail: tail consonant if any :return: composed hangul character """ tail_remainder = None lead = JA_LEAD.index(lead) * 588 medi = MO....
python
def compose(lead, medi, tail=0): """ Compose hangul using given consonant and vowel :param lead: lead consonant :param medi: medial vowel :param tail: tail consonant if any :return: composed hangul character """ tail_remainder = None lead = JA_LEAD.index(lead) * 588 medi = MO....
[ "def", "compose", "(", "lead", ",", "medi", ",", "tail", "=", "0", ")", ":", "tail_remainder", "=", "None", "lead", "=", "JA_LEAD", ".", "index", "(", "lead", ")", "*", "588", "medi", "=", "MO", ".", "index", "(", "medi", ")", "*", "28", "if", ...
Compose hangul using given consonant and vowel :param lead: lead consonant :param medi: medial vowel :param tail: tail consonant if any :return: composed hangul character
[ "Compose", "hangul", "using", "given", "consonant", "and", "vowel", ":", "param", "lead", ":", "lead", "consonant", ":", "param", "medi", ":", "medial", "vowel", ":", "param", "tail", ":", "tail", "consonant", "if", "any", ":", "return", ":", "composed", ...
67c07bc85f122f09a5d55e6dc929afb1d52d2580
https://github.com/makerj/heconvert/blob/67c07bc85f122f09a5d55e6dc929afb1d52d2580/heconvert/keyboard/ksx5002/core.py#L132-L152
train
Compose a single character from a given consonant and medial vowel.
cloudmesh-cmd3/cmd3
cmd3/plugins/rst.py
rst._print_rst
def _print_rst(self, what): """ prints the rst page of the command what :param what: the command :type what: string """ print print "Command - %s::" % what exec ("h = self.do_%s.__doc__" % what) # noinspection PyUnboundLocalVariable h =...
python
def _print_rst(self, what): """ prints the rst page of the command what :param what: the command :type what: string """ print print "Command - %s::" % what exec ("h = self.do_%s.__doc__" % what) # noinspection PyUnboundLocalVariable h =...
[ "def", "_print_rst", "(", "self", ",", "what", ")", ":", "print", "print", "\"Command - %s::\"", "%", "what", "exec", "(", "\"h = self.do_%s.__doc__\"", "%", "what", ")", "# noinspection PyUnboundLocalVariable", "h", "=", "textwrap", ".", "dedent", "(", "h", ")"...
prints the rst page of the command what :param what: the command :type what: string
[ "prints", "the", "rst", "page", "of", "the", "command", "what" ]
92e33c96032fd3921f159198a0e57917c4dc34ed
https://github.com/cloudmesh-cmd3/cmd3/blob/92e33c96032fd3921f159198a0e57917c4dc34ed/cmd3/plugins/rst.py#L11-L27
train
Prints the rst page of the command what
cloudmesh-cmd3/cmd3
cmd3/plugins/rst.py
rst.do_man
def do_man(self, args, arguments): """ :: Usage: man COMMAND man [--noheader] Options: --norule no rst header Arguments: COMMAND the command to be printed Descript...
python
def do_man(self, args, arguments): """ :: Usage: man COMMAND man [--noheader] Options: --norule no rst header Arguments: COMMAND the command to be printed Descript...
[ "def", "do_man", "(", "self", ",", "args", ",", "arguments", ")", ":", "if", "arguments", "[", "'COMMAND'", "]", "is", "None", ":", "print", "print", "\"Commands\"", "print", "70", "*", "\"=\"", "commands", "=", "[", "k", "for", "k", "in", "dir", "("...
:: Usage: man COMMAND man [--noheader] Options: --norule no rst header Arguments: COMMAND the command to be printed Description: man Prints ou...
[ "::", "Usage", ":", "man", "COMMAND", "man", "[", "--", "noheader", "]" ]
92e33c96032fd3921f159198a0e57917c4dc34ed
https://github.com/cloudmesh-cmd3/cmd3/blob/92e33c96032fd3921f159198a0e57917c4dc34ed/cmd3/plugins/rst.py#L30-L72
train
Command help page
garenchan/policy
policy/enforcer.py
Rules.load_json
def load_json(cls, data, default_rule=None, raise_error=False): """Allow loading of JSON rule data.""" rules = {k: _parser.parse_rule(v, raise_error) for k, v in json.loads(data).items()} return cls(rules, default_rule)
python
def load_json(cls, data, default_rule=None, raise_error=False): """Allow loading of JSON rule data.""" rules = {k: _parser.parse_rule(v, raise_error) for k, v in json.loads(data).items()} return cls(rules, default_rule)
[ "def", "load_json", "(", "cls", ",", "data", ",", "default_rule", "=", "None", ",", "raise_error", "=", "False", ")", ":", "rules", "=", "{", "k", ":", "_parser", ".", "parse_rule", "(", "v", ",", "raise_error", ")", "for", "k", ",", "v", "in", "js...
Allow loading of JSON rule data.
[ "Allow", "loading", "of", "JSON", "rule", "data", "." ]
7709ae5f371146f8c90380d0877a5e59d731f644
https://github.com/garenchan/policy/blob/7709ae5f371146f8c90380d0877a5e59d731f644/policy/enforcer.py#L30-L36
train
Allow loading of JSON rule data.
garenchan/policy
policy/enforcer.py
Rules.from_dict
def from_dict(cls, rules_dict: dict, default_rule=None, raise_error=False): """Allow loading of rule data from a dictionary.""" # Parse the rules stored in the dictionary rules = {k: _parser.parse_rule(v, raise_error) for k, v in rules_dict.items()} return cls(rules, d...
python
def from_dict(cls, rules_dict: dict, default_rule=None, raise_error=False): """Allow loading of rule data from a dictionary.""" # Parse the rules stored in the dictionary rules = {k: _parser.parse_rule(v, raise_error) for k, v in rules_dict.items()} return cls(rules, d...
[ "def", "from_dict", "(", "cls", ",", "rules_dict", ":", "dict", ",", "default_rule", "=", "None", ",", "raise_error", "=", "False", ")", ":", "# Parse the rules stored in the dictionary", "rules", "=", "{", "k", ":", "_parser", ".", "parse_rule", "(", "v", "...
Allow loading of rule data from a dictionary.
[ "Allow", "loading", "of", "rule", "data", "from", "a", "dictionary", "." ]
7709ae5f371146f8c90380d0877a5e59d731f644
https://github.com/garenchan/policy/blob/7709ae5f371146f8c90380d0877a5e59d731f644/policy/enforcer.py#L39-L46
train
Allow loading of rule data from a dictionary.
garenchan/policy
policy/enforcer.py
Enforcer._set_rules
def _set_rules(self, rules: dict, overwrite=True): """Created a new Rules object based on the provided dict of rules.""" if not isinstance(rules, dict): raise TypeError('rules must be an instance of dict or Rules,' 'got %r instead' % type(rules)) if over...
python
def _set_rules(self, rules: dict, overwrite=True): """Created a new Rules object based on the provided dict of rules.""" if not isinstance(rules, dict): raise TypeError('rules must be an instance of dict or Rules,' 'got %r instead' % type(rules)) if over...
[ "def", "_set_rules", "(", "self", ",", "rules", ":", "dict", ",", "overwrite", "=", "True", ")", ":", "if", "not", "isinstance", "(", "rules", ",", "dict", ")", ":", "raise", "TypeError", "(", "'rules must be an instance of dict or Rules,'", "'got %r instead'", ...
Created a new Rules object based on the provided dict of rules.
[ "Created", "a", "new", "Rules", "object", "based", "on", "the", "provided", "dict", "of", "rules", "." ]
7709ae5f371146f8c90380d0877a5e59d731f644
https://github.com/garenchan/policy/blob/7709ae5f371146f8c90380d0877a5e59d731f644/policy/enforcer.py#L103-L113
train
Create a new Rules object based on the provided dict of rules.
garenchan/policy
policy/enforcer.py
Enforcer.load_rules
def load_rules(self, force_reload=False, overwrite=True): """Load rules from policy file or cache.""" # double-checked locking if self.load_once and self._policy_loaded: return with self._load_lock: if self.load_once and self._policy_loaded: retur...
python
def load_rules(self, force_reload=False, overwrite=True): """Load rules from policy file or cache.""" # double-checked locking if self.load_once and self._policy_loaded: return with self._load_lock: if self.load_once and self._policy_loaded: retur...
[ "def", "load_rules", "(", "self", ",", "force_reload", "=", "False", ",", "overwrite", "=", "True", ")", ":", "# double-checked locking", "if", "self", ".", "load_once", "and", "self", ".", "_policy_loaded", ":", "return", "with", "self", ".", "_load_lock", ...
Load rules from policy file or cache.
[ "Load", "rules", "from", "policy", "file", "or", "cache", "." ]
7709ae5f371146f8c90380d0877a5e59d731f644
https://github.com/garenchan/policy/blob/7709ae5f371146f8c90380d0877a5e59d731f644/policy/enforcer.py#L115-L131
train
Load rules from policy file or cache.
garenchan/policy
policy/enforcer.py
Enforcer.enforce
def enforce(self, rule, target, creds, exc=None, *args, **kwargs): """Checks authorization of a rule against the target and credentials.""" self.load_rules() if isinstance(rule, checks.BaseCheck): result = rule(target, creds, self, rule) elif not self.rules: # N...
python
def enforce(self, rule, target, creds, exc=None, *args, **kwargs): """Checks authorization of a rule against the target and credentials.""" self.load_rules() if isinstance(rule, checks.BaseCheck): result = rule(target, creds, self, rule) elif not self.rules: # N...
[ "def", "enforce", "(", "self", ",", "rule", ",", "target", ",", "creds", ",", "exc", "=", "None", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "load_rules", "(", ")", "if", "isinstance", "(", "rule", ",", "checks", ".", "Base...
Checks authorization of a rule against the target and credentials.
[ "Checks", "authorization", "of", "a", "rule", "against", "the", "target", "and", "credentials", "." ]
7709ae5f371146f8c90380d0877a5e59d731f644
https://github.com/garenchan/policy/blob/7709ae5f371146f8c90380d0877a5e59d731f644/policy/enforcer.py#L133-L158
train
Enforces a rule against the target and credentials.
seung-lab/EMAnnotationSchemas
emannotationschemas/utils.py
get_flattened_bsp_keys_from_schema
def get_flattened_bsp_keys_from_schema(schema): """ Returns the flattened keys of BoundSpatialPoints in a schema :param schema: schema :return: list """ keys = [] for key in schema.declared_fields.keys(): field = schema.declared_fields[key] if isinstance(field, mm.fields.Neste...
python
def get_flattened_bsp_keys_from_schema(schema): """ Returns the flattened keys of BoundSpatialPoints in a schema :param schema: schema :return: list """ keys = [] for key in schema.declared_fields.keys(): field = schema.declared_fields[key] if isinstance(field, mm.fields.Neste...
[ "def", "get_flattened_bsp_keys_from_schema", "(", "schema", ")", ":", "keys", "=", "[", "]", "for", "key", "in", "schema", ".", "declared_fields", ".", "keys", "(", ")", ":", "field", "=", "schema", ".", "declared_fields", "[", "key", "]", "if", "isinstanc...
Returns the flattened keys of BoundSpatialPoints in a schema :param schema: schema :return: list
[ "Returns", "the", "flattened", "keys", "of", "BoundSpatialPoints", "in", "a", "schema" ]
ca81eff0f449bd7eb0392e0982db8f3636446a9e
https://github.com/seung-lab/EMAnnotationSchemas/blob/ca81eff0f449bd7eb0392e0982db8f3636446a9e/emannotationschemas/utils.py#L14-L29
train
Returns the flattened keys of BoundSpatialPoints in a schema
jstitch/MambuPy
MambuPy/rest/mambuactivity.py
MambuActivities.convertDict2Attrs
def convertDict2Attrs(self, *args, **kwargs): """The trick for iterable Mambu Objects comes here: You iterate over each element of the responded List from Mambu, and create a Mambu Activity object for each one, initializing them one at a time, and changing the attrs attribute (which jus...
python
def convertDict2Attrs(self, *args, **kwargs): """The trick for iterable Mambu Objects comes here: You iterate over each element of the responded List from Mambu, and create a Mambu Activity object for each one, initializing them one at a time, and changing the attrs attribute (which jus...
[ "def", "convertDict2Attrs", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "for", "n", ",", "a", "in", "enumerate", "(", "self", ".", "attrs", ")", ":", "# ok ok, I'm modifying elements of a list while iterating it. BAD PRACTICE!", "try", ":",...
The trick for iterable Mambu Objects comes here: You iterate over each element of the responded List from Mambu, and create a Mambu Activity object for each one, initializing them one at a time, and changing the attrs attribute (which just holds a list of plain dictionaries) with a Mamb...
[ "The", "trick", "for", "iterable", "Mambu", "Objects", "comes", "here", ":" ]
2af98cc12e7ed5ec183b3e97644e880e70b79ee8
https://github.com/jstitch/MambuPy/blob/2af98cc12e7ed5ec183b3e97644e880e70b79ee8/MambuPy/rest/mambuactivity.py#L67-L90
train
This method converts a dictionary of Mambu objects into a list of Mambu Activity objects.
BernardFW/bernard
src/bernard/engine/triggers.py
SharedTrigger.lock
def lock(self) -> asyncio.Lock: """ Return and generate if required the lock for this request. """ if self.lock_key not in self.request.custom_content: self.request.custom_content[self.lock_key] = asyncio.Lock() return self.request.custom_content[self.lock_key]
python
def lock(self) -> asyncio.Lock: """ Return and generate if required the lock for this request. """ if self.lock_key not in self.request.custom_content: self.request.custom_content[self.lock_key] = asyncio.Lock() return self.request.custom_content[self.lock_key]
[ "def", "lock", "(", "self", ")", "->", "asyncio", ".", "Lock", ":", "if", "self", ".", "lock_key", "not", "in", "self", ".", "request", ".", "custom_content", ":", "self", ".", "request", ".", "custom_content", "[", "self", ".", "lock_key", "]", "=", ...
Return and generate if required the lock for this request.
[ "Return", "and", "generate", "if", "required", "the", "lock", "for", "this", "request", "." ]
9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab
https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/engine/triggers.py#L94-L102
train
Return and generate if required the lock for this request.
BernardFW/bernard
src/bernard/engine/triggers.py
SharedTrigger.get_value
async def get_value(self): """ Get the value from the API. Make sure to use a lock in order not to fetch the value twice at the same time. """ cc = self.request.custom_content async with self.lock: if self.content_key not in cc: cc[self.conte...
python
async def get_value(self): """ Get the value from the API. Make sure to use a lock in order not to fetch the value twice at the same time. """ cc = self.request.custom_content async with self.lock: if self.content_key not in cc: cc[self.conte...
[ "async", "def", "get_value", "(", "self", ")", ":", "cc", "=", "self", ".", "request", ".", "custom_content", "async", "with", "self", ".", "lock", ":", "if", "self", ".", "content_key", "not", "in", "cc", ":", "cc", "[", "self", ".", "content_key", ...
Get the value from the API. Make sure to use a lock in order not to fetch the value twice at the same time.
[ "Get", "the", "value", "from", "the", "API", ".", "Make", "sure", "to", "use", "a", "lock", "in", "order", "not", "to", "fetch", "the", "value", "twice", "at", "the", "same", "time", "." ]
9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab
https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/engine/triggers.py#L119-L131
train
Get the value from the API.
BernardFW/bernard
src/bernard/engine/triggers.py
Text.rank
async def rank(self) -> Optional[float]: """ If there is a text layer inside the request, try to find a matching text in the specified intent. """ if not self.request.has_layer(l.RawText): return tl = self.request.get_layer(l.RawText) matcher = Match...
python
async def rank(self) -> Optional[float]: """ If there is a text layer inside the request, try to find a matching text in the specified intent. """ if not self.request.has_layer(l.RawText): return tl = self.request.get_layer(l.RawText) matcher = Match...
[ "async", "def", "rank", "(", "self", ")", "->", "Optional", "[", "float", "]", ":", "if", "not", "self", ".", "request", ".", "has_layer", "(", "l", ".", "RawText", ")", ":", "return", "tl", "=", "self", ".", "request", ".", "get_layer", "(", "l", ...
If there is a text layer inside the request, try to find a matching text in the specified intent.
[ "If", "there", "is", "a", "text", "layer", "inside", "the", "request", "try", "to", "find", "a", "matching", "text", "in", "the", "specified", "intent", "." ]
9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab
https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/engine/triggers.py#L163-L178
train
Return the rank of the current text layer.
BernardFW/bernard
src/bernard/engine/triggers.py
Choice._rank_qr
def _rank_qr(self, choices): """ Look for the QuickReply layer's slug into available choices. """ from bernard.platforms.facebook import layers as fbl try: qr = self.request.get_layer(fbl.QuickReply) self.chosen = choices[qr.slug] self.slug = ...
python
def _rank_qr(self, choices): """ Look for the QuickReply layer's slug into available choices. """ from bernard.platforms.facebook import layers as fbl try: qr = self.request.get_layer(fbl.QuickReply) self.chosen = choices[qr.slug] self.slug = ...
[ "def", "_rank_qr", "(", "self", ",", "choices", ")", ":", "from", "bernard", ".", "platforms", ".", "facebook", "import", "layers", "as", "fbl", "try", ":", "qr", "=", "self", ".", "request", ".", "get_layer", "(", "fbl", ".", "QuickReply", ")", "self"...
Look for the QuickReply layer's slug into available choices.
[ "Look", "for", "the", "QuickReply", "layer", "s", "slug", "into", "available", "choices", "." ]
9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab
https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/engine/triggers.py#L200-L214
train
Rank the QuickReply layer into available choices.
BernardFW/bernard
src/bernard/engine/triggers.py
Choice._rank_text
async def _rank_text(self, choices): """ Try to match the TextLayer with choice's intents. """ tl = self.request.get_layer(l.RawText) best = 0.0 for slug, params in choices.items(): strings = [] if params['intent']: intent = geta...
python
async def _rank_text(self, choices): """ Try to match the TextLayer with choice's intents. """ tl = self.request.get_layer(l.RawText) best = 0.0 for slug, params in choices.items(): strings = [] if params['intent']: intent = geta...
[ "async", "def", "_rank_text", "(", "self", ",", "choices", ")", ":", "tl", "=", "self", ".", "request", ".", "get_layer", "(", "l", ".", "RawText", ")", "best", "=", "0.0", "for", "slug", ",", "params", "in", "choices", ".", "items", "(", ")", ":",...
Try to match the TextLayer with choice's intents.
[ "Try", "to", "match", "the", "TextLayer", "with", "choice", "s", "intents", "." ]
9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab
https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/engine/triggers.py#L216-L243
train
Rank the text layer with the choices.
BernardFW/bernard
src/bernard/engine/triggers.py
Choice.rank
async def rank(self): """ Try to find a choice in what the user did: - If there is a quick reply, then use its payload as choice slug - Otherwise, try to match each choice with its intent """ from bernard.platforms.facebook import layers as fbl choices = self.re...
python
async def rank(self): """ Try to find a choice in what the user did: - If there is a quick reply, then use its payload as choice slug - Otherwise, try to match each choice with its intent """ from bernard.platforms.facebook import layers as fbl choices = self.re...
[ "async", "def", "rank", "(", "self", ")", ":", "from", "bernard", ".", "platforms", ".", "facebook", "import", "layers", "as", "fbl", "choices", "=", "self", ".", "request", ".", "get_trans_reg", "(", "'choices'", ")", "if", "not", "choices", ":", "retur...
Try to find a choice in what the user did: - If there is a quick reply, then use its payload as choice slug - Otherwise, try to match each choice with its intent
[ "Try", "to", "find", "a", "choice", "in", "what", "the", "user", "did", ":" ]
9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab
https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/engine/triggers.py#L246-L263
train
Try to find a choice in the user s list of available items.
ioos/cc-plugin-ncei
cc_plugin_ncei/ncei_timeseries.py
NCEITimeSeriesOrthogonalBase.check_timeseries_id
def check_timeseries_id(self, dataset): ''' Checks that if a variable exists for the time series id it has the appropriate attributes :param netCDF4.Dataset dataset: An open netCDF dataset ''' timeseries_ids = dataset.get_variables_by_attributes(cf_role='timeseries_id') ...
python
def check_timeseries_id(self, dataset): ''' Checks that if a variable exists for the time series id it has the appropriate attributes :param netCDF4.Dataset dataset: An open netCDF dataset ''' timeseries_ids = dataset.get_variables_by_attributes(cf_role='timeseries_id') ...
[ "def", "check_timeseries_id", "(", "self", ",", "dataset", ")", ":", "timeseries_ids", "=", "dataset", ".", "get_variables_by_attributes", "(", "cf_role", "=", "'timeseries_id'", ")", "# No need to check", "if", "not", "timeseries_ids", ":", "return", "test_ctx", "=...
Checks that if a variable exists for the time series id it has the appropriate attributes :param netCDF4.Dataset dataset: An open netCDF dataset
[ "Checks", "that", "if", "a", "variable", "exists", "for", "the", "time", "series", "id", "it", "has", "the", "appropriate", "attributes" ]
963fefd7fa43afd32657ac4c36aad4ddb4c25acf
https://github.com/ioos/cc-plugin-ncei/blob/963fefd7fa43afd32657ac4c36aad4ddb4c25acf/cc_plugin_ncei/ncei_timeseries.py#L37-L53
train
Checks that a variable exists for the time series id it has the appropriate attributes for the timeSeries variable.
ioos/cc-plugin-ncei
cc_plugin_ncei/ncei_timeseries.py
NCEITimeSeriesOrthogonal2_0.check_recommended_attributes
def check_recommended_attributes(self, dataset): ''' Feature type specific check of global recommended attributes. :param netCDF4.Dataset dataset: An open netCDF dataset ''' results = [] recommended_ctx = TestCtx(BaseCheck.MEDIUM, 'Recommended global attributes') ...
python
def check_recommended_attributes(self, dataset): ''' Feature type specific check of global recommended attributes. :param netCDF4.Dataset dataset: An open netCDF dataset ''' results = [] recommended_ctx = TestCtx(BaseCheck.MEDIUM, 'Recommended global attributes') ...
[ "def", "check_recommended_attributes", "(", "self", ",", "dataset", ")", ":", "results", "=", "[", "]", "recommended_ctx", "=", "TestCtx", "(", "BaseCheck", ".", "MEDIUM", ",", "'Recommended global attributes'", ")", "# Check time_coverage_duration and resolution", "for...
Feature type specific check of global recommended attributes. :param netCDF4.Dataset dataset: An open netCDF dataset
[ "Feature", "type", "specific", "check", "of", "global", "recommended", "attributes", "." ]
963fefd7fa43afd32657ac4c36aad4ddb4c25acf
https://github.com/ioos/cc-plugin-ncei/blob/963fefd7fa43afd32657ac4c36aad4ddb4c25acf/cc_plugin_ncei/ncei_timeseries.py#L154-L171
train
Feature type specific check of global recommended attributes.
ioos/cc-plugin-ncei
cc_plugin_ncei/ncei_timeseries.py
NCEITimeSeriesIncompleteBase.check_dimensions
def check_dimensions(self, dataset): ''' Checks that the feature types of this dataset are consitent with a time series incomplete dataset :param netCDF4.Dataset dataset: An open netCDF dataset ''' required_ctx = TestCtx(BaseCheck.HIGH, 'All geophysical variables are time-series...
python
def check_dimensions(self, dataset): ''' Checks that the feature types of this dataset are consitent with a time series incomplete dataset :param netCDF4.Dataset dataset: An open netCDF dataset ''' required_ctx = TestCtx(BaseCheck.HIGH, 'All geophysical variables are time-series...
[ "def", "check_dimensions", "(", "self", ",", "dataset", ")", ":", "required_ctx", "=", "TestCtx", "(", "BaseCheck", ".", "HIGH", ",", "'All geophysical variables are time-series incomplete feature types'", ")", "message", "=", "'{} must be a valid timeseries feature type. It ...
Checks that the feature types of this dataset are consitent with a time series incomplete dataset :param netCDF4.Dataset dataset: An open netCDF dataset
[ "Checks", "that", "the", "feature", "types", "of", "this", "dataset", "are", "consitent", "with", "a", "time", "series", "incomplete", "dataset" ]
963fefd7fa43afd32657ac4c36aad4ddb4c25acf
https://github.com/ioos/cc-plugin-ncei/blob/963fefd7fa43afd32657ac4c36aad4ddb4c25acf/cc_plugin_ncei/ncei_timeseries.py#L181-L196
train
Checks that the feature types of this dataset are consitent with a time series incomplete dataset
ioos/cc-plugin-ncei
cc_plugin_ncei/ncei_timeseries.py
NCEITimeSeriesIncompleteBase.check_timeseries_id
def check_timeseries_id(self, dataset): ''' Checks that if a variable exists for the time series id it has the appropriate attributes :param netCDF4.Dataset dataset: An open netCDF dataset ''' results = [] required_ctx = TestCtx(BaseCheck.HIGH, 'Required variable for tim...
python
def check_timeseries_id(self, dataset): ''' Checks that if a variable exists for the time series id it has the appropriate attributes :param netCDF4.Dataset dataset: An open netCDF dataset ''' results = [] required_ctx = TestCtx(BaseCheck.HIGH, 'Required variable for tim...
[ "def", "check_timeseries_id", "(", "self", ",", "dataset", ")", ":", "results", "=", "[", "]", "required_ctx", "=", "TestCtx", "(", "BaseCheck", ".", "HIGH", ",", "'Required variable for time series identifier'", ")", "recommended_ctx", "=", "TestCtx", "(", "BaseC...
Checks that if a variable exists for the time series id it has the appropriate attributes :param netCDF4.Dataset dataset: An open netCDF dataset
[ "Checks", "that", "if", "a", "variable", "exists", "for", "the", "time", "series", "id", "it", "has", "the", "appropriate", "attributes" ]
963fefd7fa43afd32657ac4c36aad4ddb4c25acf
https://github.com/ioos/cc-plugin-ncei/blob/963fefd7fa43afd32657ac4c36aad4ddb4c25acf/cc_plugin_ncei/ncei_timeseries.py#L198-L229
train
Checks that a variable exists for the time series identifier it has the appropriate attributes for the time series variable.
garenchan/policy
policy/_cache.py
read_file
def read_file(filename: str, force_reload=False): """Read a file if it has been modified. :param filename: File name which want to be read from. :param force_reload: Whether to reload the file. :returns: A tuple with a boolean specifying if the data is fresh or not. """ if force_reload: ...
python
def read_file(filename: str, force_reload=False): """Read a file if it has been modified. :param filename: File name which want to be read from. :param force_reload: Whether to reload the file. :returns: A tuple with a boolean specifying if the data is fresh or not. """ if force_reload: ...
[ "def", "read_file", "(", "filename", ":", "str", ",", "force_reload", "=", "False", ")", ":", "if", "force_reload", ":", "_delete_cached_file", "(", "filename", ")", "reloaded", "=", "False", "mtime", "=", "os", ".", "path", ".", "getmtime", "(", "filename...
Read a file if it has been modified. :param filename: File name which want to be read from. :param force_reload: Whether to reload the file. :returns: A tuple with a boolean specifying if the data is fresh or not.
[ "Read", "a", "file", "if", "it", "has", "been", "modified", "." ]
7709ae5f371146f8c90380d0877a5e59d731f644
https://github.com/garenchan/policy/blob/7709ae5f371146f8c90380d0877a5e59d731f644/policy/_cache.py#L19-L41
train
Read a file if it has been modified.
COALAIP/pycoalaip
coalaip/model_validators.py
is_callable
def is_callable(instance, attribute, value): """Raises a :exc:`TypeError` if the value is not a callable.""" if not callable(value): raise TypeError("'{}' must be callable".format(attribute.name))
python
def is_callable(instance, attribute, value): """Raises a :exc:`TypeError` if the value is not a callable.""" if not callable(value): raise TypeError("'{}' must be callable".format(attribute.name))
[ "def", "is_callable", "(", "instance", ",", "attribute", ",", "value", ")", ":", "if", "not", "callable", "(", "value", ")", ":", "raise", "TypeError", "(", "\"'{}' must be callable\"", ".", "format", "(", "attribute", ".", "name", ")", ")" ]
Raises a :exc:`TypeError` if the value is not a callable.
[ "Raises", "a", ":", "exc", ":", "TypeError", "if", "the", "value", "is", "not", "a", "callable", "." ]
cecc8f6ff4733f0525fafcee63647753e832f0be
https://github.com/COALAIP/pycoalaip/blob/cecc8f6ff4733f0525fafcee63647753e832f0be/coalaip/model_validators.py#L6-L10
train
Raises a : exc : TypeError if the value is not a callable.
COALAIP/pycoalaip
coalaip/model_validators.py
use_model_attr
def use_model_attr(attr): """Use the validator set on a separate attribute on the class.""" def use_model_validator(instance, attribute, value): getattr(instance, attr)(instance, attribute, value) return use_model_validator
python
def use_model_attr(attr): """Use the validator set on a separate attribute on the class.""" def use_model_validator(instance, attribute, value): getattr(instance, attr)(instance, attribute, value) return use_model_validator
[ "def", "use_model_attr", "(", "attr", ")", ":", "def", "use_model_validator", "(", "instance", ",", "attribute", ",", "value", ")", ":", "getattr", "(", "instance", ",", "attr", ")", "(", "instance", ",", "attribute", ",", "value", ")", "return", "use_mode...
Use the validator set on a separate attribute on the class.
[ "Use", "the", "validator", "set", "on", "a", "separate", "attribute", "on", "the", "class", "." ]
cecc8f6ff4733f0525fafcee63647753e832f0be
https://github.com/COALAIP/pycoalaip/blob/cecc8f6ff4733f0525fafcee63647753e832f0be/coalaip/model_validators.py#L13-L18
train
Use the validator set on a separate attribute on the class.
COALAIP/pycoalaip
coalaip/model_validators.py
does_not_contain
def does_not_contain(*avoid_keys, error_cls=ValueError): """Decorator: value must not contain any of the :attr:`avoid_keys`. """ def decorator(func): def not_contains(instance, attribute, value): instance_name = instance.__class__.__name__ num_matched_keys = len(set(avoid_k...
python
def does_not_contain(*avoid_keys, error_cls=ValueError): """Decorator: value must not contain any of the :attr:`avoid_keys`. """ def decorator(func): def not_contains(instance, attribute, value): instance_name = instance.__class__.__name__ num_matched_keys = len(set(avoid_k...
[ "def", "does_not_contain", "(", "*", "avoid_keys", ",", "error_cls", "=", "ValueError", ")", ":", "def", "decorator", "(", "func", ")", ":", "def", "not_contains", "(", "instance", ",", "attribute", ",", "value", ")", ":", "instance_name", "=", "instance", ...
Decorator: value must not contain any of the :attr:`avoid_keys`.
[ "Decorator", ":", "value", "must", "not", "contain", "any", "of", "the", ":", "attr", ":", "avoid_keys", "." ]
cecc8f6ff4733f0525fafcee63647753e832f0be
https://github.com/COALAIP/pycoalaip/blob/cecc8f6ff4733f0525fafcee63647753e832f0be/coalaip/model_validators.py#L21-L42
train
Decorator that returns a function that checks that the value of a resource attribute does not contain any of the given keys.
COALAIP/pycoalaip
coalaip/model_validators.py
is_creation_model
def is_creation_model(instance, attribute, value): """Must include at least a ``name`` key.""" creation_name = value.get('name') if not isinstance(creation_name, str): instance_name = instance.__class__.__name__ err_str = ("'name' must be given as a string in the '{attr}' " ...
python
def is_creation_model(instance, attribute, value): """Must include at least a ``name`` key.""" creation_name = value.get('name') if not isinstance(creation_name, str): instance_name = instance.__class__.__name__ err_str = ("'name' must be given as a string in the '{attr}' " ...
[ "def", "is_creation_model", "(", "instance", ",", "attribute", ",", "value", ")", ":", "creation_name", "=", "value", ".", "get", "(", "'name'", ")", "if", "not", "isinstance", "(", "creation_name", ",", "str", ")", ":", "instance_name", "=", "instance", "...
Must include at least a ``name`` key.
[ "Must", "include", "at", "least", "a", "name", "key", "." ]
cecc8f6ff4733f0525fafcee63647753e832f0be
https://github.com/COALAIP/pycoalaip/blob/cecc8f6ff4733f0525fafcee63647753e832f0be/coalaip/model_validators.py#L45-L56
train
Validate that the value is a valid creation model.
COALAIP/pycoalaip
coalaip/model_validators.py
is_manifestation_model
def is_manifestation_model(instance, attribute, value): """Must include a ``manifestationOfWork`` key.""" instance_name = instance.__class__.__name__ is_creation_model(instance, attribute, value) manifestation_of = value.get('manifestationOfWork') if not isinstance(manifestation_of, str): ...
python
def is_manifestation_model(instance, attribute, value): """Must include a ``manifestationOfWork`` key.""" instance_name = instance.__class__.__name__ is_creation_model(instance, attribute, value) manifestation_of = value.get('manifestationOfWork') if not isinstance(manifestation_of, str): ...
[ "def", "is_manifestation_model", "(", "instance", ",", "attribute", ",", "value", ")", ":", "instance_name", "=", "instance", ".", "__class__", ".", "__name__", "is_creation_model", "(", "instance", ",", "attribute", ",", "value", ")", "manifestation_of", "=", "...
Must include a ``manifestationOfWork`` key.
[ "Must", "include", "a", "manifestationOfWork", "key", "." ]
cecc8f6ff4733f0525fafcee63647753e832f0be
https://github.com/COALAIP/pycoalaip/blob/cecc8f6ff4733f0525fafcee63647753e832f0be/coalaip/model_validators.py#L68-L81
train
Check if a manifestation of the current object is a creation model.
COALAIP/pycoalaip
coalaip/model_validators.py
is_right_model
def is_right_model(instance, attribute, value): """Must include at least the ``source`` and ``license`` keys, but not a ``rightsOf`` key (``source`` indicates that the Right is derived from and allowed by a source Right; it cannot contain the full rights to a Creation). """ for key in ['source'...
python
def is_right_model(instance, attribute, value): """Must include at least the ``source`` and ``license`` keys, but not a ``rightsOf`` key (``source`` indicates that the Right is derived from and allowed by a source Right; it cannot contain the full rights to a Creation). """ for key in ['source'...
[ "def", "is_right_model", "(", "instance", ",", "attribute", ",", "value", ")", ":", "for", "key", "in", "[", "'source'", ",", "'license'", "]", ":", "key_value", "=", "value", ".", "get", "(", "key", ")", "if", "not", "isinstance", "(", "key_value", ",...
Must include at least the ``source`` and ``license`` keys, but not a ``rightsOf`` key (``source`` indicates that the Right is derived from and allowed by a source Right; it cannot contain the full rights to a Creation).
[ "Must", "include", "at", "least", "the", "source", "and", "license", "keys", "but", "not", "a", "rightsOf", "key", "(", "source", "indicates", "that", "the", "Right", "is", "derived", "from", "and", "allowed", "by", "a", "source", "Right", ";", "it", "ca...
cecc8f6ff4733f0525fafcee63647753e832f0be
https://github.com/COALAIP/pycoalaip/blob/cecc8f6ff4733f0525fafcee63647753e832f0be/coalaip/model_validators.py#L85-L101
train
Validate that the value is a dict of the right model parameters.
COALAIP/pycoalaip
coalaip/model_validators.py
is_copyright_model
def is_copyright_model(instance, attribute, value): """Must include at least a ``rightsOf`` key, but not a ``source`` key (``rightsOf`` indicates that the Right contains full rights to an existing Manifestation or Work; i.e. is a Copyright). """ rights_of = value.get('rightsOf') if not isinstan...
python
def is_copyright_model(instance, attribute, value): """Must include at least a ``rightsOf`` key, but not a ``source`` key (``rightsOf`` indicates that the Right contains full rights to an existing Manifestation or Work; i.e. is a Copyright). """ rights_of = value.get('rightsOf') if not isinstan...
[ "def", "is_copyright_model", "(", "instance", ",", "attribute", ",", "value", ")", ":", "rights_of", "=", "value", ".", "get", "(", "'rightsOf'", ")", "if", "not", "isinstance", "(", "rights_of", ",", "str", ")", ":", "instance_name", "=", "instance", ".",...
Must include at least a ``rightsOf`` key, but not a ``source`` key (``rightsOf`` indicates that the Right contains full rights to an existing Manifestation or Work; i.e. is a Copyright).
[ "Must", "include", "at", "least", "a", "rightsOf", "key", "but", "not", "a", "source", "key", "(", "rightsOf", "indicates", "that", "the", "Right", "contains", "full", "rights", "to", "an", "existing", "Manifestation", "or", "Work", ";", "i", ".", "e", "...
cecc8f6ff4733f0525fafcee63647753e832f0be
https://github.com/COALAIP/pycoalaip/blob/cecc8f6ff4733f0525fafcee63647753e832f0be/coalaip/model_validators.py#L105-L118
train
Validate that the right is a Copyright model.
klmitch/turnstile
turnstile/tools.py
add_argument
def add_argument(*args, **kwargs): """ Define an argument for the function when running in console script mode. The positional and keyword arguments are the same as for ArgumentParser.add_argument(). """ def decorator(func): func = ScriptAdaptor._wrap(func) func._add_argument(a...
python
def add_argument(*args, **kwargs): """ Define an argument for the function when running in console script mode. The positional and keyword arguments are the same as for ArgumentParser.add_argument(). """ def decorator(func): func = ScriptAdaptor._wrap(func) func._add_argument(a...
[ "def", "add_argument", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "def", "decorator", "(", "func", ")", ":", "func", "=", "ScriptAdaptor", ".", "_wrap", "(", "func", ")", "func", ".", "_add_argument", "(", "args", ",", "kwargs", ")", "retur...
Define an argument for the function when running in console script mode. The positional and keyword arguments are the same as for ArgumentParser.add_argument().
[ "Define", "an", "argument", "for", "the", "function", "when", "running", "in", "console", "script", "mode", ".", "The", "positional", "and", "keyword", "arguments", "are", "the", "same", "as", "for", "ArgumentParser", ".", "add_argument", "()", "." ]
8fe9a359b45e505d3192ab193ecf9be177ab1a17
https://github.com/klmitch/turnstile/blob/8fe9a359b45e505d3192ab193ecf9be177ab1a17/turnstile/tools.py#L241-L252
train
A decorator that adds an argument to the function when running in console script mode.
klmitch/turnstile
turnstile/tools.py
add_preprocessor
def add_preprocessor(preproc): """ Define a preprocessor to run after the arguments are parsed and before the function is executed, when running in console script mode. :param preproc: The callable, which will be passed the Namespace object generated by argparse. """ de...
python
def add_preprocessor(preproc): """ Define a preprocessor to run after the arguments are parsed and before the function is executed, when running in console script mode. :param preproc: The callable, which will be passed the Namespace object generated by argparse. """ de...
[ "def", "add_preprocessor", "(", "preproc", ")", ":", "def", "decorator", "(", "func", ")", ":", "func", "=", "ScriptAdaptor", ".", "_wrap", "(", "func", ")", "func", ".", "_add_preprocessor", "(", "preproc", ")", "return", "func", "return", "decorator" ]
Define a preprocessor to run after the arguments are parsed and before the function is executed, when running in console script mode. :param preproc: The callable, which will be passed the Namespace object generated by argparse.
[ "Define", "a", "preprocessor", "to", "run", "after", "the", "arguments", "are", "parsed", "and", "before", "the", "function", "is", "executed", "when", "running", "in", "console", "script", "mode", "." ]
8fe9a359b45e505d3192ab193ecf9be177ab1a17
https://github.com/klmitch/turnstile/blob/8fe9a359b45e505d3192ab193ecf9be177ab1a17/turnstile/tools.py#L255-L269
train
Decorator to add a preprocessor to run after the arguments are parsed and before the function is executed.
klmitch/turnstile
turnstile/tools.py
add_postprocessor
def add_postprocessor(postproc): """ Define a postprocessor to run after the function is executed, when running in console script mode. :param postproc: The callable, which will be passed the Namespace object generated by argparse and the return result of the f...
python
def add_postprocessor(postproc): """ Define a postprocessor to run after the function is executed, when running in console script mode. :param postproc: The callable, which will be passed the Namespace object generated by argparse and the return result of the f...
[ "def", "add_postprocessor", "(", "postproc", ")", ":", "def", "decorator", "(", "func", ")", ":", "func", "=", "ScriptAdaptor", ".", "_wrap", "(", "func", ")", "func", ".", "_add_postprocessor", "(", "postproc", ")", "return", "func", "return", "decorator" ]
Define a postprocessor to run after the function is executed, when running in console script mode. :param postproc: The callable, which will be passed the Namespace object generated by argparse and the return result of the function. The return result of the ...
[ "Define", "a", "postprocessor", "to", "run", "after", "the", "function", "is", "executed", "when", "running", "in", "console", "script", "mode", "." ]
8fe9a359b45e505d3192ab193ecf9be177ab1a17
https://github.com/klmitch/turnstile/blob/8fe9a359b45e505d3192ab193ecf9be177ab1a17/turnstile/tools.py#L272-L289
train
Decorator to add a postprocessor to run after the function is executed.
klmitch/turnstile
turnstile/tools.py
_setup_logging
def _setup_logging(args): """ Set up logging for the script, based on the configuration specified by the 'logging' attribute of the command line arguments. :param args: A Namespace object containing a 'logging' attribute specifying the name of a logging configuration file ...
python
def _setup_logging(args): """ Set up logging for the script, based on the configuration specified by the 'logging' attribute of the command line arguments. :param args: A Namespace object containing a 'logging' attribute specifying the name of a logging configuration file ...
[ "def", "_setup_logging", "(", "args", ")", ":", "log_conf", "=", "getattr", "(", "args", ",", "'logging'", ",", "None", ")", "if", "log_conf", ":", "logging", ".", "config", ".", "fileConfig", "(", "log_conf", ")", "else", ":", "logging", ".", "basicConf...
Set up logging for the script, based on the configuration specified by the 'logging' attribute of the command line arguments. :param args: A Namespace object containing a 'logging' attribute specifying the name of a logging configuration file to use. If not present or not...
[ "Set", "up", "logging", "for", "the", "script", "based", "on", "the", "configuration", "specified", "by", "the", "logging", "attribute", "of", "the", "command", "line", "arguments", "." ]
8fe9a359b45e505d3192ab193ecf9be177ab1a17
https://github.com/klmitch/turnstile/blob/8fe9a359b45e505d3192ab193ecf9be177ab1a17/turnstile/tools.py#L292-L308
train
Setup logging for the script based on the logging configuration file specified by the logging attribute of the command line arguments.
klmitch/turnstile
turnstile/tools.py
parse_limit_node
def parse_limit_node(db, idx, limit): """ Given an XML node describing a limit, return a Limit object. :param db: Handle for the Redis database. :param idx: The index of the limit in the XML file; used for error reporting. :param limit: The XML node describing the limit. """ ...
python
def parse_limit_node(db, idx, limit): """ Given an XML node describing a limit, return a Limit object. :param db: Handle for the Redis database. :param idx: The index of the limit in the XML file; used for error reporting. :param limit: The XML node describing the limit. """ ...
[ "def", "parse_limit_node", "(", "db", ",", "idx", ",", "limit", ")", ":", "# First, try to import the class; this will raise ImportError if", "# we can't import it", "klass", "=", "utils", ".", "find_entrypoint", "(", "'turnstile.limit'", ",", "limit", ".", "get", "(", ...
Given an XML node describing a limit, return a Limit object. :param db: Handle for the Redis database. :param idx: The index of the limit in the XML file; used for error reporting. :param limit: The XML node describing the limit.
[ "Given", "an", "XML", "node", "describing", "a", "limit", "return", "a", "Limit", "object", "." ]
8fe9a359b45e505d3192ab193ecf9be177ab1a17
https://github.com/klmitch/turnstile/blob/8fe9a359b45e505d3192ab193ecf9be177ab1a17/turnstile/tools.py#L311-L434
train
Parse an XML node describing a limit and return a Limit object.