repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
JukeboxPipeline/jukeboxmaya
src/jukeboxmaya/common.py
locknode
def locknode(node, lock=True): """Contextmanager that will lock or unlock the given node and afterwards, restore the original status :param node: the node to lock/unlock or nodes :type node: str | list | tuple :param lock: True for locking, False for unlocking :type lock: bool :returns: None :rtype: None :raises: None """ oldstatus = cmds.lockNode(node, q=1) cmds.lockNode(node, lock=lock) try: yield finally: if isinstance(node, basestring): if cmds.objExists(node): cmds.lockNode(node, lock=oldstatus[0]) else: for n, l in zip(node, oldstatus): if cmds.objExists(n): cmds.lockNode(n, lock=l)
python
def locknode(node, lock=True): """Contextmanager that will lock or unlock the given node and afterwards, restore the original status :param node: the node to lock/unlock or nodes :type node: str | list | tuple :param lock: True for locking, False for unlocking :type lock: bool :returns: None :rtype: None :raises: None """ oldstatus = cmds.lockNode(node, q=1) cmds.lockNode(node, lock=lock) try: yield finally: if isinstance(node, basestring): if cmds.objExists(node): cmds.lockNode(node, lock=oldstatus[0]) else: for n, l in zip(node, oldstatus): if cmds.objExists(n): cmds.lockNode(n, lock=l)
[ "def", "locknode", "(", "node", ",", "lock", "=", "True", ")", ":", "oldstatus", "=", "cmds", ".", "lockNode", "(", "node", ",", "q", "=", "1", ")", "cmds", ".", "lockNode", "(", "node", ",", "lock", "=", "lock", ")", "try", ":", "yield", "finally", ":", "if", "isinstance", "(", "node", ",", "basestring", ")", ":", "if", "cmds", ".", "objExists", "(", "node", ")", ":", "cmds", ".", "lockNode", "(", "node", ",", "lock", "=", "oldstatus", "[", "0", "]", ")", "else", ":", "for", "n", ",", "l", "in", "zip", "(", "node", ",", "oldstatus", ")", ":", "if", "cmds", ".", "objExists", "(", "n", ")", ":", "cmds", ".", "lockNode", "(", "n", ",", "lock", "=", "l", ")" ]
Contextmanager that will lock or unlock the given node and afterwards, restore the original status :param node: the node to lock/unlock or nodes :type node: str | list | tuple :param lock: True for locking, False for unlocking :type lock: bool :returns: None :rtype: None :raises: None
[ "Contextmanager", "that", "will", "lock", "or", "unlock", "the", "given", "node", "and", "afterwards", "restore", "the", "original", "status" ]
c8d6318d53cdb5493453c4a6b65ef75bdb2d5f2c
https://github.com/JukeboxPipeline/jukeboxmaya/blob/c8d6318d53cdb5493453c4a6b65ef75bdb2d5f2c/src/jukeboxmaya/common.py#L42-L65
train
JukeboxPipeline/jukeboxmaya
src/jukeboxmaya/common.py
get_top_namespace
def get_top_namespace(node): """Return the top namespace of the given node If the node has not namespace (only root), ":" is returned. Else the top namespace (after root) is returned :param node: the node to query :type node: str :returns: The top level namespace. :rtype: str :raises: None """ name = node.rsplit("|", 1)[-1] # get the node name, in case we get a dagpath name = name.lstrip(":") # strip the root namespace if ":" not in name: # if there is no namespace return root return ":" else: # get the top namespace return name.partition(":")[0]
python
def get_top_namespace(node): """Return the top namespace of the given node If the node has not namespace (only root), ":" is returned. Else the top namespace (after root) is returned :param node: the node to query :type node: str :returns: The top level namespace. :rtype: str :raises: None """ name = node.rsplit("|", 1)[-1] # get the node name, in case we get a dagpath name = name.lstrip(":") # strip the root namespace if ":" not in name: # if there is no namespace return root return ":" else: # get the top namespace return name.partition(":")[0]
[ "def", "get_top_namespace", "(", "node", ")", ":", "name", "=", "node", ".", "rsplit", "(", "\"|\"", ",", "1", ")", "[", "-", "1", "]", "# get the node name, in case we get a dagpath", "name", "=", "name", ".", "lstrip", "(", "\":\"", ")", "# strip the root namespace", "if", "\":\"", "not", "in", "name", ":", "# if there is no namespace return root", "return", "\":\"", "else", ":", "# get the top namespace", "return", "name", ".", "partition", "(", "\":\"", ")", "[", "0", "]" ]
Return the top namespace of the given node If the node has not namespace (only root), ":" is returned. Else the top namespace (after root) is returned :param node: the node to query :type node: str :returns: The top level namespace. :rtype: str :raises: None
[ "Return", "the", "top", "namespace", "of", "the", "given", "node" ]
c8d6318d53cdb5493453c4a6b65ef75bdb2d5f2c
https://github.com/JukeboxPipeline/jukeboxmaya/blob/c8d6318d53cdb5493453c4a6b65ef75bdb2d5f2c/src/jukeboxmaya/common.py#L68-L86
train
JukeboxPipeline/jukeboxmaya
src/jukeboxmaya/common.py
disconnect_node
def disconnect_node(node, src=True, dst=True): """Disconnect all connections from node :param node: the node to disconnect :type node: str :returns: None :rtype: None :raises: None """ if dst: destconns = cmds.listConnections(node, connections=True, plugs=True, source=False) or [] for i in range(0, len(destconns), 2): source, dest = destconns[i], destconns[i+1] cmds.disconnectAttr(source, dest) if src: srcconns = cmds.listConnections(node, connections=True, plugs=True, destination=False) or [] for i in range(0, len(srcconns), 2): source, dest = srcconns[i+1], srcconns[i] cmds.disconnectAttr(source, dest)
python
def disconnect_node(node, src=True, dst=True): """Disconnect all connections from node :param node: the node to disconnect :type node: str :returns: None :rtype: None :raises: None """ if dst: destconns = cmds.listConnections(node, connections=True, plugs=True, source=False) or [] for i in range(0, len(destconns), 2): source, dest = destconns[i], destconns[i+1] cmds.disconnectAttr(source, dest) if src: srcconns = cmds.listConnections(node, connections=True, plugs=True, destination=False) or [] for i in range(0, len(srcconns), 2): source, dest = srcconns[i+1], srcconns[i] cmds.disconnectAttr(source, dest)
[ "def", "disconnect_node", "(", "node", ",", "src", "=", "True", ",", "dst", "=", "True", ")", ":", "if", "dst", ":", "destconns", "=", "cmds", ".", "listConnections", "(", "node", ",", "connections", "=", "True", ",", "plugs", "=", "True", ",", "source", "=", "False", ")", "or", "[", "]", "for", "i", "in", "range", "(", "0", ",", "len", "(", "destconns", ")", ",", "2", ")", ":", "source", ",", "dest", "=", "destconns", "[", "i", "]", ",", "destconns", "[", "i", "+", "1", "]", "cmds", ".", "disconnectAttr", "(", "source", ",", "dest", ")", "if", "src", ":", "srcconns", "=", "cmds", ".", "listConnections", "(", "node", ",", "connections", "=", "True", ",", "plugs", "=", "True", ",", "destination", "=", "False", ")", "or", "[", "]", "for", "i", "in", "range", "(", "0", ",", "len", "(", "srcconns", ")", ",", "2", ")", ":", "source", ",", "dest", "=", "srcconns", "[", "i", "+", "1", "]", ",", "srcconns", "[", "i", "]", "cmds", ".", "disconnectAttr", "(", "source", ",", "dest", ")" ]
Disconnect all connections from node :param node: the node to disconnect :type node: str :returns: None :rtype: None :raises: None
[ "Disconnect", "all", "connections", "from", "node" ]
c8d6318d53cdb5493453c4a6b65ef75bdb2d5f2c
https://github.com/JukeboxPipeline/jukeboxmaya/blob/c8d6318d53cdb5493453c4a6b65ef75bdb2d5f2c/src/jukeboxmaya/common.py#L105-L123
train
TorkamaniLab/metapipe
metapipe/models/tokens.py
Input.fuzzy_match
def fuzzy_match(self, other): """ Given another token, see if either the major alias identifier matches the other alias, or if magic matches the alias. """ magic, fuzzy = False, False try: magic = self.alias == other.magic except AttributeError: pass if '.' in self.alias: major = self.alias.split('.')[0] fuzzy = major == other.alias return magic or fuzzy
python
def fuzzy_match(self, other): """ Given another token, see if either the major alias identifier matches the other alias, or if magic matches the alias. """ magic, fuzzy = False, False try: magic = self.alias == other.magic except AttributeError: pass if '.' in self.alias: major = self.alias.split('.')[0] fuzzy = major == other.alias return magic or fuzzy
[ "def", "fuzzy_match", "(", "self", ",", "other", ")", ":", "magic", ",", "fuzzy", "=", "False", ",", "False", "try", ":", "magic", "=", "self", ".", "alias", "==", "other", ".", "magic", "except", "AttributeError", ":", "pass", "if", "'.'", "in", "self", ".", "alias", ":", "major", "=", "self", ".", "alias", ".", "split", "(", "'.'", ")", "[", "0", "]", "fuzzy", "=", "major", "==", "other", ".", "alias", "return", "magic", "or", "fuzzy" ]
Given another token, see if either the major alias identifier matches the other alias, or if magic matches the alias.
[ "Given", "another", "token", "see", "if", "either", "the", "major", "alias", "identifier", "matches", "the", "other", "alias", "or", "if", "magic", "matches", "the", "alias", "." ]
15592e5b0c217afb00ac03503f8d0d7453d4baf4
https://github.com/TorkamaniLab/metapipe/blob/15592e5b0c217afb00ac03503f8d0d7453d4baf4/metapipe/models/tokens.py#L98-L111
train
TorkamaniLab/metapipe
metapipe/models/tokens.py
Input.eval
def eval(self): """ Evaluates the given input and returns a string containing the actual filenames represented. If the input token represents multiple independent files, then eval will return a list of all the input files needed, otherwise it returns the filenames in a string. """ if self.and_or == 'or': return [Input(self.alias, file, self.cwd, 'and') for file in self.files] return ' '.join(self.files)
python
def eval(self): """ Evaluates the given input and returns a string containing the actual filenames represented. If the input token represents multiple independent files, then eval will return a list of all the input files needed, otherwise it returns the filenames in a string. """ if self.and_or == 'or': return [Input(self.alias, file, self.cwd, 'and') for file in self.files] return ' '.join(self.files)
[ "def", "eval", "(", "self", ")", ":", "if", "self", ".", "and_or", "==", "'or'", ":", "return", "[", "Input", "(", "self", ".", "alias", ",", "file", ",", "self", ".", "cwd", ",", "'and'", ")", "for", "file", "in", "self", ".", "files", "]", "return", "' '", ".", "join", "(", "self", ".", "files", ")" ]
Evaluates the given input and returns a string containing the actual filenames represented. If the input token represents multiple independent files, then eval will return a list of all the input files needed, otherwise it returns the filenames in a string.
[ "Evaluates", "the", "given", "input", "and", "returns", "a", "string", "containing", "the", "actual", "filenames", "represented", ".", "If", "the", "input", "token", "represents", "multiple", "independent", "files", "then", "eval", "will", "return", "a", "list", "of", "all", "the", "input", "files", "needed", "otherwise", "it", "returns", "the", "filenames", "in", "a", "string", "." ]
15592e5b0c217afb00ac03503f8d0d7453d4baf4
https://github.com/TorkamaniLab/metapipe/blob/15592e5b0c217afb00ac03503f8d0d7453d4baf4/metapipe/models/tokens.py#L113-L122
train
TorkamaniLab/metapipe
metapipe/models/tokens.py
Input.files
def files(self): """ Returns a list of all the files that match the given input token. """ res = None if not res: res = glob.glob(self.path) if not res and self.is_glob: res = glob.glob(self.magic_path) if not res: res = glob.glob(self.alias) if not res: raise ValueError('No files match. %s' % self) return res
python
def files(self): """ Returns a list of all the files that match the given input token. """ res = None if not res: res = glob.glob(self.path) if not res and self.is_glob: res = glob.glob(self.magic_path) if not res: res = glob.glob(self.alias) if not res: raise ValueError('No files match. %s' % self) return res
[ "def", "files", "(", "self", ")", ":", "res", "=", "None", "if", "not", "res", ":", "res", "=", "glob", ".", "glob", "(", "self", ".", "path", ")", "if", "not", "res", "and", "self", ".", "is_glob", ":", "res", "=", "glob", ".", "glob", "(", "self", ".", "magic_path", ")", "if", "not", "res", ":", "res", "=", "glob", ".", "glob", "(", "self", ".", "alias", ")", "if", "not", "res", ":", "raise", "ValueError", "(", "'No files match. %s'", "%", "self", ")", "return", "res" ]
Returns a list of all the files that match the given input token.
[ "Returns", "a", "list", "of", "all", "the", "files", "that", "match", "the", "given", "input", "token", "." ]
15592e5b0c217afb00ac03503f8d0d7453d4baf4
https://github.com/TorkamaniLab/metapipe/blob/15592e5b0c217afb00ac03503f8d0d7453d4baf4/metapipe/models/tokens.py#L152-L165
train
TorkamaniLab/metapipe
metapipe/models/tokens.py
Input.from_string
def from_string(string, _or=''): """ Parse a given string and turn it into an input token. """ if _or: and_or = 'or' else: and_or = '' return Input(string, and_or=and_or)
python
def from_string(string, _or=''): """ Parse a given string and turn it into an input token. """ if _or: and_or = 'or' else: and_or = '' return Input(string, and_or=and_or)
[ "def", "from_string", "(", "string", ",", "_or", "=", "''", ")", ":", "if", "_or", ":", "and_or", "=", "'or'", "else", ":", "and_or", "=", "''", "return", "Input", "(", "string", ",", "and_or", "=", "and_or", ")" ]
Parse a given string and turn it into an input token.
[ "Parse", "a", "given", "string", "and", "turn", "it", "into", "an", "input", "token", "." ]
15592e5b0c217afb00ac03503f8d0d7453d4baf4
https://github.com/TorkamaniLab/metapipe/blob/15592e5b0c217afb00ac03503f8d0d7453d4baf4/metapipe/models/tokens.py#L168-L174
train
TorkamaniLab/metapipe
metapipe/models/tokens.py
Output.eval
def eval(self): """ Returns a filename to be used for script output. """ if self.magic: return self.magic if not self.filename: return file_pattern.format(self.alias, self.ext) return self.path
python
def eval(self): """ Returns a filename to be used for script output. """ if self.magic: return self.magic if not self.filename: return file_pattern.format(self.alias, self.ext) return self.path
[ "def", "eval", "(", "self", ")", ":", "if", "self", ".", "magic", ":", "return", "self", ".", "magic", "if", "not", "self", ".", "filename", ":", "return", "file_pattern", ".", "format", "(", "self", ".", "alias", ",", "self", ".", "ext", ")", "return", "self", ".", "path" ]
Returns a filename to be used for script output.
[ "Returns", "a", "filename", "to", "be", "used", "for", "script", "output", "." ]
15592e5b0c217afb00ac03503f8d0d7453d4baf4
https://github.com/TorkamaniLab/metapipe/blob/15592e5b0c217afb00ac03503f8d0d7453d4baf4/metapipe/models/tokens.py#L202-L208
train
TorkamaniLab/metapipe
metapipe/models/tokens.py
Output._clean
def _clean(self, magic): """ Given a magic string, remove the output tag designator. """ if magic.lower() == 'o': self.magic = '' elif magic[:2].lower() == 'o:': self.magic = magic[2:] elif magic[:2].lower() == 'o.': self.ext = magic[1:]
python
def _clean(self, magic): """ Given a magic string, remove the output tag designator. """ if magic.lower() == 'o': self.magic = '' elif magic[:2].lower() == 'o:': self.magic = magic[2:] elif magic[:2].lower() == 'o.': self.ext = magic[1:]
[ "def", "_clean", "(", "self", ",", "magic", ")", ":", "if", "magic", ".", "lower", "(", ")", "==", "'o'", ":", "self", ".", "magic", "=", "''", "elif", "magic", "[", ":", "2", "]", ".", "lower", "(", ")", "==", "'o:'", ":", "self", ".", "magic", "=", "magic", "[", "2", ":", "]", "elif", "magic", "[", ":", "2", "]", ".", "lower", "(", ")", "==", "'o.'", ":", "self", ".", "ext", "=", "magic", "[", "1", ":", "]" ]
Given a magic string, remove the output tag designator.
[ "Given", "a", "magic", "string", "remove", "the", "output", "tag", "designator", "." ]
15592e5b0c217afb00ac03503f8d0d7453d4baf4
https://github.com/TorkamaniLab/metapipe/blob/15592e5b0c217afb00ac03503f8d0d7453d4baf4/metapipe/models/tokens.py#L214-L221
train
The-Politico/politico-civic-election
election/models/candidate.py
Candidate.get_candidate_election
def get_candidate_election(self, election): """Get a CandidateElection.""" return CandidateElection.objects.get(candidate=self, election=election)
python
def get_candidate_election(self, election): """Get a CandidateElection.""" return CandidateElection.objects.get(candidate=self, election=election)
[ "def", "get_candidate_election", "(", "self", ",", "election", ")", ":", "return", "CandidateElection", ".", "objects", ".", "get", "(", "candidate", "=", "self", ",", "election", "=", "election", ")" ]
Get a CandidateElection.
[ "Get", "a", "CandidateElection", "." ]
44c6872c419909df616e997e1990c4d295b25eda
https://github.com/The-Politico/politico-civic-election/blob/44c6872c419909df616e997e1990c4d295b25eda/election/models/candidate.py#L53-L55
train
The-Politico/politico-civic-election
election/models/candidate.py
Candidate.get_election_votes
def get_election_votes(self, election): """Get all votes for this candidate in an election.""" candidate_election = CandidateElection.objects.get( candidate=self, election=election ) return candidate_election.votes.all()
python
def get_election_votes(self, election): """Get all votes for this candidate in an election.""" candidate_election = CandidateElection.objects.get( candidate=self, election=election ) return candidate_election.votes.all()
[ "def", "get_election_votes", "(", "self", ",", "election", ")", ":", "candidate_election", "=", "CandidateElection", ".", "objects", ".", "get", "(", "candidate", "=", "self", ",", "election", "=", "election", ")", "return", "candidate_election", ".", "votes", ".", "all", "(", ")" ]
Get all votes for this candidate in an election.
[ "Get", "all", "votes", "for", "this", "candidate", "in", "an", "election", "." ]
44c6872c419909df616e997e1990c4d295b25eda
https://github.com/The-Politico/politico-civic-election/blob/44c6872c419909df616e997e1990c4d295b25eda/election/models/candidate.py#L63-L69
train
The-Politico/politico-civic-election
election/models/candidate.py
Candidate.get_election_electoral_votes
def get_election_electoral_votes(self, election): """Get all electoral votes for this candidate in an election.""" candidate_election = CandidateElection.objects.get( candidate=self, election=election ) return candidate_election.electoral_votes.all()
python
def get_election_electoral_votes(self, election): """Get all electoral votes for this candidate in an election.""" candidate_election = CandidateElection.objects.get( candidate=self, election=election ) return candidate_election.electoral_votes.all()
[ "def", "get_election_electoral_votes", "(", "self", ",", "election", ")", ":", "candidate_election", "=", "CandidateElection", ".", "objects", ".", "get", "(", "candidate", "=", "self", ",", "election", "=", "election", ")", "return", "candidate_election", ".", "electoral_votes", ".", "all", "(", ")" ]
Get all electoral votes for this candidate in an election.
[ "Get", "all", "electoral", "votes", "for", "this", "candidate", "in", "an", "election", "." ]
44c6872c419909df616e997e1990c4d295b25eda
https://github.com/The-Politico/politico-civic-election/blob/44c6872c419909df616e997e1990c4d295b25eda/election/models/candidate.py#L71-L77
train
The-Politico/politico-civic-election
election/models/candidate.py
Candidate.get_election_delegates
def get_election_delegates(self, election): """Get all pledged delegates for this candidate in an election.""" candidate_election = CandidateElection.objects.get( candidate=self, election=election ) return candidate_election.delegates.all()
python
def get_election_delegates(self, election): """Get all pledged delegates for this candidate in an election.""" candidate_election = CandidateElection.objects.get( candidate=self, election=election ) return candidate_election.delegates.all()
[ "def", "get_election_delegates", "(", "self", ",", "election", ")", ":", "candidate_election", "=", "CandidateElection", ".", "objects", ".", "get", "(", "candidate", "=", "self", ",", "election", "=", "election", ")", "return", "candidate_election", ".", "delegates", ".", "all", "(", ")" ]
Get all pledged delegates for this candidate in an election.
[ "Get", "all", "pledged", "delegates", "for", "this", "candidate", "in", "an", "election", "." ]
44c6872c419909df616e997e1990c4d295b25eda
https://github.com/The-Politico/politico-civic-election/blob/44c6872c419909df616e997e1990c4d295b25eda/election/models/candidate.py#L79-L85
train
Frzk/Ellis
ellis/ellis.py
Ellis.load_config
def load_config(self, config_file=None): """ If `config_file` is not None, tries to load Ellis configuration from the given location. If, for some reason, the file can't be read, Ellis will not start. If no configuration file is given (`config_file` is None), tries to load Ellis configuration from these potential locations, in this specific order: 1. `/etc/ellis.conf` 2. `/etc/ellis/ellis.conf` 3. `./ellis.conf` If more than one of these files exist, the configuration is merged which can lead to one or more section(s) being overriden. The last file (`./ellis.conf`) takes precedence over the second one, which takes precedence over the first one. """ if config_file is None: config_file = [ '/etc/ellis.conf', '/etc/ellis/ellis.conf', os.path.join(os.path.dirname(__file__), 'ellis.conf'), ] self.config.read(config_file, encoding='utf-8') return self
python
def load_config(self, config_file=None): """ If `config_file` is not None, tries to load Ellis configuration from the given location. If, for some reason, the file can't be read, Ellis will not start. If no configuration file is given (`config_file` is None), tries to load Ellis configuration from these potential locations, in this specific order: 1. `/etc/ellis.conf` 2. `/etc/ellis/ellis.conf` 3. `./ellis.conf` If more than one of these files exist, the configuration is merged which can lead to one or more section(s) being overriden. The last file (`./ellis.conf`) takes precedence over the second one, which takes precedence over the first one. """ if config_file is None: config_file = [ '/etc/ellis.conf', '/etc/ellis/ellis.conf', os.path.join(os.path.dirname(__file__), 'ellis.conf'), ] self.config.read(config_file, encoding='utf-8') return self
[ "def", "load_config", "(", "self", ",", "config_file", "=", "None", ")", ":", "if", "config_file", "is", "None", ":", "config_file", "=", "[", "'/etc/ellis.conf'", ",", "'/etc/ellis/ellis.conf'", ",", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ",", "'ellis.conf'", ")", ",", "]", "self", ".", "config", ".", "read", "(", "config_file", ",", "encoding", "=", "'utf-8'", ")", "return", "self" ]
If `config_file` is not None, tries to load Ellis configuration from the given location. If, for some reason, the file can't be read, Ellis will not start. If no configuration file is given (`config_file` is None), tries to load Ellis configuration from these potential locations, in this specific order: 1. `/etc/ellis.conf` 2. `/etc/ellis/ellis.conf` 3. `./ellis.conf` If more than one of these files exist, the configuration is merged which can lead to one or more section(s) being overriden. The last file (`./ellis.conf`) takes precedence over the second one, which takes precedence over the first one.
[ "If", "config_file", "is", "not", "None", "tries", "to", "load", "Ellis", "configuration", "from", "the", "given", "location", ".", "If", "for", "some", "reason", "the", "file", "can", "t", "be", "read", "Ellis", "will", "not", "start", "." ]
39ce8987cbc503354cf1f45927344186a8b18363
https://github.com/Frzk/Ellis/blob/39ce8987cbc503354cf1f45927344186a8b18363/ellis/ellis.py#L45-L74
train
Frzk/Ellis
ellis/ellis.py
Ellis.load_rules
def load_rules(self): """ Loads the Rules from the config file. An invalid Rule (no Filter or no Action) will trigger a warning message and will be ignored. """ for rule_name in self.config.sections(): limit = 1 try: limit = self.config.getint(rule_name, 'limit') except ValueError: warnings.warn("Rule '{0}': invalid value for 'limit' option. " "Limit must be an integer > 0. " "Going on with the default value of 1." .format(rule_name)) except configparser.NoOptionError: warnings.warn("Rule '{0}': no value specified for 'limit' " "option. Going on with the default value of 1." .format(rule_name)) try: filter_str = self.config.get(rule_name, 'filter') action_str = self.config.get(rule_name, 'action') except configparser.NoOptionError as e: warnings.warn("Ignoring '{0}' rule: {1}." .format(rule_name, e)) else: try: rule = Rule(rule_name, filter_str, limit, action_str) except ValueError as e: warnings.warn("Ignoring '{0}' rule: {1}." .format(rule_name, e)) else: self.rules.append(rule) if not self.rules: raise NoRuleError() return self
python
def load_rules(self): """ Loads the Rules from the config file. An invalid Rule (no Filter or no Action) will trigger a warning message and will be ignored. """ for rule_name in self.config.sections(): limit = 1 try: limit = self.config.getint(rule_name, 'limit') except ValueError: warnings.warn("Rule '{0}': invalid value for 'limit' option. " "Limit must be an integer > 0. " "Going on with the default value of 1." .format(rule_name)) except configparser.NoOptionError: warnings.warn("Rule '{0}': no value specified for 'limit' " "option. Going on with the default value of 1." .format(rule_name)) try: filter_str = self.config.get(rule_name, 'filter') action_str = self.config.get(rule_name, 'action') except configparser.NoOptionError as e: warnings.warn("Ignoring '{0}' rule: {1}." .format(rule_name, e)) else: try: rule = Rule(rule_name, filter_str, limit, action_str) except ValueError as e: warnings.warn("Ignoring '{0}' rule: {1}." .format(rule_name, e)) else: self.rules.append(rule) if not self.rules: raise NoRuleError() return self
[ "def", "load_rules", "(", "self", ")", ":", "for", "rule_name", "in", "self", ".", "config", ".", "sections", "(", ")", ":", "limit", "=", "1", "try", ":", "limit", "=", "self", ".", "config", ".", "getint", "(", "rule_name", ",", "'limit'", ")", "except", "ValueError", ":", "warnings", ".", "warn", "(", "\"Rule '{0}': invalid value for 'limit' option. \"", "\"Limit must be an integer > 0. \"", "\"Going on with the default value of 1.\"", ".", "format", "(", "rule_name", ")", ")", "except", "configparser", ".", "NoOptionError", ":", "warnings", ".", "warn", "(", "\"Rule '{0}': no value specified for 'limit' \"", "\"option. Going on with the default value of 1.\"", ".", "format", "(", "rule_name", ")", ")", "try", ":", "filter_str", "=", "self", ".", "config", ".", "get", "(", "rule_name", ",", "'filter'", ")", "action_str", "=", "self", ".", "config", ".", "get", "(", "rule_name", ",", "'action'", ")", "except", "configparser", ".", "NoOptionError", "as", "e", ":", "warnings", ".", "warn", "(", "\"Ignoring '{0}' rule: {1}.\"", ".", "format", "(", "rule_name", ",", "e", ")", ")", "else", ":", "try", ":", "rule", "=", "Rule", "(", "rule_name", ",", "filter_str", ",", "limit", ",", "action_str", ")", "except", "ValueError", "as", "e", ":", "warnings", ".", "warn", "(", "\"Ignoring '{0}' rule: {1}.\"", ".", "format", "(", "rule_name", ",", "e", ")", ")", "else", ":", "self", ".", "rules", ".", "append", "(", "rule", ")", "if", "not", "self", ".", "rules", ":", "raise", "NoRuleError", "(", ")", "return", "self" ]
Loads the Rules from the config file. An invalid Rule (no Filter or no Action) will trigger a warning message and will be ignored.
[ "Loads", "the", "Rules", "from", "the", "config", "file", "." ]
39ce8987cbc503354cf1f45927344186a8b18363
https://github.com/Frzk/Ellis/blob/39ce8987cbc503354cf1f45927344186a8b18363/ellis/ellis.py#L76-L117
train
Frzk/Ellis
ellis/ellis.py
Ellis.load_units
def load_units(self): """ Build a set of systemd units that Ellis will watch. This set will be used to filter journald entries so that we only process entries that were produced by these units. This should result in better performance. """ # Of course, we only consider valid Rules. for rule in self.rules: try: systemd_unit = self.config.get(rule.name, 'systemd_unit') except configparser.NoOptionError: warnings.warn("Rule '{0}' doesn't have a `systemd_unit` " "option set.\nThe filters will be checked " "against all journald entries, which will " "probably result in poor performance." .format(rule.name)) # At this point, we can clear `self.units` because in any # case, we will need to process every journald entries # for THIS Rule. self.units.clear() # And we can also stop looping through rules. break else: # Append ".service" if not present. # Note that we don't check if the service actually exists. # FIXME ? if not systemd_unit.endswith(".service"): systemd_unit += ".service" self.units.add(systemd_unit) return self
python
def load_units(self): """ Build a set of systemd units that Ellis will watch. This set will be used to filter journald entries so that we only process entries that were produced by these units. This should result in better performance. """ # Of course, we only consider valid Rules. for rule in self.rules: try: systemd_unit = self.config.get(rule.name, 'systemd_unit') except configparser.NoOptionError: warnings.warn("Rule '{0}' doesn't have a `systemd_unit` " "option set.\nThe filters will be checked " "against all journald entries, which will " "probably result in poor performance." .format(rule.name)) # At this point, we can clear `self.units` because in any # case, we will need to process every journald entries # for THIS Rule. self.units.clear() # And we can also stop looping through rules. break else: # Append ".service" if not present. # Note that we don't check if the service actually exists. # FIXME ? if not systemd_unit.endswith(".service"): systemd_unit += ".service" self.units.add(systemd_unit) return self
[ "def", "load_units", "(", "self", ")", ":", "# Of course, we only consider valid Rules.", "for", "rule", "in", "self", ".", "rules", ":", "try", ":", "systemd_unit", "=", "self", ".", "config", ".", "get", "(", "rule", ".", "name", ",", "'systemd_unit'", ")", "except", "configparser", ".", "NoOptionError", ":", "warnings", ".", "warn", "(", "\"Rule '{0}' doesn't have a `systemd_unit` \"", "\"option set.\\nThe filters will be checked \"", "\"against all journald entries, which will \"", "\"probably result in poor performance.\"", ".", "format", "(", "rule", ".", "name", ")", ")", "# At this point, we can clear `self.units` because in any", "# case, we will need to process every journald entries", "# for THIS Rule.", "self", ".", "units", ".", "clear", "(", ")", "# And we can also stop looping through rules.", "break", "else", ":", "# Append \".service\" if not present.", "# Note that we don't check if the service actually exists.", "# FIXME ?", "if", "not", "systemd_unit", ".", "endswith", "(", "\".service\"", ")", ":", "systemd_unit", "+=", "\".service\"", "self", ".", "units", ".", "add", "(", "systemd_unit", ")", "return", "self" ]
Build a set of systemd units that Ellis will watch. This set will be used to filter journald entries so that we only process entries that were produced by these units. This should result in better performance.
[ "Build", "a", "set", "of", "systemd", "units", "that", "Ellis", "will", "watch", "." ]
39ce8987cbc503354cf1f45927344186a8b18363
https://github.com/Frzk/Ellis/blob/39ce8987cbc503354cf1f45927344186a8b18363/ellis/ellis.py#L119-L156
train
sirfoga/pyhal
hal/data/lists.py
find_commons
def find_commons(lists): """Finds common values :param lists: List of lists :return: List of values that are in common between inner lists """ others = lists[1:] return [ val for val in lists[0] if is_in_all(val, others) ]
python
def find_commons(lists): """Finds common values :param lists: List of lists :return: List of values that are in common between inner lists """ others = lists[1:] return [ val for val in lists[0] if is_in_all(val, others) ]
[ "def", "find_commons", "(", "lists", ")", ":", "others", "=", "lists", "[", "1", ":", "]", "return", "[", "val", "for", "val", "in", "lists", "[", "0", "]", "if", "is_in_all", "(", "val", ",", "others", ")", "]" ]
Finds common values :param lists: List of lists :return: List of values that are in common between inner lists
[ "Finds", "common", "values" ]
4394d8a1f7e45bea28a255ec390f4962ee64d33a
https://github.com/sirfoga/pyhal/blob/4394d8a1f7e45bea28a255ec390f4962ee64d33a/hal/data/lists.py#L44-L55
train
IS-ENES-Data/esgf-pid
esgfpid/solr/solr.py
SolrInteractor.send_query
def send_query(self, query): ''' This method is called by the tasks. It is redirected to the submodule.''' if self.__switched_on: return self.__solr_server_connector.send_query(query) else: msg = 'Not sending query' LOGGER.debug(msg) raise esgfpid.exceptions.SolrSwitchedOff(msg)
python
def send_query(self, query): ''' This method is called by the tasks. It is redirected to the submodule.''' if self.__switched_on: return self.__solr_server_connector.send_query(query) else: msg = 'Not sending query' LOGGER.debug(msg) raise esgfpid.exceptions.SolrSwitchedOff(msg)
[ "def", "send_query", "(", "self", ",", "query", ")", ":", "if", "self", ".", "__switched_on", ":", "return", "self", ".", "__solr_server_connector", ".", "send_query", "(", "query", ")", "else", ":", "msg", "=", "'Not sending query'", "LOGGER", ".", "debug", "(", "msg", ")", "raise", "esgfpid", ".", "exceptions", ".", "SolrSwitchedOff", "(", "msg", ")" ]
This method is called by the tasks. It is redirected to the submodule.
[ "This", "method", "is", "called", "by", "the", "tasks", ".", "It", "is", "redirected", "to", "the", "submodule", "." ]
2f4909bb3ff79c0b6ed2932e0dd8b3bb6aec5e41
https://github.com/IS-ENES-Data/esgf-pid/blob/2f4909bb3ff79c0b6ed2932e0dd8b3bb6aec5e41/esgfpid/solr/solr.py#L104-L111
train
lowandrew/OLCTools
accessoryFunctions/accessoryFunctions.py
strainer
def strainer(sequencepath): """ Locate all the FASTA files in the supplied sequence path. Create basic metadata objects for each sample """ metadata_list = list() assert os.path.isdir(sequencepath), 'Cannot locate sequence path as specified: {}' \ .format(sequencepath) # Get the sequences in the sequences folder into a list. Note that they must have a file extension that # begins with .fa strains = sorted(glob.glob(os.path.join(sequencepath, '*.fa*'))) # Populate the metadata object. This object will be populated to mirror the objects created in the # genome assembly pipeline. This way this script will be able to be used as a stand-alone, or as part # of a pipeline assert strains, 'Could not find any files with an extension starting with "fa" in {}. Please check ' \ 'to ensure that your sequence path is correct'.format(sequencepath) for sample in strains: # Create the object metadata = MetadataObject() # Set the base file name of the sequence. Just remove the file extension filename = os.path.splitext(os.path.split(sample)[1])[0] # Set the .name attribute to be the file name metadata.name = filename # Create the .general attribute metadata.general = GenObject() metadata.commands = GenObject() metadata.general.outputdirectory = os.path.join(sequencepath, filename) # Set the .general.bestassembly file to be the name and path of the sequence file metadata.general.bestassemblyfile = os.path.join(metadata.general.outputdirectory, '{sn}.fasta' .format(sn=filename)) make_path(metadata.general.outputdirectory) # Create a symlink to the directory relative_symlink(sample, metadata.general.outputdirectory) metadata.general.logout = os.path.join(metadata.general.outputdirectory, 'out') metadata.general.logerr = os.path.join(metadata.general.outputdirectory, 'err') # Append the metadata for each sample to the list of samples metadata_list.append(metadata) return strains, metadata_list
python
def strainer(sequencepath): """ Locate all the FASTA files in the supplied sequence path. Create basic metadata objects for each sample """ metadata_list = list() assert os.path.isdir(sequencepath), 'Cannot locate sequence path as specified: {}' \ .format(sequencepath) # Get the sequences in the sequences folder into a list. Note that they must have a file extension that # begins with .fa strains = sorted(glob.glob(os.path.join(sequencepath, '*.fa*'))) # Populate the metadata object. This object will be populated to mirror the objects created in the # genome assembly pipeline. This way this script will be able to be used as a stand-alone, or as part # of a pipeline assert strains, 'Could not find any files with an extension starting with "fa" in {}. Please check ' \ 'to ensure that your sequence path is correct'.format(sequencepath) for sample in strains: # Create the object metadata = MetadataObject() # Set the base file name of the sequence. Just remove the file extension filename = os.path.splitext(os.path.split(sample)[1])[0] # Set the .name attribute to be the file name metadata.name = filename # Create the .general attribute metadata.general = GenObject() metadata.commands = GenObject() metadata.general.outputdirectory = os.path.join(sequencepath, filename) # Set the .general.bestassembly file to be the name and path of the sequence file metadata.general.bestassemblyfile = os.path.join(metadata.general.outputdirectory, '{sn}.fasta' .format(sn=filename)) make_path(metadata.general.outputdirectory) # Create a symlink to the directory relative_symlink(sample, metadata.general.outputdirectory) metadata.general.logout = os.path.join(metadata.general.outputdirectory, 'out') metadata.general.logerr = os.path.join(metadata.general.outputdirectory, 'err') # Append the metadata for each sample to the list of samples metadata_list.append(metadata) return strains, metadata_list
[ "def", "strainer", "(", "sequencepath", ")", ":", "metadata_list", "=", "list", "(", ")", "assert", "os", ".", "path", ".", "isdir", "(", "sequencepath", ")", ",", "'Cannot locate sequence path as specified: {}'", ".", "format", "(", "sequencepath", ")", "# Get the sequences in the sequences folder into a list. Note that they must have a file extension that", "# begins with .fa", "strains", "=", "sorted", "(", "glob", ".", "glob", "(", "os", ".", "path", ".", "join", "(", "sequencepath", ",", "'*.fa*'", ")", ")", ")", "# Populate the metadata object. This object will be populated to mirror the objects created in the", "# genome assembly pipeline. This way this script will be able to be used as a stand-alone, or as part", "# of a pipeline", "assert", "strains", ",", "'Could not find any files with an extension starting with \"fa\" in {}. Please check '", "'to ensure that your sequence path is correct'", ".", "format", "(", "sequencepath", ")", "for", "sample", "in", "strains", ":", "# Create the object", "metadata", "=", "MetadataObject", "(", ")", "# Set the base file name of the sequence. Just remove the file extension", "filename", "=", "os", ".", "path", ".", "splitext", "(", "os", ".", "path", ".", "split", "(", "sample", ")", "[", "1", "]", ")", "[", "0", "]", "# Set the .name attribute to be the file name", "metadata", ".", "name", "=", "filename", "# Create the .general attribute", "metadata", ".", "general", "=", "GenObject", "(", ")", "metadata", ".", "commands", "=", "GenObject", "(", ")", "metadata", ".", "general", ".", "outputdirectory", "=", "os", ".", "path", ".", "join", "(", "sequencepath", ",", "filename", ")", "# Set the .general.bestassembly file to be the name and path of the sequence file", "metadata", ".", "general", ".", "bestassemblyfile", "=", "os", ".", "path", ".", "join", "(", "metadata", ".", "general", ".", "outputdirectory", ",", "'{sn}.fasta'", ".", "format", "(", "sn", "=", "filename", ")", ")", "make_path", "(", "metadata", ".", "general", ".", "outputdirectory", ")", "# Create a symlink to the directory", "relative_symlink", "(", "sample", ",", "metadata", ".", "general", ".", "outputdirectory", ")", "metadata", ".", "general", ".", "logout", "=", "os", ".", "path", ".", "join", "(", "metadata", ".", "general", ".", "outputdirectory", ",", "'out'", ")", "metadata", ".", "general", ".", "logerr", "=", "os", ".", "path", ".", "join", "(", "metadata", ".", "general", ".", "outputdirectory", ",", "'err'", ")", "# Append the metadata for each sample to the list of samples", "metadata_list", ".", "append", "(", "metadata", ")", "return", "strains", ",", "metadata_list" ]
Locate all the FASTA files in the supplied sequence path. Create basic metadata objects for each sample
[ "Locate", "all", "the", "FASTA", "files", "in", "the", "supplied", "sequence", "path", ".", "Create", "basic", "metadata", "objects", "for", "each", "sample" ]
88aa90ac85f84d0bbeb03e43c29b0a9d36e4ce2a
https://github.com/lowandrew/OLCTools/blob/88aa90ac85f84d0bbeb03e43c29b0a9d36e4ce2a/accessoryFunctions/accessoryFunctions.py#L894-L932
train
AllTheWayDown/turgles
turgles/render/turtles.py
TurtleShapeVAO.render
def render(self, model, color, num_turtles): """Renders all turtles of a given shape""" self.program.bind() glBindVertexArray(self.vao) self.model_buffer.load(model.data, model.byte_size) self.color_buffer.load(color.data, color.byte_size) glDrawArraysInstanced( GL_TRIANGLES, 0, len(self.geometry.edges) // 7, # 7 = 4 for vertex, 3 for edge num_turtles ) glBindVertexArray(0) self.program.unbind()
python
def render(self, model, color, num_turtles): """Renders all turtles of a given shape""" self.program.bind() glBindVertexArray(self.vao) self.model_buffer.load(model.data, model.byte_size) self.color_buffer.load(color.data, color.byte_size) glDrawArraysInstanced( GL_TRIANGLES, 0, len(self.geometry.edges) // 7, # 7 = 4 for vertex, 3 for edge num_turtles ) glBindVertexArray(0) self.program.unbind()
[ "def", "render", "(", "self", ",", "model", ",", "color", ",", "num_turtles", ")", ":", "self", ".", "program", ".", "bind", "(", ")", "glBindVertexArray", "(", "self", ".", "vao", ")", "self", ".", "model_buffer", ".", "load", "(", "model", ".", "data", ",", "model", ".", "byte_size", ")", "self", ".", "color_buffer", ".", "load", "(", "color", ".", "data", ",", "color", ".", "byte_size", ")", "glDrawArraysInstanced", "(", "GL_TRIANGLES", ",", "0", ",", "len", "(", "self", ".", "geometry", ".", "edges", ")", "//", "7", ",", "# 7 = 4 for vertex, 3 for edge", "num_turtles", ")", "glBindVertexArray", "(", "0", ")", "self", ".", "program", ".", "unbind", "(", ")" ]
Renders all turtles of a given shape
[ "Renders", "all", "turtles", "of", "a", "given", "shape" ]
1bb17abe9b3aa0953d9a8e9b05a23369c5bf8852
https://github.com/AllTheWayDown/turgles/blob/1bb17abe9b3aa0953d9a8e9b05a23369c5bf8852/turgles/render/turtles.py#L74-L90
train
sirfoga/pyhal
hal/internet/web.py
renew_connection
def renew_connection(password): """Renews TOR session :param password: new password """ with Controller.from_port(port=9051) as controller: controller.authenticate(password=password) controller.signal(Signal.NEWNYM)
python
def renew_connection(password): """Renews TOR session :param password: new password """ with Controller.from_port(port=9051) as controller: controller.authenticate(password=password) controller.signal(Signal.NEWNYM)
[ "def", "renew_connection", "(", "password", ")", ":", "with", "Controller", ".", "from_port", "(", "port", "=", "9051", ")", "as", "controller", ":", "controller", ".", "authenticate", "(", "password", "=", "password", ")", "controller", ".", "signal", "(", "Signal", ".", "NEWNYM", ")" ]
Renews TOR session :param password: new password
[ "Renews", "TOR", "session" ]
4394d8a1f7e45bea28a255ec390f4962ee64d33a
https://github.com/sirfoga/pyhal/blob/4394d8a1f7e45bea28a255ec390f4962ee64d33a/hal/internet/web.py#L258-L265
train
sirfoga/pyhal
hal/internet/web.py
Webpage.parse_url
def parse_url(url): """Parses correctly url :param url: url to parse """ parsed = url if not url.startswith("http://") and not url.startswith( "https://"): # if url is like www.yahoo.com parsed = "http://" + parsed elif url.startswith("https://"): parsed = parsed[8:] parsed = "http://" + parsed index_hash = parsed.rfind("#") # remove trailing # index_slash = parsed.rfind("/") if index_hash > index_slash: parsed = parsed[0: index_hash] return parsed
python
def parse_url(url): """Parses correctly url :param url: url to parse """ parsed = url if not url.startswith("http://") and not url.startswith( "https://"): # if url is like www.yahoo.com parsed = "http://" + parsed elif url.startswith("https://"): parsed = parsed[8:] parsed = "http://" + parsed index_hash = parsed.rfind("#") # remove trailing # index_slash = parsed.rfind("/") if index_hash > index_slash: parsed = parsed[0: index_hash] return parsed
[ "def", "parse_url", "(", "url", ")", ":", "parsed", "=", "url", "if", "not", "url", ".", "startswith", "(", "\"http://\"", ")", "and", "not", "url", ".", "startswith", "(", "\"https://\"", ")", ":", "# if url is like www.yahoo.com", "parsed", "=", "\"http://\"", "+", "parsed", "elif", "url", ".", "startswith", "(", "\"https://\"", ")", ":", "parsed", "=", "parsed", "[", "8", ":", "]", "parsed", "=", "\"http://\"", "+", "parsed", "index_hash", "=", "parsed", ".", "rfind", "(", "\"#\"", ")", "# remove trailing #", "index_slash", "=", "parsed", ".", "rfind", "(", "\"/\"", ")", "if", "index_hash", ">", "index_slash", ":", "parsed", "=", "parsed", "[", "0", ":", "index_hash", "]", "return", "parsed" ]
Parses correctly url :param url: url to parse
[ "Parses", "correctly", "url" ]
4394d8a1f7e45bea28a255ec390f4962ee64d33a
https://github.com/sirfoga/pyhal/blob/4394d8a1f7e45bea28a255ec390f4962ee64d33a/hal/internet/web.py#L128-L147
train
sirfoga/pyhal
hal/internet/web.py
Webpage.get_links
def get_links(self, recall, timeout): """Gets links in page :param recall: max times to attempt to fetch url :param timeout: max times :return: array of out_links """ for _ in range(recall): try: # setting timeout soup = BeautifulSoup(self.source) # parse source out_links = [] for tag in soup.findAll(["a", "link"], href=True): tag["href"] = urljoin(self.url, tag["href"]) out_links.append(tag["href"]) return sorted(out_links) # sort array except: time.sleep(timeout)
python
def get_links(self, recall, timeout): """Gets links in page :param recall: max times to attempt to fetch url :param timeout: max times :return: array of out_links """ for _ in range(recall): try: # setting timeout soup = BeautifulSoup(self.source) # parse source out_links = [] for tag in soup.findAll(["a", "link"], href=True): tag["href"] = urljoin(self.url, tag["href"]) out_links.append(tag["href"]) return sorted(out_links) # sort array except: time.sleep(timeout)
[ "def", "get_links", "(", "self", ",", "recall", ",", "timeout", ")", ":", "for", "_", "in", "range", "(", "recall", ")", ":", "try", ":", "# setting timeout", "soup", "=", "BeautifulSoup", "(", "self", ".", "source", ")", "# parse source", "out_links", "=", "[", "]", "for", "tag", "in", "soup", ".", "findAll", "(", "[", "\"a\"", ",", "\"link\"", "]", ",", "href", "=", "True", ")", ":", "tag", "[", "\"href\"", "]", "=", "urljoin", "(", "self", ".", "url", ",", "tag", "[", "\"href\"", "]", ")", "out_links", ".", "append", "(", "tag", "[", "\"href\"", "]", ")", "return", "sorted", "(", "out_links", ")", "# sort array", "except", ":", "time", ".", "sleep", "(", "timeout", ")" ]
Gets links in page :param recall: max times to attempt to fetch url :param timeout: max times :return: array of out_links
[ "Gets", "links", "in", "page" ]
4394d8a1f7e45bea28a255ec390f4962ee64d33a
https://github.com/sirfoga/pyhal/blob/4394d8a1f7e45bea28a255ec390f4962ee64d33a/hal/internet/web.py#L182-L200
train
sirfoga/pyhal
hal/internet/web.py
Webpage.open_in_browser
def open_in_browser(self, n_times): """Opens page in browser :param n_times: Times to open page in browser """ for _ in range(n_times): webbrowser.open(self.url)
python
def open_in_browser(self, n_times): """Opens page in browser :param n_times: Times to open page in browser """ for _ in range(n_times): webbrowser.open(self.url)
[ "def", "open_in_browser", "(", "self", ",", "n_times", ")", ":", "for", "_", "in", "range", "(", "n_times", ")", ":", "webbrowser", ".", "open", "(", "self", ".", "url", ")" ]
Opens page in browser :param n_times: Times to open page in browser
[ "Opens", "page", "in", "browser" ]
4394d8a1f7e45bea28a255ec390f4962ee64d33a
https://github.com/sirfoga/pyhal/blob/4394d8a1f7e45bea28a255ec390f4962ee64d33a/hal/internet/web.py#L202-L209
train
sirfoga/pyhal
hal/internet/web.py
Webpage.download_url
def download_url(self, local_file): """Downloads url to local file :param local_file: Save url as this path """ downloader = urllib.request.URLopener() downloader.retrieve(self.url, local_file)
python
def download_url(self, local_file): """Downloads url to local file :param local_file: Save url as this path """ downloader = urllib.request.URLopener() downloader.retrieve(self.url, local_file)
[ "def", "download_url", "(", "self", ",", "local_file", ")", ":", "downloader", "=", "urllib", ".", "request", ".", "URLopener", "(", ")", "downloader", ".", "retrieve", "(", "self", ".", "url", ",", "local_file", ")" ]
Downloads url to local file :param local_file: Save url as this path
[ "Downloads", "url", "to", "local", "file" ]
4394d8a1f7e45bea28a255ec390f4962ee64d33a
https://github.com/sirfoga/pyhal/blob/4394d8a1f7e45bea28a255ec390f4962ee64d33a/hal/internet/web.py#L211-L218
train
sirfoga/pyhal
hal/internet/web.py
Webpage.download_to_file
def download_to_file(self, local_file, headers=None, cookies=None, chunk_size=1024): """Downloads link to local file :param local_file: Save url as this path :param headers: Headers to fetch url :param cookies: Cookies to fetch url :param chunk_size: int """ if not headers: headers = HEADERS if not cookies: cookies = {} req = requests.get(self.url, headers=headers, cookies=cookies, stream=True) with open(local_file, "wb") as local_download: for chunk in req.iter_content(chunk_size): if chunk: local_download.write(chunk)
python
def download_to_file(self, local_file, headers=None, cookies=None, chunk_size=1024): """Downloads link to local file :param local_file: Save url as this path :param headers: Headers to fetch url :param cookies: Cookies to fetch url :param chunk_size: int """ if not headers: headers = HEADERS if not cookies: cookies = {} req = requests.get(self.url, headers=headers, cookies=cookies, stream=True) with open(local_file, "wb") as local_download: for chunk in req.iter_content(chunk_size): if chunk: local_download.write(chunk)
[ "def", "download_to_file", "(", "self", ",", "local_file", ",", "headers", "=", "None", ",", "cookies", "=", "None", ",", "chunk_size", "=", "1024", ")", ":", "if", "not", "headers", ":", "headers", "=", "HEADERS", "if", "not", "cookies", ":", "cookies", "=", "{", "}", "req", "=", "requests", ".", "get", "(", "self", ".", "url", ",", "headers", "=", "headers", ",", "cookies", "=", "cookies", ",", "stream", "=", "True", ")", "with", "open", "(", "local_file", ",", "\"wb\"", ")", "as", "local_download", ":", "for", "chunk", "in", "req", ".", "iter_content", "(", "chunk_size", ")", ":", "if", "chunk", ":", "local_download", ".", "write", "(", "chunk", ")" ]
Downloads link to local file :param local_file: Save url as this path :param headers: Headers to fetch url :param cookies: Cookies to fetch url :param chunk_size: int
[ "Downloads", "link", "to", "local", "file" ]
4394d8a1f7e45bea28a255ec390f4962ee64d33a
https://github.com/sirfoga/pyhal/blob/4394d8a1f7e45bea28a255ec390f4962ee64d33a/hal/internet/web.py#L220-L241
train
tBaxter/python-card-me
card_me/base.py
getLogicalLines
def getLogicalLines(fp, allowQP=True, findBegin=False): """ Iterate through a stream, yielding one logical line at a time. Because many applications still use vCard 2.1, we have to deal with the quoted-printable encoding for long lines, as well as the vCard 3.0 and vCalendar line folding technique, a whitespace character at the start of the line. Quoted-printable data will be decoded in the Behavior decoding phase. # We're leaving this test in for awhile, because the unittest was ugly and dumb. >>> from six import StringIO >>> f=StringIO(testLines) >>> for n, l in enumerate(getLogicalLines(f)): ... print("Line %s: %s" % (n, l[0])) ... Line 0: Line 0 text, Line 0 continued. Line 1: Line 1;encoding=quoted-printable:this is an evil= evil= format. Line 2: Line 2 is a new line, it does not start with whitespace. """ if not allowQP: val = fp.read(-1) #Shouldn't need this anymore... """ if len(val) > 0: if not findBegin: val = val.decode('utf-8') else: for encoding in 'utf-8', 'utf-16-LE', 'utf-16-BE', 'iso-8859-1': try: val = val.decode(encoding) if begin_re.search(val) is not None: break except UnicodeDecodeError: pass else: raise ParseError('Could not find BEGIN when trying to determine encoding') """ # strip off any UTF8 BOMs which Python's UTF8 decoder leaves #val = val.lstrip( unicode( codecs.BOM_UTF8, "utf8" ) ) lineNumber = 1 for match in logical_lines_re.finditer(val): line, n = wrap_re.subn('', match.group()) if line != '': yield line, lineNumber lineNumber += n else: quotedPrintable = False newbuffer = six.StringIO logicalLine = newbuffer() lineNumber = 0 lineStartNumber = 0 while True: line = fp.readline() if line == '': break else: line = line.rstrip(CRLF) lineNumber += 1 if line.rstrip() == '': if logicalLine.tell() > 0: yield logicalLine.getvalue(), lineStartNumber lineStartNumber = lineNumber logicalLine = newbuffer() quotedPrintable = False continue if quotedPrintable and allowQP: logicalLine.write('\n') logicalLine.write(line) quotedPrintable = False elif line[0] in SPACEORTAB: logicalLine.write(line[1:]) elif logicalLine.tell() > 0: yield logicalLine.getvalue(), lineStartNumber lineStartNumber = lineNumber logicalLine = newbuffer() logicalLine.write(line) else: logicalLine = newbuffer() logicalLine.write(line) # vCard 2.1 allows parameters to be encoded without a parameter name. # False positives are unlikely, but possible. val = logicalLine.getvalue() if val[-1]=='=' and val.lower().find('quoted-printable') >= 0: quotedPrintable=True if logicalLine.tell() > 0: yield logicalLine.getvalue(), lineStartNumber
python
def getLogicalLines(fp, allowQP=True, findBegin=False): """ Iterate through a stream, yielding one logical line at a time. Because many applications still use vCard 2.1, we have to deal with the quoted-printable encoding for long lines, as well as the vCard 3.0 and vCalendar line folding technique, a whitespace character at the start of the line. Quoted-printable data will be decoded in the Behavior decoding phase. # We're leaving this test in for awhile, because the unittest was ugly and dumb. >>> from six import StringIO >>> f=StringIO(testLines) >>> for n, l in enumerate(getLogicalLines(f)): ... print("Line %s: %s" % (n, l[0])) ... Line 0: Line 0 text, Line 0 continued. Line 1: Line 1;encoding=quoted-printable:this is an evil= evil= format. Line 2: Line 2 is a new line, it does not start with whitespace. """ if not allowQP: val = fp.read(-1) #Shouldn't need this anymore... """ if len(val) > 0: if not findBegin: val = val.decode('utf-8') else: for encoding in 'utf-8', 'utf-16-LE', 'utf-16-BE', 'iso-8859-1': try: val = val.decode(encoding) if begin_re.search(val) is not None: break except UnicodeDecodeError: pass else: raise ParseError('Could not find BEGIN when trying to determine encoding') """ # strip off any UTF8 BOMs which Python's UTF8 decoder leaves #val = val.lstrip( unicode( codecs.BOM_UTF8, "utf8" ) ) lineNumber = 1 for match in logical_lines_re.finditer(val): line, n = wrap_re.subn('', match.group()) if line != '': yield line, lineNumber lineNumber += n else: quotedPrintable = False newbuffer = six.StringIO logicalLine = newbuffer() lineNumber = 0 lineStartNumber = 0 while True: line = fp.readline() if line == '': break else: line = line.rstrip(CRLF) lineNumber += 1 if line.rstrip() == '': if logicalLine.tell() > 0: yield logicalLine.getvalue(), lineStartNumber lineStartNumber = lineNumber logicalLine = newbuffer() quotedPrintable = False continue if quotedPrintable and allowQP: logicalLine.write('\n') logicalLine.write(line) quotedPrintable = False elif line[0] in SPACEORTAB: logicalLine.write(line[1:]) elif logicalLine.tell() > 0: yield logicalLine.getvalue(), lineStartNumber lineStartNumber = lineNumber logicalLine = newbuffer() logicalLine.write(line) else: logicalLine = newbuffer() logicalLine.write(line) # vCard 2.1 allows parameters to be encoded without a parameter name. # False positives are unlikely, but possible. val = logicalLine.getvalue() if val[-1]=='=' and val.lower().find('quoted-printable') >= 0: quotedPrintable=True if logicalLine.tell() > 0: yield logicalLine.getvalue(), lineStartNumber
[ "def", "getLogicalLines", "(", "fp", ",", "allowQP", "=", "True", ",", "findBegin", "=", "False", ")", ":", "if", "not", "allowQP", ":", "val", "=", "fp", ".", "read", "(", "-", "1", ")", "#Shouldn't need this anymore...", "\"\"\"\n if len(val) > 0:\n if not findBegin:\n val = val.decode('utf-8')\n else:\n for encoding in 'utf-8', 'utf-16-LE', 'utf-16-BE', 'iso-8859-1':\n try:\n val = val.decode(encoding)\n if begin_re.search(val) is not None:\n break\n except UnicodeDecodeError:\n pass\n else:\n raise ParseError('Could not find BEGIN when trying to determine encoding')\n \"\"\"", "# strip off any UTF8 BOMs which Python's UTF8 decoder leaves", "#val = val.lstrip( unicode( codecs.BOM_UTF8, \"utf8\" ) )", "lineNumber", "=", "1", "for", "match", "in", "logical_lines_re", ".", "finditer", "(", "val", ")", ":", "line", ",", "n", "=", "wrap_re", ".", "subn", "(", "''", ",", "match", ".", "group", "(", ")", ")", "if", "line", "!=", "''", ":", "yield", "line", ",", "lineNumber", "lineNumber", "+=", "n", "else", ":", "quotedPrintable", "=", "False", "newbuffer", "=", "six", ".", "StringIO", "logicalLine", "=", "newbuffer", "(", ")", "lineNumber", "=", "0", "lineStartNumber", "=", "0", "while", "True", ":", "line", "=", "fp", ".", "readline", "(", ")", "if", "line", "==", "''", ":", "break", "else", ":", "line", "=", "line", ".", "rstrip", "(", "CRLF", ")", "lineNumber", "+=", "1", "if", "line", ".", "rstrip", "(", ")", "==", "''", ":", "if", "logicalLine", ".", "tell", "(", ")", ">", "0", ":", "yield", "logicalLine", ".", "getvalue", "(", ")", ",", "lineStartNumber", "lineStartNumber", "=", "lineNumber", "logicalLine", "=", "newbuffer", "(", ")", "quotedPrintable", "=", "False", "continue", "if", "quotedPrintable", "and", "allowQP", ":", "logicalLine", ".", "write", "(", "'\\n'", ")", "logicalLine", ".", "write", "(", "line", ")", "quotedPrintable", "=", "False", "elif", "line", "[", "0", "]", "in", "SPACEORTAB", ":", "logicalLine", ".", "write", "(", "line", "[", "1", ":", "]", ")", "elif", "logicalLine", ".", "tell", "(", ")", ">", "0", ":", "yield", "logicalLine", ".", "getvalue", "(", ")", ",", "lineStartNumber", "lineStartNumber", "=", "lineNumber", "logicalLine", "=", "newbuffer", "(", ")", "logicalLine", ".", "write", "(", "line", ")", "else", ":", "logicalLine", "=", "newbuffer", "(", ")", "logicalLine", ".", "write", "(", "line", ")", "# vCard 2.1 allows parameters to be encoded without a parameter name.", "# False positives are unlikely, but possible.", "val", "=", "logicalLine", ".", "getvalue", "(", ")", "if", "val", "[", "-", "1", "]", "==", "'='", "and", "val", ".", "lower", "(", ")", ".", "find", "(", "'quoted-printable'", ")", ">=", "0", ":", "quotedPrintable", "=", "True", "if", "logicalLine", ".", "tell", "(", ")", ">", "0", ":", "yield", "logicalLine", ".", "getvalue", "(", ")", ",", "lineStartNumber" ]
Iterate through a stream, yielding one logical line at a time. Because many applications still use vCard 2.1, we have to deal with the quoted-printable encoding for long lines, as well as the vCard 3.0 and vCalendar line folding technique, a whitespace character at the start of the line. Quoted-printable data will be decoded in the Behavior decoding phase. # We're leaving this test in for awhile, because the unittest was ugly and dumb. >>> from six import StringIO >>> f=StringIO(testLines) >>> for n, l in enumerate(getLogicalLines(f)): ... print("Line %s: %s" % (n, l[0])) ... Line 0: Line 0 text, Line 0 continued. Line 1: Line 1;encoding=quoted-printable:this is an evil= evil= format. Line 2: Line 2 is a new line, it does not start with whitespace.
[ "Iterate", "through", "a", "stream", "yielding", "one", "logical", "line", "at", "a", "time", "." ]
ffebc7fed44f83983b7438e57263dcda67207664
https://github.com/tBaxter/python-card-me/blob/ffebc7fed44f83983b7438e57263dcda67207664/card_me/base.py#L783-L879
train
tBaxter/python-card-me
card_me/base.py
newFromBehavior
def newFromBehavior(name, id=None): """ Given a name, return a behaviored ContentLine or Component. """ name = name.upper() behavior = getBehavior(name, id) if behavior is None: raise VObjectError("No behavior found named %s" % name) if behavior.isComponent: obj = Component(name) else: obj = ContentLine(name, [], '') obj.behavior = behavior obj.isNative = False return obj
python
def newFromBehavior(name, id=None): """ Given a name, return a behaviored ContentLine or Component. """ name = name.upper() behavior = getBehavior(name, id) if behavior is None: raise VObjectError("No behavior found named %s" % name) if behavior.isComponent: obj = Component(name) else: obj = ContentLine(name, [], '') obj.behavior = behavior obj.isNative = False return obj
[ "def", "newFromBehavior", "(", "name", ",", "id", "=", "None", ")", ":", "name", "=", "name", ".", "upper", "(", ")", "behavior", "=", "getBehavior", "(", "name", ",", "id", ")", "if", "behavior", "is", "None", ":", "raise", "VObjectError", "(", "\"No behavior found named %s\"", "%", "name", ")", "if", "behavior", ".", "isComponent", ":", "obj", "=", "Component", "(", "name", ")", "else", ":", "obj", "=", "ContentLine", "(", "name", ",", "[", "]", ",", "''", ")", "obj", ".", "behavior", "=", "behavior", "obj", ".", "isNative", "=", "False", "return", "obj" ]
Given a name, return a behaviored ContentLine or Component.
[ "Given", "a", "name", "return", "a", "behaviored", "ContentLine", "or", "Component", "." ]
ffebc7fed44f83983b7438e57263dcda67207664
https://github.com/tBaxter/python-card-me/blob/ffebc7fed44f83983b7438e57263dcda67207664/card_me/base.py#L1140-L1154
train
tBaxter/python-card-me
card_me/base.py
VBase.transformFromNative
def transformFromNative(self): """ Return self transformed into a ContentLine or Component if needed. May have side effects. If it does, transformFromNative and transformToNative MUST have perfectly inverse side effects. Allowing such side effects is convenient for objects whose transformations only change a few attributes. Note that it isn't always possible for transformFromNative to be a perfect inverse of transformToNative, in such cases transformFromNative should return a new object, not self after modifications. """ if self.isNative and self.behavior and self.behavior.hasNative: try: return self.behavior.transformFromNative(self) except Exception as e: # wrap errors in transformation in a NativeError lineNumber = getattr(self, 'lineNumber', None) if isinstance(e, NativeError): if lineNumber is not None: e.lineNumber = lineNumber raise else: msg = "In transformFromNative, unhandled exception on line %s %s: %s" msg = msg % (lineNumber, sys.exc_info()[0], sys.exc_info()[1]) raise NativeError(msg, lineNumber) else: return self
python
def transformFromNative(self): """ Return self transformed into a ContentLine or Component if needed. May have side effects. If it does, transformFromNative and transformToNative MUST have perfectly inverse side effects. Allowing such side effects is convenient for objects whose transformations only change a few attributes. Note that it isn't always possible for transformFromNative to be a perfect inverse of transformToNative, in such cases transformFromNative should return a new object, not self after modifications. """ if self.isNative and self.behavior and self.behavior.hasNative: try: return self.behavior.transformFromNative(self) except Exception as e: # wrap errors in transformation in a NativeError lineNumber = getattr(self, 'lineNumber', None) if isinstance(e, NativeError): if lineNumber is not None: e.lineNumber = lineNumber raise else: msg = "In transformFromNative, unhandled exception on line %s %s: %s" msg = msg % (lineNumber, sys.exc_info()[0], sys.exc_info()[1]) raise NativeError(msg, lineNumber) else: return self
[ "def", "transformFromNative", "(", "self", ")", ":", "if", "self", ".", "isNative", "and", "self", ".", "behavior", "and", "self", ".", "behavior", ".", "hasNative", ":", "try", ":", "return", "self", ".", "behavior", ".", "transformFromNative", "(", "self", ")", "except", "Exception", "as", "e", ":", "# wrap errors in transformation in a NativeError", "lineNumber", "=", "getattr", "(", "self", ",", "'lineNumber'", ",", "None", ")", "if", "isinstance", "(", "e", ",", "NativeError", ")", ":", "if", "lineNumber", "is", "not", "None", ":", "e", ".", "lineNumber", "=", "lineNumber", "raise", "else", ":", "msg", "=", "\"In transformFromNative, unhandled exception on line %s %s: %s\"", "msg", "=", "msg", "%", "(", "lineNumber", ",", "sys", ".", "exc_info", "(", ")", "[", "0", "]", ",", "sys", ".", "exc_info", "(", ")", "[", "1", "]", ")", "raise", "NativeError", "(", "msg", ",", "lineNumber", ")", "else", ":", "return", "self" ]
Return self transformed into a ContentLine or Component if needed. May have side effects. If it does, transformFromNative and transformToNative MUST have perfectly inverse side effects. Allowing such side effects is convenient for objects whose transformations only change a few attributes. Note that it isn't always possible for transformFromNative to be a perfect inverse of transformToNative, in such cases transformFromNative should return a new object, not self after modifications.
[ "Return", "self", "transformed", "into", "a", "ContentLine", "or", "Component", "if", "needed", "." ]
ffebc7fed44f83983b7438e57263dcda67207664
https://github.com/tBaxter/python-card-me/blob/ffebc7fed44f83983b7438e57263dcda67207664/card_me/base.py#L163-L192
train
yamcs/yamcs-python
yamcs-client/yamcs/client.py
_wrap_callback_parse_time_info
def _wrap_callback_parse_time_info(subscription, on_data, message): """ Wraps a user callback to parse TimeInfo from a WebSocket data message """ if message.type == message.REPLY: time_response = web_pb2.TimeSubscriptionResponse() time_response.ParseFromString(message.reply.data) time = parse_isostring(time_response.timeInfo.currentTimeUTC) #pylint: disable=protected-access subscription._process(time) if on_data: on_data(time) elif message.type == message.DATA: if message.data.type == yamcs_pb2.TIME_INFO: time_message = getattr(message.data, 'timeInfo') time = parse_isostring(time_message.currentTimeUTC) #pylint: disable=protected-access subscription._process(time) if on_data: on_data(time)
python
def _wrap_callback_parse_time_info(subscription, on_data, message): """ Wraps a user callback to parse TimeInfo from a WebSocket data message """ if message.type == message.REPLY: time_response = web_pb2.TimeSubscriptionResponse() time_response.ParseFromString(message.reply.data) time = parse_isostring(time_response.timeInfo.currentTimeUTC) #pylint: disable=protected-access subscription._process(time) if on_data: on_data(time) elif message.type == message.DATA: if message.data.type == yamcs_pb2.TIME_INFO: time_message = getattr(message.data, 'timeInfo') time = parse_isostring(time_message.currentTimeUTC) #pylint: disable=protected-access subscription._process(time) if on_data: on_data(time)
[ "def", "_wrap_callback_parse_time_info", "(", "subscription", ",", "on_data", ",", "message", ")", ":", "if", "message", ".", "type", "==", "message", ".", "REPLY", ":", "time_response", "=", "web_pb2", ".", "TimeSubscriptionResponse", "(", ")", "time_response", ".", "ParseFromString", "(", "message", ".", "reply", ".", "data", ")", "time", "=", "parse_isostring", "(", "time_response", ".", "timeInfo", ".", "currentTimeUTC", ")", "#pylint: disable=protected-access", "subscription", ".", "_process", "(", "time", ")", "if", "on_data", ":", "on_data", "(", "time", ")", "elif", "message", ".", "type", "==", "message", ".", "DATA", ":", "if", "message", ".", "data", ".", "type", "==", "yamcs_pb2", ".", "TIME_INFO", ":", "time_message", "=", "getattr", "(", "message", ".", "data", ",", "'timeInfo'", ")", "time", "=", "parse_isostring", "(", "time_message", ".", "currentTimeUTC", ")", "#pylint: disable=protected-access", "subscription", ".", "_process", "(", "time", ")", "if", "on_data", ":", "on_data", "(", "time", ")" ]
Wraps a user callback to parse TimeInfo from a WebSocket data message
[ "Wraps", "a", "user", "callback", "to", "parse", "TimeInfo", "from", "a", "WebSocket", "data", "message" ]
1082fee8a299010cc44416bbb7518fac0ef08b48
https://github.com/yamcs/yamcs-python/blob/1082fee8a299010cc44416bbb7518fac0ef08b48/yamcs-client/yamcs/client.py#L22-L42
train
yamcs/yamcs-python
yamcs-client/yamcs/client.py
_wrap_callback_parse_event
def _wrap_callback_parse_event(on_data, message): """ Wraps a user callback to parse Events from a WebSocket data message """ if message.type == message.DATA: if message.data.type == yamcs_pb2.EVENT: event = Event(getattr(message.data, 'event')) #pylint: disable=protected-access on_data(event)
python
def _wrap_callback_parse_event(on_data, message): """ Wraps a user callback to parse Events from a WebSocket data message """ if message.type == message.DATA: if message.data.type == yamcs_pb2.EVENT: event = Event(getattr(message.data, 'event')) #pylint: disable=protected-access on_data(event)
[ "def", "_wrap_callback_parse_event", "(", "on_data", ",", "message", ")", ":", "if", "message", ".", "type", "==", "message", ".", "DATA", ":", "if", "message", ".", "data", ".", "type", "==", "yamcs_pb2", ".", "EVENT", ":", "event", "=", "Event", "(", "getattr", "(", "message", ".", "data", ",", "'event'", ")", ")", "#pylint: disable=protected-access", "on_data", "(", "event", ")" ]
Wraps a user callback to parse Events from a WebSocket data message
[ "Wraps", "a", "user", "callback", "to", "parse", "Events", "from", "a", "WebSocket", "data", "message" ]
1082fee8a299010cc44416bbb7518fac0ef08b48
https://github.com/yamcs/yamcs-python/blob/1082fee8a299010cc44416bbb7518fac0ef08b48/yamcs-client/yamcs/client.py#L45-L54
train
yamcs/yamcs-python
yamcs-client/yamcs/client.py
_wrap_callback_parse_link_event
def _wrap_callback_parse_link_event(subscription, on_data, message): """ Wraps a user callback to parse LinkEvents from a WebSocket data message """ if message.type == message.DATA: if message.data.type == yamcs_pb2.LINK_EVENT: link_message = getattr(message.data, 'linkEvent') link_event = LinkEvent(link_message) #pylint: disable=protected-access subscription._process(link_event) if on_data: on_data(link_event)
python
def _wrap_callback_parse_link_event(subscription, on_data, message): """ Wraps a user callback to parse LinkEvents from a WebSocket data message """ if message.type == message.DATA: if message.data.type == yamcs_pb2.LINK_EVENT: link_message = getattr(message.data, 'linkEvent') link_event = LinkEvent(link_message) #pylint: disable=protected-access subscription._process(link_event) if on_data: on_data(link_event)
[ "def", "_wrap_callback_parse_link_event", "(", "subscription", ",", "on_data", ",", "message", ")", ":", "if", "message", ".", "type", "==", "message", ".", "DATA", ":", "if", "message", ".", "data", ".", "type", "==", "yamcs_pb2", ".", "LINK_EVENT", ":", "link_message", "=", "getattr", "(", "message", ".", "data", ",", "'linkEvent'", ")", "link_event", "=", "LinkEvent", "(", "link_message", ")", "#pylint: disable=protected-access", "subscription", ".", "_process", "(", "link_event", ")", "if", "on_data", ":", "on_data", "(", "link_event", ")" ]
Wraps a user callback to parse LinkEvents from a WebSocket data message
[ "Wraps", "a", "user", "callback", "to", "parse", "LinkEvents", "from", "a", "WebSocket", "data", "message" ]
1082fee8a299010cc44416bbb7518fac0ef08b48
https://github.com/yamcs/yamcs-python/blob/1082fee8a299010cc44416bbb7518fac0ef08b48/yamcs-client/yamcs/client.py#L57-L69
train
yamcs/yamcs-python
yamcs-client/yamcs/client.py
YamcsClient.get_time
def get_time(self, instance): """ Return the current mission time for the specified instance. :rtype: ~datetime.datetime """ url = '/instances/{}'.format(instance) response = self.get_proto(url) message = yamcsManagement_pb2.YamcsInstance() message.ParseFromString(response.content) if message.HasField('missionTime'): return parse_isostring(message.missionTime) return None
python
def get_time(self, instance): """ Return the current mission time for the specified instance. :rtype: ~datetime.datetime """ url = '/instances/{}'.format(instance) response = self.get_proto(url) message = yamcsManagement_pb2.YamcsInstance() message.ParseFromString(response.content) if message.HasField('missionTime'): return parse_isostring(message.missionTime) return None
[ "def", "get_time", "(", "self", ",", "instance", ")", ":", "url", "=", "'/instances/{}'", ".", "format", "(", "instance", ")", "response", "=", "self", ".", "get_proto", "(", "url", ")", "message", "=", "yamcsManagement_pb2", ".", "YamcsInstance", "(", ")", "message", ".", "ParseFromString", "(", "response", ".", "content", ")", "if", "message", ".", "HasField", "(", "'missionTime'", ")", ":", "return", "parse_isostring", "(", "message", ".", "missionTime", ")", "return", "None" ]
Return the current mission time for the specified instance. :rtype: ~datetime.datetime
[ "Return", "the", "current", "mission", "time", "for", "the", "specified", "instance", "." ]
1082fee8a299010cc44416bbb7518fac0ef08b48
https://github.com/yamcs/yamcs-python/blob/1082fee8a299010cc44416bbb7518fac0ef08b48/yamcs-client/yamcs/client.py#L150-L162
train
yamcs/yamcs-python
yamcs-client/yamcs/client.py
YamcsClient.get_server_info
def get_server_info(self): """ Return general server info. :rtype: .ServerInfo """ response = self.get_proto(path='') message = rest_pb2.GetApiOverviewResponse() message.ParseFromString(response.content) return ServerInfo(message)
python
def get_server_info(self): """ Return general server info. :rtype: .ServerInfo """ response = self.get_proto(path='') message = rest_pb2.GetApiOverviewResponse() message.ParseFromString(response.content) return ServerInfo(message)
[ "def", "get_server_info", "(", "self", ")", ":", "response", "=", "self", ".", "get_proto", "(", "path", "=", "''", ")", "message", "=", "rest_pb2", ".", "GetApiOverviewResponse", "(", ")", "message", ".", "ParseFromString", "(", "response", ".", "content", ")", "return", "ServerInfo", "(", "message", ")" ]
Return general server info. :rtype: .ServerInfo
[ "Return", "general", "server", "info", "." ]
1082fee8a299010cc44416bbb7518fac0ef08b48
https://github.com/yamcs/yamcs-python/blob/1082fee8a299010cc44416bbb7518fac0ef08b48/yamcs-client/yamcs/client.py#L164-L173
train
yamcs/yamcs-python
yamcs-client/yamcs/client.py
YamcsClient.get_auth_info
def get_auth_info(self): """ Returns general authentication information. This operation does not require authenticating and is useful to test if a server requires authentication or not. :rtype: .AuthInfo """ try: response = self.session.get(self.auth_root, headers={ 'Accept': 'application/protobuf' }) message = web_pb2.AuthInfo() message.ParseFromString(response.content) return AuthInfo(message) except requests.exceptions.ConnectionError: raise ConnectionFailure('Connection to {} refused'.format(self.address))
python
def get_auth_info(self): """ Returns general authentication information. This operation does not require authenticating and is useful to test if a server requires authentication or not. :rtype: .AuthInfo """ try: response = self.session.get(self.auth_root, headers={ 'Accept': 'application/protobuf' }) message = web_pb2.AuthInfo() message.ParseFromString(response.content) return AuthInfo(message) except requests.exceptions.ConnectionError: raise ConnectionFailure('Connection to {} refused'.format(self.address))
[ "def", "get_auth_info", "(", "self", ")", ":", "try", ":", "response", "=", "self", ".", "session", ".", "get", "(", "self", ".", "auth_root", ",", "headers", "=", "{", "'Accept'", ":", "'application/protobuf'", "}", ")", "message", "=", "web_pb2", ".", "AuthInfo", "(", ")", "message", ".", "ParseFromString", "(", "response", ".", "content", ")", "return", "AuthInfo", "(", "message", ")", "except", "requests", ".", "exceptions", ".", "ConnectionError", ":", "raise", "ConnectionFailure", "(", "'Connection to {} refused'", ".", "format", "(", "self", ".", "address", ")", ")" ]
Returns general authentication information. This operation does not require authenticating and is useful to test if a server requires authentication or not. :rtype: .AuthInfo
[ "Returns", "general", "authentication", "information", ".", "This", "operation", "does", "not", "require", "authenticating", "and", "is", "useful", "to", "test", "if", "a", "server", "requires", "authentication", "or", "not", "." ]
1082fee8a299010cc44416bbb7518fac0ef08b48
https://github.com/yamcs/yamcs-python/blob/1082fee8a299010cc44416bbb7518fac0ef08b48/yamcs-client/yamcs/client.py#L175-L191
train
yamcs/yamcs-python
yamcs-client/yamcs/client.py
YamcsClient.get_user_info
def get_user_info(self): """ Get information on the authenticated user. :rtype: .UserInfo """ response = self.get_proto(path='/user') message = yamcsManagement_pb2.UserInfo() message.ParseFromString(response.content) return UserInfo(message)
python
def get_user_info(self): """ Get information on the authenticated user. :rtype: .UserInfo """ response = self.get_proto(path='/user') message = yamcsManagement_pb2.UserInfo() message.ParseFromString(response.content) return UserInfo(message)
[ "def", "get_user_info", "(", "self", ")", ":", "response", "=", "self", ".", "get_proto", "(", "path", "=", "'/user'", ")", "message", "=", "yamcsManagement_pb2", ".", "UserInfo", "(", ")", "message", ".", "ParseFromString", "(", "response", ".", "content", ")", "return", "UserInfo", "(", "message", ")" ]
Get information on the authenticated user. :rtype: .UserInfo
[ "Get", "information", "on", "the", "authenticated", "user", "." ]
1082fee8a299010cc44416bbb7518fac0ef08b48
https://github.com/yamcs/yamcs-python/blob/1082fee8a299010cc44416bbb7518fac0ef08b48/yamcs-client/yamcs/client.py#L193-L202
train
yamcs/yamcs-python
yamcs-client/yamcs/client.py
YamcsClient.create_instance
def create_instance(self, name, template, args=None, labels=None): """ Create a new instance based on an existing template. This method blocks until the instance is fully started. :param str instance: A Yamcs instance name. :param str template: The name of an existing template. """ req = rest_pb2.CreateInstanceRequest() req.name = name req.template = template if args: for k in args: req.templateArgs[k] = args[k] if labels: for k in labels: req.labels[k] = labels[k] url = '/instances' self.post_proto(url, data=req.SerializeToString())
python
def create_instance(self, name, template, args=None, labels=None): """ Create a new instance based on an existing template. This method blocks until the instance is fully started. :param str instance: A Yamcs instance name. :param str template: The name of an existing template. """ req = rest_pb2.CreateInstanceRequest() req.name = name req.template = template if args: for k in args: req.templateArgs[k] = args[k] if labels: for k in labels: req.labels[k] = labels[k] url = '/instances' self.post_proto(url, data=req.SerializeToString())
[ "def", "create_instance", "(", "self", ",", "name", ",", "template", ",", "args", "=", "None", ",", "labels", "=", "None", ")", ":", "req", "=", "rest_pb2", ".", "CreateInstanceRequest", "(", ")", "req", ".", "name", "=", "name", "req", ".", "template", "=", "template", "if", "args", ":", "for", "k", "in", "args", ":", "req", ".", "templateArgs", "[", "k", "]", "=", "args", "[", "k", "]", "if", "labels", ":", "for", "k", "in", "labels", ":", "req", ".", "labels", "[", "k", "]", "=", "labels", "[", "k", "]", "url", "=", "'/instances'", "self", ".", "post_proto", "(", "url", ",", "data", "=", "req", ".", "SerializeToString", "(", ")", ")" ]
Create a new instance based on an existing template. This method blocks until the instance is fully started. :param str instance: A Yamcs instance name. :param str template: The name of an existing template.
[ "Create", "a", "new", "instance", "based", "on", "an", "existing", "template", ".", "This", "method", "blocks", "until", "the", "instance", "is", "fully", "started", "." ]
1082fee8a299010cc44416bbb7518fac0ef08b48
https://github.com/yamcs/yamcs-python/blob/1082fee8a299010cc44416bbb7518fac0ef08b48/yamcs-client/yamcs/client.py#L222-L240
train
yamcs/yamcs-python
yamcs-client/yamcs/client.py
YamcsClient.list_instance_templates
def list_instance_templates(self): """ List the available instance templates. """ response = self.get_proto(path='/instance-templates') message = rest_pb2.ListInstanceTemplatesResponse() message.ParseFromString(response.content) templates = getattr(message, 'template') return iter([InstanceTemplate(template) for template in templates])
python
def list_instance_templates(self): """ List the available instance templates. """ response = self.get_proto(path='/instance-templates') message = rest_pb2.ListInstanceTemplatesResponse() message.ParseFromString(response.content) templates = getattr(message, 'template') return iter([InstanceTemplate(template) for template in templates])
[ "def", "list_instance_templates", "(", "self", ")", ":", "response", "=", "self", ".", "get_proto", "(", "path", "=", "'/instance-templates'", ")", "message", "=", "rest_pb2", ".", "ListInstanceTemplatesResponse", "(", ")", "message", ".", "ParseFromString", "(", "response", ".", "content", ")", "templates", "=", "getattr", "(", "message", ",", "'template'", ")", "return", "iter", "(", "[", "InstanceTemplate", "(", "template", ")", "for", "template", "in", "templates", "]", ")" ]
List the available instance templates.
[ "List", "the", "available", "instance", "templates", "." ]
1082fee8a299010cc44416bbb7518fac0ef08b48
https://github.com/yamcs/yamcs-python/blob/1082fee8a299010cc44416bbb7518fac0ef08b48/yamcs-client/yamcs/client.py#L242-L250
train
yamcs/yamcs-python
yamcs-client/yamcs/client.py
YamcsClient.list_services
def list_services(self, instance): """ List the services for an instance. :param str instance: A Yamcs instance name. :rtype: ~collections.Iterable[.Service] """ # Server does not do pagination on listings of this resource. # Return an iterator anyway for similarity with other API methods url = '/services/{}'.format(instance) response = self.get_proto(path=url) message = rest_pb2.ListServiceInfoResponse() message.ParseFromString(response.content) services = getattr(message, 'service') return iter([Service(service) for service in services])
python
def list_services(self, instance): """ List the services for an instance. :param str instance: A Yamcs instance name. :rtype: ~collections.Iterable[.Service] """ # Server does not do pagination on listings of this resource. # Return an iterator anyway for similarity with other API methods url = '/services/{}'.format(instance) response = self.get_proto(path=url) message = rest_pb2.ListServiceInfoResponse() message.ParseFromString(response.content) services = getattr(message, 'service') return iter([Service(service) for service in services])
[ "def", "list_services", "(", "self", ",", "instance", ")", ":", "# Server does not do pagination on listings of this resource.", "# Return an iterator anyway for similarity with other API methods", "url", "=", "'/services/{}'", ".", "format", "(", "instance", ")", "response", "=", "self", ".", "get_proto", "(", "path", "=", "url", ")", "message", "=", "rest_pb2", ".", "ListServiceInfoResponse", "(", ")", "message", ".", "ParseFromString", "(", "response", ".", "content", ")", "services", "=", "getattr", "(", "message", ",", "'service'", ")", "return", "iter", "(", "[", "Service", "(", "service", ")", "for", "service", "in", "services", "]", ")" ]
List the services for an instance. :param str instance: A Yamcs instance name. :rtype: ~collections.Iterable[.Service]
[ "List", "the", "services", "for", "an", "instance", "." ]
1082fee8a299010cc44416bbb7518fac0ef08b48
https://github.com/yamcs/yamcs-python/blob/1082fee8a299010cc44416bbb7518fac0ef08b48/yamcs-client/yamcs/client.py#L252-L266
train
yamcs/yamcs-python
yamcs-client/yamcs/client.py
YamcsClient.stop_service
def stop_service(self, instance, service): """ Stops a single service. :param str instance: A Yamcs instance name. :param str service: The name of the service. """ req = rest_pb2.EditServiceRequest() req.state = 'stopped' url = '/services/{}/{}'.format(instance, service) self.patch_proto(url, data=req.SerializeToString())
python
def stop_service(self, instance, service): """ Stops a single service. :param str instance: A Yamcs instance name. :param str service: The name of the service. """ req = rest_pb2.EditServiceRequest() req.state = 'stopped' url = '/services/{}/{}'.format(instance, service) self.patch_proto(url, data=req.SerializeToString())
[ "def", "stop_service", "(", "self", ",", "instance", ",", "service", ")", ":", "req", "=", "rest_pb2", ".", "EditServiceRequest", "(", ")", "req", ".", "state", "=", "'stopped'", "url", "=", "'/services/{}/{}'", ".", "format", "(", "instance", ",", "service", ")", "self", ".", "patch_proto", "(", "url", ",", "data", "=", "req", ".", "SerializeToString", "(", ")", ")" ]
Stops a single service. :param str instance: A Yamcs instance name. :param str service: The name of the service.
[ "Stops", "a", "single", "service", "." ]
1082fee8a299010cc44416bbb7518fac0ef08b48
https://github.com/yamcs/yamcs-python/blob/1082fee8a299010cc44416bbb7518fac0ef08b48/yamcs-client/yamcs/client.py#L280-L290
train
yamcs/yamcs-python
yamcs-client/yamcs/client.py
YamcsClient.list_processors
def list_processors(self, instance=None): """ Lists the processors. Processors are returned in lexicographical order. :param Optional[str] instance: A Yamcs instance name. :rtype: ~collections.Iterable[.Processor] """ # Server does not do pagination on listings of this resource. # Return an iterator anyway for similarity with other API methods url = '/processors' if instance: url += '/' + instance response = self.get_proto(path=url) message = rest_pb2.ListProcessorsResponse() message.ParseFromString(response.content) processors = getattr(message, 'processor') return iter([Processor(processor) for processor in processors])
python
def list_processors(self, instance=None): """ Lists the processors. Processors are returned in lexicographical order. :param Optional[str] instance: A Yamcs instance name. :rtype: ~collections.Iterable[.Processor] """ # Server does not do pagination on listings of this resource. # Return an iterator anyway for similarity with other API methods url = '/processors' if instance: url += '/' + instance response = self.get_proto(path=url) message = rest_pb2.ListProcessorsResponse() message.ParseFromString(response.content) processors = getattr(message, 'processor') return iter([Processor(processor) for processor in processors])
[ "def", "list_processors", "(", "self", ",", "instance", "=", "None", ")", ":", "# Server does not do pagination on listings of this resource.", "# Return an iterator anyway for similarity with other API methods", "url", "=", "'/processors'", "if", "instance", ":", "url", "+=", "'/'", "+", "instance", "response", "=", "self", ".", "get_proto", "(", "path", "=", "url", ")", "message", "=", "rest_pb2", ".", "ListProcessorsResponse", "(", ")", "message", ".", "ParseFromString", "(", "response", ".", "content", ")", "processors", "=", "getattr", "(", "message", ",", "'processor'", ")", "return", "iter", "(", "[", "Processor", "(", "processor", ")", "for", "processor", "in", "processors", "]", ")" ]
Lists the processors. Processors are returned in lexicographical order. :param Optional[str] instance: A Yamcs instance name. :rtype: ~collections.Iterable[.Processor]
[ "Lists", "the", "processors", "." ]
1082fee8a299010cc44416bbb7518fac0ef08b48
https://github.com/yamcs/yamcs-python/blob/1082fee8a299010cc44416bbb7518fac0ef08b48/yamcs-client/yamcs/client.py#L292-L310
train
yamcs/yamcs-python
yamcs-client/yamcs/client.py
YamcsClient.list_clients
def list_clients(self, instance=None): """ Lists the clients. :param Optional[str] instance: A Yamcs instance name. :rtype: ~collections.Iterable[yamcs.model.Client] """ # Server does not do pagination on listings of this resource. # Return an iterator anyway for similarity with other API methods url = '/clients' if instance: url = '/instances/{}/clients'.format(instance) response = self.get_proto(path=url) message = rest_pb2.ListClientsResponse() message.ParseFromString(response.content) clients = getattr(message, 'client') return iter([Client(client) for client in clients])
python
def list_clients(self, instance=None): """ Lists the clients. :param Optional[str] instance: A Yamcs instance name. :rtype: ~collections.Iterable[yamcs.model.Client] """ # Server does not do pagination on listings of this resource. # Return an iterator anyway for similarity with other API methods url = '/clients' if instance: url = '/instances/{}/clients'.format(instance) response = self.get_proto(path=url) message = rest_pb2.ListClientsResponse() message.ParseFromString(response.content) clients = getattr(message, 'client') return iter([Client(client) for client in clients])
[ "def", "list_clients", "(", "self", ",", "instance", "=", "None", ")", ":", "# Server does not do pagination on listings of this resource.", "# Return an iterator anyway for similarity with other API methods", "url", "=", "'/clients'", "if", "instance", ":", "url", "=", "'/instances/{}/clients'", ".", "format", "(", "instance", ")", "response", "=", "self", ".", "get_proto", "(", "path", "=", "url", ")", "message", "=", "rest_pb2", ".", "ListClientsResponse", "(", ")", "message", ".", "ParseFromString", "(", "response", ".", "content", ")", "clients", "=", "getattr", "(", "message", ",", "'client'", ")", "return", "iter", "(", "[", "Client", "(", "client", ")", "for", "client", "in", "clients", "]", ")" ]
Lists the clients. :param Optional[str] instance: A Yamcs instance name. :rtype: ~collections.Iterable[yamcs.model.Client]
[ "Lists", "the", "clients", "." ]
1082fee8a299010cc44416bbb7518fac0ef08b48
https://github.com/yamcs/yamcs-python/blob/1082fee8a299010cc44416bbb7518fac0ef08b48/yamcs-client/yamcs/client.py#L312-L328
train
yamcs/yamcs-python
yamcs-client/yamcs/client.py
YamcsClient.list_instances
def list_instances(self): """ Lists the instances. Instances are returned in lexicographical order. :rtype: ~collections.Iterable[.Instance] """ # Server does not do pagination on listings of this resource. # Return an iterator anyway for similarity with other API methods response = self.get_proto(path='/instances') message = rest_pb2.ListInstancesResponse() message.ParseFromString(response.content) instances = getattr(message, 'instance') return iter([Instance(instance) for instance in instances])
python
def list_instances(self): """ Lists the instances. Instances are returned in lexicographical order. :rtype: ~collections.Iterable[.Instance] """ # Server does not do pagination on listings of this resource. # Return an iterator anyway for similarity with other API methods response = self.get_proto(path='/instances') message = rest_pb2.ListInstancesResponse() message.ParseFromString(response.content) instances = getattr(message, 'instance') return iter([Instance(instance) for instance in instances])
[ "def", "list_instances", "(", "self", ")", ":", "# Server does not do pagination on listings of this resource.", "# Return an iterator anyway for similarity with other API methods", "response", "=", "self", ".", "get_proto", "(", "path", "=", "'/instances'", ")", "message", "=", "rest_pb2", ".", "ListInstancesResponse", "(", ")", "message", ".", "ParseFromString", "(", "response", ".", "content", ")", "instances", "=", "getattr", "(", "message", ",", "'instance'", ")", "return", "iter", "(", "[", "Instance", "(", "instance", ")", "for", "instance", "in", "instances", "]", ")" ]
Lists the instances. Instances are returned in lexicographical order. :rtype: ~collections.Iterable[.Instance]
[ "Lists", "the", "instances", "." ]
1082fee8a299010cc44416bbb7518fac0ef08b48
https://github.com/yamcs/yamcs-python/blob/1082fee8a299010cc44416bbb7518fac0ef08b48/yamcs-client/yamcs/client.py#L340-L354
train
yamcs/yamcs-python
yamcs-client/yamcs/client.py
YamcsClient.start_instance
def start_instance(self, instance): """ Starts a single instance. :param str instance: A Yamcs instance name. """ params = {'state': 'running'} url = '/instances/{}'.format(instance) self.patch_proto(url, params=params)
python
def start_instance(self, instance): """ Starts a single instance. :param str instance: A Yamcs instance name. """ params = {'state': 'running'} url = '/instances/{}'.format(instance) self.patch_proto(url, params=params)
[ "def", "start_instance", "(", "self", ",", "instance", ")", ":", "params", "=", "{", "'state'", ":", "'running'", "}", "url", "=", "'/instances/{}'", ".", "format", "(", "instance", ")", "self", ".", "patch_proto", "(", "url", ",", "params", "=", "params", ")" ]
Starts a single instance. :param str instance: A Yamcs instance name.
[ "Starts", "a", "single", "instance", "." ]
1082fee8a299010cc44416bbb7518fac0ef08b48
https://github.com/yamcs/yamcs-python/blob/1082fee8a299010cc44416bbb7518fac0ef08b48/yamcs-client/yamcs/client.py#L356-L364
train
yamcs/yamcs-python
yamcs-client/yamcs/client.py
YamcsClient.stop_instance
def stop_instance(self, instance): """ Stops a single instance. :param str instance: A Yamcs instance name. """ params = {'state': 'stopped'} url = '/instances/{}'.format(instance) self.patch_proto(url, params=params)
python
def stop_instance(self, instance): """ Stops a single instance. :param str instance: A Yamcs instance name. """ params = {'state': 'stopped'} url = '/instances/{}'.format(instance) self.patch_proto(url, params=params)
[ "def", "stop_instance", "(", "self", ",", "instance", ")", ":", "params", "=", "{", "'state'", ":", "'stopped'", "}", "url", "=", "'/instances/{}'", ".", "format", "(", "instance", ")", "self", ".", "patch_proto", "(", "url", ",", "params", "=", "params", ")" ]
Stops a single instance. :param str instance: A Yamcs instance name.
[ "Stops", "a", "single", "instance", "." ]
1082fee8a299010cc44416bbb7518fac0ef08b48
https://github.com/yamcs/yamcs-python/blob/1082fee8a299010cc44416bbb7518fac0ef08b48/yamcs-client/yamcs/client.py#L366-L374
train
yamcs/yamcs-python
yamcs-client/yamcs/client.py
YamcsClient.restart_instance
def restart_instance(self, instance): """ Restarts a single instance. :param str instance: A Yamcs instance name. """ params = {'state': 'restarted'} url = '/instances/{}'.format(instance) self.patch_proto(url, params=params)
python
def restart_instance(self, instance): """ Restarts a single instance. :param str instance: A Yamcs instance name. """ params = {'state': 'restarted'} url = '/instances/{}'.format(instance) self.patch_proto(url, params=params)
[ "def", "restart_instance", "(", "self", ",", "instance", ")", ":", "params", "=", "{", "'state'", ":", "'restarted'", "}", "url", "=", "'/instances/{}'", ".", "format", "(", "instance", ")", "self", ".", "patch_proto", "(", "url", ",", "params", "=", "params", ")" ]
Restarts a single instance. :param str instance: A Yamcs instance name.
[ "Restarts", "a", "single", "instance", "." ]
1082fee8a299010cc44416bbb7518fac0ef08b48
https://github.com/yamcs/yamcs-python/blob/1082fee8a299010cc44416bbb7518fac0ef08b48/yamcs-client/yamcs/client.py#L376-L384
train
yamcs/yamcs-python
yamcs-client/yamcs/client.py
YamcsClient.list_data_links
def list_data_links(self, instance): """ Lists the data links visible to this client. Data links are returned in random order. :param str instance: A Yamcs instance name. :rtype: ~collections.Iterable[.Link] """ # Server does not do pagination on listings of this resource. # Return an iterator anyway for similarity with other API methods response = self.get_proto(path='/links/' + instance) message = rest_pb2.ListLinkInfoResponse() message.ParseFromString(response.content) links = getattr(message, 'link') return iter([Link(link) for link in links])
python
def list_data_links(self, instance): """ Lists the data links visible to this client. Data links are returned in random order. :param str instance: A Yamcs instance name. :rtype: ~collections.Iterable[.Link] """ # Server does not do pagination on listings of this resource. # Return an iterator anyway for similarity with other API methods response = self.get_proto(path='/links/' + instance) message = rest_pb2.ListLinkInfoResponse() message.ParseFromString(response.content) links = getattr(message, 'link') return iter([Link(link) for link in links])
[ "def", "list_data_links", "(", "self", ",", "instance", ")", ":", "# Server does not do pagination on listings of this resource.", "# Return an iterator anyway for similarity with other API methods", "response", "=", "self", ".", "get_proto", "(", "path", "=", "'/links/'", "+", "instance", ")", "message", "=", "rest_pb2", ".", "ListLinkInfoResponse", "(", ")", "message", ".", "ParseFromString", "(", "response", ".", "content", ")", "links", "=", "getattr", "(", "message", ",", "'link'", ")", "return", "iter", "(", "[", "Link", "(", "link", ")", "for", "link", "in", "links", "]", ")" ]
Lists the data links visible to this client. Data links are returned in random order. :param str instance: A Yamcs instance name. :rtype: ~collections.Iterable[.Link]
[ "Lists", "the", "data", "links", "visible", "to", "this", "client", "." ]
1082fee8a299010cc44416bbb7518fac0ef08b48
https://github.com/yamcs/yamcs-python/blob/1082fee8a299010cc44416bbb7518fac0ef08b48/yamcs-client/yamcs/client.py#L386-L401
train
yamcs/yamcs-python
yamcs-client/yamcs/client.py
YamcsClient.send_event
def send_event(self, instance, message, event_type=None, time=None, severity='info', source=None, sequence_number=None): """ Post a new event. :param str instance: A Yamcs instance name. :param str message: Event message. :param Optional[str] event_type: Type of event. :param severity: The severity level of the event. One of ``info``, ``watch``, ``warning``, ``critical`` or ``severe``. Defaults to ``info``. :type severity: Optional[str] :param time: Time of the event. If unspecified, defaults to mission time. :type time: Optional[~datetime.datetime] :param source: Source of the event. Useful for grouping events in the archive. When unset this defaults to ``User``. :type source: Optional[str] :param sequence_number: Sequence number of this event. This is primarily used to determine unicity of events coming from the same source. If not set Yamcs will automatically assign a sequential number as if every submitted event is unique. :type sequence_number: Optional[int] """ req = rest_pb2.CreateEventRequest() req.message = message req.severity = severity if event_type: req.type = event_type if time: req.time = to_isostring(time) if source: req.source = source if sequence_number is not None: req.sequence_number = sequence_number url = '/archive/{}/events'.format(instance) self.post_proto(url, data=req.SerializeToString())
python
def send_event(self, instance, message, event_type=None, time=None, severity='info', source=None, sequence_number=None): """ Post a new event. :param str instance: A Yamcs instance name. :param str message: Event message. :param Optional[str] event_type: Type of event. :param severity: The severity level of the event. One of ``info``, ``watch``, ``warning``, ``critical`` or ``severe``. Defaults to ``info``. :type severity: Optional[str] :param time: Time of the event. If unspecified, defaults to mission time. :type time: Optional[~datetime.datetime] :param source: Source of the event. Useful for grouping events in the archive. When unset this defaults to ``User``. :type source: Optional[str] :param sequence_number: Sequence number of this event. This is primarily used to determine unicity of events coming from the same source. If not set Yamcs will automatically assign a sequential number as if every submitted event is unique. :type sequence_number: Optional[int] """ req = rest_pb2.CreateEventRequest() req.message = message req.severity = severity if event_type: req.type = event_type if time: req.time = to_isostring(time) if source: req.source = source if sequence_number is not None: req.sequence_number = sequence_number url = '/archive/{}/events'.format(instance) self.post_proto(url, data=req.SerializeToString())
[ "def", "send_event", "(", "self", ",", "instance", ",", "message", ",", "event_type", "=", "None", ",", "time", "=", "None", ",", "severity", "=", "'info'", ",", "source", "=", "None", ",", "sequence_number", "=", "None", ")", ":", "req", "=", "rest_pb2", ".", "CreateEventRequest", "(", ")", "req", ".", "message", "=", "message", "req", ".", "severity", "=", "severity", "if", "event_type", ":", "req", ".", "type", "=", "event_type", "if", "time", ":", "req", ".", "time", "=", "to_isostring", "(", "time", ")", "if", "source", ":", "req", ".", "source", "=", "source", "if", "sequence_number", "is", "not", "None", ":", "req", ".", "sequence_number", "=", "sequence_number", "url", "=", "'/archive/{}/events'", ".", "format", "(", "instance", ")", "self", ".", "post_proto", "(", "url", ",", "data", "=", "req", ".", "SerializeToString", "(", ")", ")" ]
Post a new event. :param str instance: A Yamcs instance name. :param str message: Event message. :param Optional[str] event_type: Type of event. :param severity: The severity level of the event. One of ``info``, ``watch``, ``warning``, ``critical`` or ``severe``. Defaults to ``info``. :type severity: Optional[str] :param time: Time of the event. If unspecified, defaults to mission time. :type time: Optional[~datetime.datetime] :param source: Source of the event. Useful for grouping events in the archive. When unset this defaults to ``User``. :type source: Optional[str] :param sequence_number: Sequence number of this event. This is primarily used to determine unicity of events coming from the same source. If not set Yamcs will automatically assign a sequential number as if every submitted event is unique. :type sequence_number: Optional[int]
[ "Post", "a", "new", "event", "." ]
1082fee8a299010cc44416bbb7518fac0ef08b48
https://github.com/yamcs/yamcs-python/blob/1082fee8a299010cc44416bbb7518fac0ef08b48/yamcs-client/yamcs/client.py#L403-L444
train
yamcs/yamcs-python
yamcs-client/yamcs/client.py
YamcsClient.get_data_link
def get_data_link(self, instance, link): """ Gets a single data link. :param str instance: A Yamcs instance name. :param str link: The name of the data link. :rtype: .Link """ response = self.get_proto('/links/{}/{}'.format(instance, link)) message = yamcsManagement_pb2.LinkInfo() message.ParseFromString(response.content) return Link(message)
python
def get_data_link(self, instance, link): """ Gets a single data link. :param str instance: A Yamcs instance name. :param str link: The name of the data link. :rtype: .Link """ response = self.get_proto('/links/{}/{}'.format(instance, link)) message = yamcsManagement_pb2.LinkInfo() message.ParseFromString(response.content) return Link(message)
[ "def", "get_data_link", "(", "self", ",", "instance", ",", "link", ")", ":", "response", "=", "self", ".", "get_proto", "(", "'/links/{}/{}'", ".", "format", "(", "instance", ",", "link", ")", ")", "message", "=", "yamcsManagement_pb2", ".", "LinkInfo", "(", ")", "message", ".", "ParseFromString", "(", "response", ".", "content", ")", "return", "Link", "(", "message", ")" ]
Gets a single data link. :param str instance: A Yamcs instance name. :param str link: The name of the data link. :rtype: .Link
[ "Gets", "a", "single", "data", "link", "." ]
1082fee8a299010cc44416bbb7518fac0ef08b48
https://github.com/yamcs/yamcs-python/blob/1082fee8a299010cc44416bbb7518fac0ef08b48/yamcs-client/yamcs/client.py#L446-L457
train
yamcs/yamcs-python
yamcs-client/yamcs/client.py
YamcsClient.enable_data_link
def enable_data_link(self, instance, link): """ Enables a data link. :param str instance: A Yamcs instance name. :param str link: The name of the data link. """ req = rest_pb2.EditLinkRequest() req.state = 'enabled' url = '/links/{}/{}'.format(instance, link) self.patch_proto(url, data=req.SerializeToString())
python
def enable_data_link(self, instance, link): """ Enables a data link. :param str instance: A Yamcs instance name. :param str link: The name of the data link. """ req = rest_pb2.EditLinkRequest() req.state = 'enabled' url = '/links/{}/{}'.format(instance, link) self.patch_proto(url, data=req.SerializeToString())
[ "def", "enable_data_link", "(", "self", ",", "instance", ",", "link", ")", ":", "req", "=", "rest_pb2", ".", "EditLinkRequest", "(", ")", "req", ".", "state", "=", "'enabled'", "url", "=", "'/links/{}/{}'", ".", "format", "(", "instance", ",", "link", ")", "self", ".", "patch_proto", "(", "url", ",", "data", "=", "req", ".", "SerializeToString", "(", ")", ")" ]
Enables a data link. :param str instance: A Yamcs instance name. :param str link: The name of the data link.
[ "Enables", "a", "data", "link", "." ]
1082fee8a299010cc44416bbb7518fac0ef08b48
https://github.com/yamcs/yamcs-python/blob/1082fee8a299010cc44416bbb7518fac0ef08b48/yamcs-client/yamcs/client.py#L459-L469
train
yamcs/yamcs-python
yamcs-client/yamcs/client.py
YamcsClient.create_data_link_subscription
def create_data_link_subscription(self, instance, on_data=None, timeout=60): """ Create a new subscription for receiving data link updates of an instance. This method returns a future, then returns immediately. Stop the subscription by canceling the future. :param str instance: A Yamcs instance name. :param on_data: Function that gets called with :class:`.LinkEvent` updates. :type on_data: Optional[Callable[.LinkEvent]) :param timeout: The amount of seconds to wait for the request to complete. :type timeout: Optional[float] :return: Future that can be used to manage the background websocket subscription. :rtype: .DataLinkSubscription """ manager = WebSocketSubscriptionManager(self, resource='links') # Represent subscription as a future subscription = DataLinkSubscription(manager) wrapped_callback = functools.partial( _wrap_callback_parse_link_event, subscription, on_data) manager.open(wrapped_callback, instance) # Wait until a reply or exception is received subscription.reply(timeout=timeout) return subscription
python
def create_data_link_subscription(self, instance, on_data=None, timeout=60): """ Create a new subscription for receiving data link updates of an instance. This method returns a future, then returns immediately. Stop the subscription by canceling the future. :param str instance: A Yamcs instance name. :param on_data: Function that gets called with :class:`.LinkEvent` updates. :type on_data: Optional[Callable[.LinkEvent]) :param timeout: The amount of seconds to wait for the request to complete. :type timeout: Optional[float] :return: Future that can be used to manage the background websocket subscription. :rtype: .DataLinkSubscription """ manager = WebSocketSubscriptionManager(self, resource='links') # Represent subscription as a future subscription = DataLinkSubscription(manager) wrapped_callback = functools.partial( _wrap_callback_parse_link_event, subscription, on_data) manager.open(wrapped_callback, instance) # Wait until a reply or exception is received subscription.reply(timeout=timeout) return subscription
[ "def", "create_data_link_subscription", "(", "self", ",", "instance", ",", "on_data", "=", "None", ",", "timeout", "=", "60", ")", ":", "manager", "=", "WebSocketSubscriptionManager", "(", "self", ",", "resource", "=", "'links'", ")", "# Represent subscription as a future", "subscription", "=", "DataLinkSubscription", "(", "manager", ")", "wrapped_callback", "=", "functools", ".", "partial", "(", "_wrap_callback_parse_link_event", ",", "subscription", ",", "on_data", ")", "manager", ".", "open", "(", "wrapped_callback", ",", "instance", ")", "# Wait until a reply or exception is received", "subscription", ".", "reply", "(", "timeout", "=", "timeout", ")", "return", "subscription" ]
Create a new subscription for receiving data link updates of an instance. This method returns a future, then returns immediately. Stop the subscription by canceling the future. :param str instance: A Yamcs instance name. :param on_data: Function that gets called with :class:`.LinkEvent` updates. :type on_data: Optional[Callable[.LinkEvent]) :param timeout: The amount of seconds to wait for the request to complete. :type timeout: Optional[float] :return: Future that can be used to manage the background websocket subscription. :rtype: .DataLinkSubscription
[ "Create", "a", "new", "subscription", "for", "receiving", "data", "link", "updates", "of", "an", "instance", "." ]
1082fee8a299010cc44416bbb7518fac0ef08b48
https://github.com/yamcs/yamcs-python/blob/1082fee8a299010cc44416bbb7518fac0ef08b48/yamcs-client/yamcs/client.py#L483-L517
train
yamcs/yamcs-python
yamcs-client/yamcs/client.py
YamcsClient.create_time_subscription
def create_time_subscription(self, instance, on_data=None, timeout=60): """ Create a new subscription for receiving time updates of an instance. Time updates are emitted at 1Hz. This method returns a future, then returns immediately. Stop the subscription by canceling the future. :param str instance: A Yamcs instance name :param on_data: Function that gets called with :class:`~datetime.datetime` updates. :type on_data: Optional[Callable[~datetime.datetime]) :param timeout: The amount of seconds to wait for the request to complete. :type timeout: Optional[float] :return: Future that can be used to manage the background websocket subscription. :rtype: .TimeSubscription """ manager = WebSocketSubscriptionManager(self, resource='time') # Represent subscription as a future subscription = TimeSubscription(manager) wrapped_callback = functools.partial( _wrap_callback_parse_time_info, subscription, on_data) manager.open(wrapped_callback, instance) # Wait until a reply or exception is received subscription.reply(timeout=timeout) return subscription
python
def create_time_subscription(self, instance, on_data=None, timeout=60): """ Create a new subscription for receiving time updates of an instance. Time updates are emitted at 1Hz. This method returns a future, then returns immediately. Stop the subscription by canceling the future. :param str instance: A Yamcs instance name :param on_data: Function that gets called with :class:`~datetime.datetime` updates. :type on_data: Optional[Callable[~datetime.datetime]) :param timeout: The amount of seconds to wait for the request to complete. :type timeout: Optional[float] :return: Future that can be used to manage the background websocket subscription. :rtype: .TimeSubscription """ manager = WebSocketSubscriptionManager(self, resource='time') # Represent subscription as a future subscription = TimeSubscription(manager) wrapped_callback = functools.partial( _wrap_callback_parse_time_info, subscription, on_data) manager.open(wrapped_callback, instance) # Wait until a reply or exception is received subscription.reply(timeout=timeout) return subscription
[ "def", "create_time_subscription", "(", "self", ",", "instance", ",", "on_data", "=", "None", ",", "timeout", "=", "60", ")", ":", "manager", "=", "WebSocketSubscriptionManager", "(", "self", ",", "resource", "=", "'time'", ")", "# Represent subscription as a future", "subscription", "=", "TimeSubscription", "(", "manager", ")", "wrapped_callback", "=", "functools", ".", "partial", "(", "_wrap_callback_parse_time_info", ",", "subscription", ",", "on_data", ")", "manager", ".", "open", "(", "wrapped_callback", ",", "instance", ")", "# Wait until a reply or exception is received", "subscription", ".", "reply", "(", "timeout", "=", "timeout", ")", "return", "subscription" ]
Create a new subscription for receiving time updates of an instance. Time updates are emitted at 1Hz. This method returns a future, then returns immediately. Stop the subscription by canceling the future. :param str instance: A Yamcs instance name :param on_data: Function that gets called with :class:`~datetime.datetime` updates. :type on_data: Optional[Callable[~datetime.datetime]) :param timeout: The amount of seconds to wait for the request to complete. :type timeout: Optional[float] :return: Future that can be used to manage the background websocket subscription. :rtype: .TimeSubscription
[ "Create", "a", "new", "subscription", "for", "receiving", "time", "updates", "of", "an", "instance", ".", "Time", "updates", "are", "emitted", "at", "1Hz", "." ]
1082fee8a299010cc44416bbb7518fac0ef08b48
https://github.com/yamcs/yamcs-python/blob/1082fee8a299010cc44416bbb7518fac0ef08b48/yamcs-client/yamcs/client.py#L519-L554
train
yamcs/yamcs-python
yamcs-client/yamcs/client.py
YamcsClient.create_event_subscription
def create_event_subscription(self, instance, on_data, timeout=60): """ Create a new subscription for receiving events of an instance. This method returns a future, then returns immediately. Stop the subscription by canceling the future. :param str instance: A Yamcs instance name :param on_data: Function that gets called on each :class:`.Event`. :type on_data: Optional[Callable[.Event]) :param timeout: The amount of seconds to wait for the request to complete. :type timeout: Optional[float] :return: Future that can be used to manage the background websocket subscription. :rtype: .WebSocketSubscriptionFuture """ manager = WebSocketSubscriptionManager(self, resource='events') # Represent subscription as a future subscription = WebSocketSubscriptionFuture(manager) wrapped_callback = functools.partial( _wrap_callback_parse_event, on_data) manager.open(wrapped_callback, instance) # Wait until a reply or exception is received subscription.reply(timeout=timeout) return subscription
python
def create_event_subscription(self, instance, on_data, timeout=60): """ Create a new subscription for receiving events of an instance. This method returns a future, then returns immediately. Stop the subscription by canceling the future. :param str instance: A Yamcs instance name :param on_data: Function that gets called on each :class:`.Event`. :type on_data: Optional[Callable[.Event]) :param timeout: The amount of seconds to wait for the request to complete. :type timeout: Optional[float] :return: Future that can be used to manage the background websocket subscription. :rtype: .WebSocketSubscriptionFuture """ manager = WebSocketSubscriptionManager(self, resource='events') # Represent subscription as a future subscription = WebSocketSubscriptionFuture(manager) wrapped_callback = functools.partial( _wrap_callback_parse_event, on_data) manager.open(wrapped_callback, instance) # Wait until a reply or exception is received subscription.reply(timeout=timeout) return subscription
[ "def", "create_event_subscription", "(", "self", ",", "instance", ",", "on_data", ",", "timeout", "=", "60", ")", ":", "manager", "=", "WebSocketSubscriptionManager", "(", "self", ",", "resource", "=", "'events'", ")", "# Represent subscription as a future", "subscription", "=", "WebSocketSubscriptionFuture", "(", "manager", ")", "wrapped_callback", "=", "functools", ".", "partial", "(", "_wrap_callback_parse_event", ",", "on_data", ")", "manager", ".", "open", "(", "wrapped_callback", ",", "instance", ")", "# Wait until a reply or exception is received", "subscription", ".", "reply", "(", "timeout", "=", "timeout", ")", "return", "subscription" ]
Create a new subscription for receiving events of an instance. This method returns a future, then returns immediately. Stop the subscription by canceling the future. :param str instance: A Yamcs instance name :param on_data: Function that gets called on each :class:`.Event`. :type on_data: Optional[Callable[.Event]) :param timeout: The amount of seconds to wait for the request to complete. :type timeout: Optional[float] :return: Future that can be used to manage the background websocket subscription. :rtype: .WebSocketSubscriptionFuture
[ "Create", "a", "new", "subscription", "for", "receiving", "events", "of", "an", "instance", "." ]
1082fee8a299010cc44416bbb7518fac0ef08b48
https://github.com/yamcs/yamcs-python/blob/1082fee8a299010cc44416bbb7518fac0ef08b48/yamcs-client/yamcs/client.py#L556-L589
train
hozn/keepassdb
keepassdb/db.py
Database.remove_group
def remove_group(self, group): """ Remove the specified group. """ if not isinstance(group, Group): raise TypeError("group must be Group") if group not in self.groups: raise ValueError("Group doesn't exist / is not bound to this database.") #save num entries and children before removal to avoid for loop problems num_entries = len(group.entries) for i in xrange(num_entries): self.remove_entry(group.entries[0]) # Recurse down to remove sub-groups num_children = len(group.children) for i in xrange(num_children): # We may need to copy this to avoid CME (see below) self.remove_group(group.children[0]) # Finally remove group from the parent's list. group.parent.children.remove(group) # Concurrent modification exception? Parent in recursive stack is iterating ... self.groups.remove(group)
python
def remove_group(self, group): """ Remove the specified group. """ if not isinstance(group, Group): raise TypeError("group must be Group") if group not in self.groups: raise ValueError("Group doesn't exist / is not bound to this database.") #save num entries and children before removal to avoid for loop problems num_entries = len(group.entries) for i in xrange(num_entries): self.remove_entry(group.entries[0]) # Recurse down to remove sub-groups num_children = len(group.children) for i in xrange(num_children): # We may need to copy this to avoid CME (see below) self.remove_group(group.children[0]) # Finally remove group from the parent's list. group.parent.children.remove(group) # Concurrent modification exception? Parent in recursive stack is iterating ... self.groups.remove(group)
[ "def", "remove_group", "(", "self", ",", "group", ")", ":", "if", "not", "isinstance", "(", "group", ",", "Group", ")", ":", "raise", "TypeError", "(", "\"group must be Group\"", ")", "if", "group", "not", "in", "self", ".", "groups", ":", "raise", "ValueError", "(", "\"Group doesn't exist / is not bound to this database.\"", ")", "#save num entries and children before removal to avoid for loop problems", "num_entries", "=", "len", "(", "group", ".", "entries", ")", "for", "i", "in", "xrange", "(", "num_entries", ")", ":", "self", ".", "remove_entry", "(", "group", ".", "entries", "[", "0", "]", ")", "# Recurse down to remove sub-groups", "num_children", "=", "len", "(", "group", ".", "children", ")", "for", "i", "in", "xrange", "(", "num_children", ")", ":", "# We may need to copy this to avoid CME (see below)", "self", ".", "remove_group", "(", "group", ".", "children", "[", "0", "]", ")", "# Finally remove group from the parent's list.", "group", ".", "parent", ".", "children", ".", "remove", "(", "group", ")", "# Concurrent modification exception? Parent in recursive stack is iterating ...", "self", ".", "groups", ".", "remove", "(", "group", ")" ]
Remove the specified group.
[ "Remove", "the", "specified", "group", "." ]
cb24985d1ed04e7d7db99ecdddf80dd1a91ee48b
https://github.com/hozn/keepassdb/blob/cb24985d1ed04e7d7db99ecdddf80dd1a91ee48b/keepassdb/db.py#L359-L380
train
hozn/keepassdb
keepassdb/db.py
Database.create_entry
def create_entry(self, group, **kwargs): """ Create a new Entry object. The group which should hold the entry is needed. image must be an unsigned int >0, group a Group. :param group: The associated group. :keyword title: :keyword icon: :keyword url: :keyword username: :keyword password: :keyword notes: :keyword expires: Expiration date (if None, entry will never expire). :type expires: datetime :return: The new entry. :rtype: :class:`keepassdb.model.Entry` """ if group not in self.groups: raise ValueError("Group doesn't exist / is not bound to this database.") uuid = binascii.hexlify(get_random_bytes(16)) entry = Entry(uuid=uuid, group_id=group.id, created=util.now(), modified=util.now(), accessed=util.now(), **kwargs) self.entries.append(entry) group.entries.append(entry) return entry
python
def create_entry(self, group, **kwargs): """ Create a new Entry object. The group which should hold the entry is needed. image must be an unsigned int >0, group a Group. :param group: The associated group. :keyword title: :keyword icon: :keyword url: :keyword username: :keyword password: :keyword notes: :keyword expires: Expiration date (if None, entry will never expire). :type expires: datetime :return: The new entry. :rtype: :class:`keepassdb.model.Entry` """ if group not in self.groups: raise ValueError("Group doesn't exist / is not bound to this database.") uuid = binascii.hexlify(get_random_bytes(16)) entry = Entry(uuid=uuid, group_id=group.id, created=util.now(), modified=util.now(), accessed=util.now(), **kwargs) self.entries.append(entry) group.entries.append(entry) return entry
[ "def", "create_entry", "(", "self", ",", "group", ",", "*", "*", "kwargs", ")", ":", "if", "group", "not", "in", "self", ".", "groups", ":", "raise", "ValueError", "(", "\"Group doesn't exist / is not bound to this database.\"", ")", "uuid", "=", "binascii", ".", "hexlify", "(", "get_random_bytes", "(", "16", ")", ")", "entry", "=", "Entry", "(", "uuid", "=", "uuid", ",", "group_id", "=", "group", ".", "id", ",", "created", "=", "util", ".", "now", "(", ")", ",", "modified", "=", "util", ".", "now", "(", ")", ",", "accessed", "=", "util", ".", "now", "(", ")", ",", "*", "*", "kwargs", ")", "self", ".", "entries", ".", "append", "(", "entry", ")", "group", ".", "entries", ".", "append", "(", "entry", ")", "return", "entry" ]
Create a new Entry object. The group which should hold the entry is needed. image must be an unsigned int >0, group a Group. :param group: The associated group. :keyword title: :keyword icon: :keyword url: :keyword username: :keyword password: :keyword notes: :keyword expires: Expiration date (if None, entry will never expire). :type expires: datetime :return: The new entry. :rtype: :class:`keepassdb.model.Entry`
[ "Create", "a", "new", "Entry", "object", ".", "The", "group", "which", "should", "hold", "the", "entry", "is", "needed", "." ]
cb24985d1ed04e7d7db99ecdddf80dd1a91ee48b
https://github.com/hozn/keepassdb/blob/cb24985d1ed04e7d7db99ecdddf80dd1a91ee48b/keepassdb/db.py#L449-L485
train
hozn/keepassdb
keepassdb/db.py
Database._bind_model
def _bind_model(self): """ This method binds the various model objects together in the correct hierarchy and adds referneces to this database object in the groups. """ if self.groups[0].level != 0: self.log.info("Got invalid first group: {0}".format(self.groups[0])) raise ValueError("Invalid group tree: first group must have level of 0 (got {0})".format(self.groups[0].level)) # The KeePassX source code maintains that first group to have incremented # level is a child of the previous group with a lower level. # # [R] # | A (1) # +-| B (2) # | | C (2) # | D (1) # +-| E (2) # | F (2) # +-| G (3) # | H (3) # | I (3) # class Stack(list): """ A class to make parsing code slightly more semantic. """ def push(self, el): self.append(el) # This is a different parsing approach than taken by KeePassX (or other python # libs), but seems a little more intuitive. It could be further simplified # by noting that current_parent is always parent_stack[-1], but this is a bit # more readable. parent_stack = Stack([self.root]) current_parent = self.root prev_group = None for g in self.groups: g.db = self # Bind database to group objects if prev_group is not None: # first iteration is exceptional if g.level > prev_group.level: # Always true for iteration 1 since root has level of -1 # Dropping down a level; the previous group is the parent current_parent = prev_group parent_stack.push(current_parent) elif g.level < prev_group.level: # Pop off parents until we have a parent with a level that is less than current while g.level <= current_parent.level: current_parent = parent_stack.pop() parent_stack.push(current_parent) # We want to make sure that the top of the stack always matches current parent # bi-directional child-parent binding g.parent = current_parent current_parent.children.append(g) prev_group = g # Bind group objects to entries for entry in self.entries: for group in self.groups: if entry.group_id == group.id: group.entries.append(entry) entry.group = group break else: # KeePassX adds these to the first group (i.e. root.children[0]) raise NotImplementedError("Orphaned entries not (yet) supported.")
python
def _bind_model(self): """ This method binds the various model objects together in the correct hierarchy and adds referneces to this database object in the groups. """ if self.groups[0].level != 0: self.log.info("Got invalid first group: {0}".format(self.groups[0])) raise ValueError("Invalid group tree: first group must have level of 0 (got {0})".format(self.groups[0].level)) # The KeePassX source code maintains that first group to have incremented # level is a child of the previous group with a lower level. # # [R] # | A (1) # +-| B (2) # | | C (2) # | D (1) # +-| E (2) # | F (2) # +-| G (3) # | H (3) # | I (3) # class Stack(list): """ A class to make parsing code slightly more semantic. """ def push(self, el): self.append(el) # This is a different parsing approach than taken by KeePassX (or other python # libs), but seems a little more intuitive. It could be further simplified # by noting that current_parent is always parent_stack[-1], but this is a bit # more readable. parent_stack = Stack([self.root]) current_parent = self.root prev_group = None for g in self.groups: g.db = self # Bind database to group objects if prev_group is not None: # first iteration is exceptional if g.level > prev_group.level: # Always true for iteration 1 since root has level of -1 # Dropping down a level; the previous group is the parent current_parent = prev_group parent_stack.push(current_parent) elif g.level < prev_group.level: # Pop off parents until we have a parent with a level that is less than current while g.level <= current_parent.level: current_parent = parent_stack.pop() parent_stack.push(current_parent) # We want to make sure that the top of the stack always matches current parent # bi-directional child-parent binding g.parent = current_parent current_parent.children.append(g) prev_group = g # Bind group objects to entries for entry in self.entries: for group in self.groups: if entry.group_id == group.id: group.entries.append(entry) entry.group = group break else: # KeePassX adds these to the first group (i.e. root.children[0]) raise NotImplementedError("Orphaned entries not (yet) supported.")
[ "def", "_bind_model", "(", "self", ")", ":", "if", "self", ".", "groups", "[", "0", "]", ".", "level", "!=", "0", ":", "self", ".", "log", ".", "info", "(", "\"Got invalid first group: {0}\"", ".", "format", "(", "self", ".", "groups", "[", "0", "]", ")", ")", "raise", "ValueError", "(", "\"Invalid group tree: first group must have level of 0 (got {0})\"", ".", "format", "(", "self", ".", "groups", "[", "0", "]", ".", "level", ")", ")", "# The KeePassX source code maintains that first group to have incremented ", "# level is a child of the previous group with a lower level.", "#", "# [R]", "# | A (1)", "# +-| B (2)", "# | | C (2)", "# | D (1)", "# +-| E (2)", "# | F (2)", "# +-| G (3)", "# | H (3)", "# | I (3)", "# ", "class", "Stack", "(", "list", ")", ":", "\"\"\" A class to make parsing code slightly more semantic. \"\"\"", "def", "push", "(", "self", ",", "el", ")", ":", "self", ".", "append", "(", "el", ")", "# This is a different parsing approach than taken by KeePassX (or other python ", "# libs), but seems a little more intuitive. It could be further simplified", "# by noting that current_parent is always parent_stack[-1], but this is a bit", "# more readable.", "parent_stack", "=", "Stack", "(", "[", "self", ".", "root", "]", ")", "current_parent", "=", "self", ".", "root", "prev_group", "=", "None", "for", "g", "in", "self", ".", "groups", ":", "g", ".", "db", "=", "self", "# Bind database to group objects", "if", "prev_group", "is", "not", "None", ":", "# first iteration is exceptional", "if", "g", ".", "level", ">", "prev_group", ".", "level", ":", "# Always true for iteration 1 since root has level of -1", "# Dropping down a level; the previous group is the parent", "current_parent", "=", "prev_group", "parent_stack", ".", "push", "(", "current_parent", ")", "elif", "g", ".", "level", "<", "prev_group", ".", "level", ":", "# Pop off parents until we have a parent with a level that is less than current", "while", "g", ".", "level", "<=", "current_parent", ".", "level", ":", "current_parent", "=", "parent_stack", ".", "pop", "(", ")", "parent_stack", ".", "push", "(", "current_parent", ")", "# We want to make sure that the top of the stack always matches current parent", "# bi-directional child-parent binding", "g", ".", "parent", "=", "current_parent", "current_parent", ".", "children", ".", "append", "(", "g", ")", "prev_group", "=", "g", "# Bind group objects to entries", "for", "entry", "in", "self", ".", "entries", ":", "for", "group", "in", "self", ".", "groups", ":", "if", "entry", ".", "group_id", "==", "group", ".", "id", ":", "group", ".", "entries", ".", "append", "(", "entry", ")", "entry", ".", "group", "=", "group", "break", "else", ":", "# KeePassX adds these to the first group (i.e. root.children[0])", "raise", "NotImplementedError", "(", "\"Orphaned entries not (yet) supported.\"", ")" ]
This method binds the various model objects together in the correct hierarchy and adds referneces to this database object in the groups.
[ "This", "method", "binds", "the", "various", "model", "objects", "together", "in", "the", "correct", "hierarchy", "and", "adds", "referneces", "to", "this", "database", "object", "in", "the", "groups", "." ]
cb24985d1ed04e7d7db99ecdddf80dd1a91ee48b
https://github.com/hozn/keepassdb/blob/cb24985d1ed04e7d7db99ecdddf80dd1a91ee48b/keepassdb/db.py#L556-L621
train
hozn/keepassdb
keepassdb/db.py
LockingDatabase.filepath
def filepath(self, value): """ Property for setting current filepath, automatically takes out lock on new file if not readonly db. """ if not self.readonly and self._filepath != value: if self._locked: self.log.debug("Releasing previously-held lock file: {0}".format(self.lockfile)) # Release the lock on previous filepath. self.release_lock() self._filepath = value if self._filepath is not None: self.acquire_lock() else: self._filepath = value
python
def filepath(self, value): """ Property for setting current filepath, automatically takes out lock on new file if not readonly db. """ if not self.readonly and self._filepath != value: if self._locked: self.log.debug("Releasing previously-held lock file: {0}".format(self.lockfile)) # Release the lock on previous filepath. self.release_lock() self._filepath = value if self._filepath is not None: self.acquire_lock() else: self._filepath = value
[ "def", "filepath", "(", "self", ",", "value", ")", ":", "if", "not", "self", ".", "readonly", "and", "self", ".", "_filepath", "!=", "value", ":", "if", "self", ".", "_locked", ":", "self", ".", "log", ".", "debug", "(", "\"Releasing previously-held lock file: {0}\"", ".", "format", "(", "self", ".", "lockfile", ")", ")", "# Release the lock on previous filepath.", "self", ".", "release_lock", "(", ")", "self", ".", "_filepath", "=", "value", "if", "self", ".", "_filepath", "is", "not", "None", ":", "self", ".", "acquire_lock", "(", ")", "else", ":", "self", ".", "_filepath", "=", "value" ]
Property for setting current filepath, automatically takes out lock on new file if not readonly db.
[ "Property", "for", "setting", "current", "filepath", "automatically", "takes", "out", "lock", "on", "new", "file", "if", "not", "readonly", "db", "." ]
cb24985d1ed04e7d7db99ecdddf80dd1a91ee48b
https://github.com/hozn/keepassdb/blob/cb24985d1ed04e7d7db99ecdddf80dd1a91ee48b/keepassdb/db.py#L655-L666
train
hozn/keepassdb
keepassdb/db.py
LockingDatabase.close
def close(self): """ Closes the database, releasing lock. """ super(LockingDatabase, self).close() if not self.readonly: self.release_lock()
python
def close(self): """ Closes the database, releasing lock. """ super(LockingDatabase, self).close() if not self.readonly: self.release_lock()
[ "def", "close", "(", "self", ")", ":", "super", "(", "LockingDatabase", ",", "self", ")", ".", "close", "(", ")", "if", "not", "self", ".", "readonly", ":", "self", ".", "release_lock", "(", ")" ]
Closes the database, releasing lock.
[ "Closes", "the", "database", "releasing", "lock", "." ]
cb24985d1ed04e7d7db99ecdddf80dd1a91ee48b
https://github.com/hozn/keepassdb/blob/cb24985d1ed04e7d7db99ecdddf80dd1a91ee48b/keepassdb/db.py#L719-L725
train
jmbhughes/suvi-trainer
suvitrainer/fileio.py
get_dates_file
def get_dates_file(path): """ parse dates file of dates and probability of choosing""" with open(path) as f: dates = f.readlines() return [(convert_time_string(date_string.split(" ")[0]), float(date_string.split(" ")[1])) for date_string in dates]
python
def get_dates_file(path): """ parse dates file of dates and probability of choosing""" with open(path) as f: dates = f.readlines() return [(convert_time_string(date_string.split(" ")[0]), float(date_string.split(" ")[1])) for date_string in dates]
[ "def", "get_dates_file", "(", "path", ")", ":", "with", "open", "(", "path", ")", "as", "f", ":", "dates", "=", "f", ".", "readlines", "(", ")", "return", "[", "(", "convert_time_string", "(", "date_string", ".", "split", "(", "\" \"", ")", "[", "0", "]", ")", ",", "float", "(", "date_string", ".", "split", "(", "\" \"", ")", "[", "1", "]", ")", ")", "for", "date_string", "in", "dates", "]" ]
parse dates file of dates and probability of choosing
[ "parse", "dates", "file", "of", "dates", "and", "probability", "of", "choosing" ]
3d89894a4a037286221974c7eb5634d229b4f5d4
https://github.com/jmbhughes/suvi-trainer/blob/3d89894a4a037286221974c7eb5634d229b4f5d4/suvitrainer/fileio.py#L36-L41
train
jmbhughes/suvi-trainer
suvitrainer/fileio.py
get_dates_link
def get_dates_link(url): """ download the dates file from the internet and parse it as a dates file""" urllib.request.urlretrieve(url, "temp.txt") dates = get_dates_file("temp.txt") os.remove("temp.txt") return dates
python
def get_dates_link(url): """ download the dates file from the internet and parse it as a dates file""" urllib.request.urlretrieve(url, "temp.txt") dates = get_dates_file("temp.txt") os.remove("temp.txt") return dates
[ "def", "get_dates_link", "(", "url", ")", ":", "urllib", ".", "request", ".", "urlretrieve", "(", "url", ",", "\"temp.txt\"", ")", "dates", "=", "get_dates_file", "(", "\"temp.txt\"", ")", "os", ".", "remove", "(", "\"temp.txt\"", ")", "return", "dates" ]
download the dates file from the internet and parse it as a dates file
[ "download", "the", "dates", "file", "from", "the", "internet", "and", "parse", "it", "as", "a", "dates", "file" ]
3d89894a4a037286221974c7eb5634d229b4f5d4
https://github.com/jmbhughes/suvi-trainer/blob/3d89894a4a037286221974c7eb5634d229b4f5d4/suvitrainer/fileio.py#L44-L49
train
jmbhughes/suvi-trainer
suvitrainer/fileio.py
Fetcher.parse_filename_meta
def parse_filename_meta(filename): """ taken from suvi code by vhsu Parse the metadata from a product filename, either L1b or l2. - file start - file end - platform - product :param filename: string filename of product :return: (start datetime, end datetime, platform) """ common_pattern = "_%s_%s" % ( "(?P<product>[a-zA-Z]{3}[a-zA-Z]?-[a-zA-Z0-9]{2}[a-zA-Z0-9]?-[a-zA-Z0-9]{4}[a-zA-Z0-9]?)", # product l1b, or l2 "(?P<platform>[gG][1-9]{2})" # patform, like g16 ) patterns = { # all patterns must have the common componennt "l2_pattern": re.compile("%s_s(?P<start>[0-9]{8}T[0-9]{6})Z_e(?P<end>[0-9]{8}T[0-9]{6})Z" % common_pattern), "l1b_pattern": re.compile('%s_s(?P<start>[0-9]{14})_e(?P<end>[0-9]{14})' % common_pattern), "dayfile_pattern": re.compile("%s_d(?P<start>[0-9]{8})" % common_pattern), "monthfile_pattern": re.compile("%s_m(?P<start>[0-9]{6})" % common_pattern), "yearfile_pattern": re.compile("%s_y(?P<start>[0-9]{4})" % common_pattern), } match, dt_start, dt_end = None, None, None for pat_type, pat in patterns.items(): match = pat.search(filename) if match is not None: if pat_type == "l2_pattern": # parse l2 dt_start = datetime.strptime(match.group("start"), '%Y%m%dT%H%M%S') dt_end = datetime.strptime(match.group("end"), '%Y%m%dT%H%M%S') elif pat_type == "l1b_pattern": # parse l1b dt_start = datetime.strptime(match.group("start"), '%Y%j%H%M%S%f') dt_end = datetime.strptime(match.group("end"), '%Y%j%H%M%S%f') elif pat_type == "dayfile_pattern": dt_start = datetime.strptime(match.group("start"), "%Y%m%d") dt_end = dt_start + timedelta(hours=24) elif pat_type == "monthfile_pattern": dt_start = datetime.strptime(match.group("start"), "%Y%m") dt_end = datetime(dt_start.year, dt_start.month + 1, 1) # will raise exception in December, fix when needed elif pat_type == "yearfile_pattern": dt_start = datetime.strptime(match.group("start"), "%Y") dt_end = datetime(dt_start.year + 1, 1, 1) break if match is None: if "NCEI" in filename and ".fits" in filename: dt_start = datetime.strptime("T".join(filename.split("_")[4:6]), "%Y%m%dT%H%M%S") dt_end = dt_start angstroms = int(filename.split("_")[2]) atom = "Fe" if angstroms != 304 else "He" product = "SUVI-L1b-{}{}".format(atom, angstroms) return filename, dt_start, dt_end, "g16", product else: # we didn't find any matching patterns... raise ValueError("Timestamps not detected in filename: %s" % filename) else: return filename, dt_start, dt_end, match.group("platform"), match.group("product")
python
def parse_filename_meta(filename): """ taken from suvi code by vhsu Parse the metadata from a product filename, either L1b or l2. - file start - file end - platform - product :param filename: string filename of product :return: (start datetime, end datetime, platform) """ common_pattern = "_%s_%s" % ( "(?P<product>[a-zA-Z]{3}[a-zA-Z]?-[a-zA-Z0-9]{2}[a-zA-Z0-9]?-[a-zA-Z0-9]{4}[a-zA-Z0-9]?)", # product l1b, or l2 "(?P<platform>[gG][1-9]{2})" # patform, like g16 ) patterns = { # all patterns must have the common componennt "l2_pattern": re.compile("%s_s(?P<start>[0-9]{8}T[0-9]{6})Z_e(?P<end>[0-9]{8}T[0-9]{6})Z" % common_pattern), "l1b_pattern": re.compile('%s_s(?P<start>[0-9]{14})_e(?P<end>[0-9]{14})' % common_pattern), "dayfile_pattern": re.compile("%s_d(?P<start>[0-9]{8})" % common_pattern), "monthfile_pattern": re.compile("%s_m(?P<start>[0-9]{6})" % common_pattern), "yearfile_pattern": re.compile("%s_y(?P<start>[0-9]{4})" % common_pattern), } match, dt_start, dt_end = None, None, None for pat_type, pat in patterns.items(): match = pat.search(filename) if match is not None: if pat_type == "l2_pattern": # parse l2 dt_start = datetime.strptime(match.group("start"), '%Y%m%dT%H%M%S') dt_end = datetime.strptime(match.group("end"), '%Y%m%dT%H%M%S') elif pat_type == "l1b_pattern": # parse l1b dt_start = datetime.strptime(match.group("start"), '%Y%j%H%M%S%f') dt_end = datetime.strptime(match.group("end"), '%Y%j%H%M%S%f') elif pat_type == "dayfile_pattern": dt_start = datetime.strptime(match.group("start"), "%Y%m%d") dt_end = dt_start + timedelta(hours=24) elif pat_type == "monthfile_pattern": dt_start = datetime.strptime(match.group("start"), "%Y%m") dt_end = datetime(dt_start.year, dt_start.month + 1, 1) # will raise exception in December, fix when needed elif pat_type == "yearfile_pattern": dt_start = datetime.strptime(match.group("start"), "%Y") dt_end = datetime(dt_start.year + 1, 1, 1) break if match is None: if "NCEI" in filename and ".fits" in filename: dt_start = datetime.strptime("T".join(filename.split("_")[4:6]), "%Y%m%dT%H%M%S") dt_end = dt_start angstroms = int(filename.split("_")[2]) atom = "Fe" if angstroms != 304 else "He" product = "SUVI-L1b-{}{}".format(atom, angstroms) return filename, dt_start, dt_end, "g16", product else: # we didn't find any matching patterns... raise ValueError("Timestamps not detected in filename: %s" % filename) else: return filename, dt_start, dt_end, match.group("platform"), match.group("product")
[ "def", "parse_filename_meta", "(", "filename", ")", ":", "common_pattern", "=", "\"_%s_%s\"", "%", "(", "\"(?P<product>[a-zA-Z]{3}[a-zA-Z]?-[a-zA-Z0-9]{2}[a-zA-Z0-9]?-[a-zA-Z0-9]{4}[a-zA-Z0-9]?)\"", ",", "# product l1b, or l2", "\"(?P<platform>[gG][1-9]{2})\"", "# patform, like g16", ")", "patterns", "=", "{", "# all patterns must have the common componennt", "\"l2_pattern\"", ":", "re", ".", "compile", "(", "\"%s_s(?P<start>[0-9]{8}T[0-9]{6})Z_e(?P<end>[0-9]{8}T[0-9]{6})Z\"", "%", "common_pattern", ")", ",", "\"l1b_pattern\"", ":", "re", ".", "compile", "(", "'%s_s(?P<start>[0-9]{14})_e(?P<end>[0-9]{14})'", "%", "common_pattern", ")", ",", "\"dayfile_pattern\"", ":", "re", ".", "compile", "(", "\"%s_d(?P<start>[0-9]{8})\"", "%", "common_pattern", ")", ",", "\"monthfile_pattern\"", ":", "re", ".", "compile", "(", "\"%s_m(?P<start>[0-9]{6})\"", "%", "common_pattern", ")", ",", "\"yearfile_pattern\"", ":", "re", ".", "compile", "(", "\"%s_y(?P<start>[0-9]{4})\"", "%", "common_pattern", ")", ",", "}", "match", ",", "dt_start", ",", "dt_end", "=", "None", ",", "None", ",", "None", "for", "pat_type", ",", "pat", "in", "patterns", ".", "items", "(", ")", ":", "match", "=", "pat", ".", "search", "(", "filename", ")", "if", "match", "is", "not", "None", ":", "if", "pat_type", "==", "\"l2_pattern\"", ":", "# parse l2", "dt_start", "=", "datetime", ".", "strptime", "(", "match", ".", "group", "(", "\"start\"", ")", ",", "'%Y%m%dT%H%M%S'", ")", "dt_end", "=", "datetime", ".", "strptime", "(", "match", ".", "group", "(", "\"end\"", ")", ",", "'%Y%m%dT%H%M%S'", ")", "elif", "pat_type", "==", "\"l1b_pattern\"", ":", "# parse l1b", "dt_start", "=", "datetime", ".", "strptime", "(", "match", ".", "group", "(", "\"start\"", ")", ",", "'%Y%j%H%M%S%f'", ")", "dt_end", "=", "datetime", ".", "strptime", "(", "match", ".", "group", "(", "\"end\"", ")", ",", "'%Y%j%H%M%S%f'", ")", "elif", "pat_type", "==", "\"dayfile_pattern\"", ":", "dt_start", "=", "datetime", ".", "strptime", "(", "match", ".", "group", "(", "\"start\"", ")", ",", "\"%Y%m%d\"", ")", "dt_end", "=", "dt_start", "+", "timedelta", "(", "hours", "=", "24", ")", "elif", "pat_type", "==", "\"monthfile_pattern\"", ":", "dt_start", "=", "datetime", ".", "strptime", "(", "match", ".", "group", "(", "\"start\"", ")", ",", "\"%Y%m\"", ")", "dt_end", "=", "datetime", "(", "dt_start", ".", "year", ",", "dt_start", ".", "month", "+", "1", ",", "1", ")", "# will raise exception in December, fix when needed", "elif", "pat_type", "==", "\"yearfile_pattern\"", ":", "dt_start", "=", "datetime", ".", "strptime", "(", "match", ".", "group", "(", "\"start\"", ")", ",", "\"%Y\"", ")", "dt_end", "=", "datetime", "(", "dt_start", ".", "year", "+", "1", ",", "1", ",", "1", ")", "break", "if", "match", "is", "None", ":", "if", "\"NCEI\"", "in", "filename", "and", "\".fits\"", "in", "filename", ":", "dt_start", "=", "datetime", ".", "strptime", "(", "\"T\"", ".", "join", "(", "filename", ".", "split", "(", "\"_\"", ")", "[", "4", ":", "6", "]", ")", ",", "\"%Y%m%dT%H%M%S\"", ")", "dt_end", "=", "dt_start", "angstroms", "=", "int", "(", "filename", ".", "split", "(", "\"_\"", ")", "[", "2", "]", ")", "atom", "=", "\"Fe\"", "if", "angstroms", "!=", "304", "else", "\"He\"", "product", "=", "\"SUVI-L1b-{}{}\"", ".", "format", "(", "atom", ",", "angstroms", ")", "return", "filename", ",", "dt_start", ",", "dt_end", ",", "\"g16\"", ",", "product", "else", ":", "# we didn't find any matching patterns...", "raise", "ValueError", "(", "\"Timestamps not detected in filename: %s\"", "%", "filename", ")", "else", ":", "return", "filename", ",", "dt_start", ",", "dt_end", ",", "match", ".", "group", "(", "\"platform\"", ")", ",", "match", ".", "group", "(", "\"product\"", ")" ]
taken from suvi code by vhsu Parse the metadata from a product filename, either L1b or l2. - file start - file end - platform - product :param filename: string filename of product :return: (start datetime, end datetime, platform)
[ "taken", "from", "suvi", "code", "by", "vhsu", "Parse", "the", "metadata", "from", "a", "product", "filename", "either", "L1b", "or", "l2", ".", "-", "file", "start", "-", "file", "end", "-", "platform", "-", "product" ]
3d89894a4a037286221974c7eb5634d229b4f5d4
https://github.com/jmbhughes/suvi-trainer/blob/3d89894a4a037286221974c7eb5634d229b4f5d4/suvitrainer/fileio.py#L351-L411
train
ArabellaTech/django-basic-cms
basic_cms/http.py
get_request_mock
def get_request_mock(): """Build a ``request`` mock up that is used in to render the templates in the most fidel environement as possible. This fonction is used in the get_placeholders method to render the input template and search for the placeholder within. """ basehandler = BaseHandler() basehandler.load_middleware() # http://www.python.org/dev/peps/pep-0333/ request = WSGIRequest({ 'HTTP_COOKIE': '', 'PATH_INFO': '/', 'QUERY_STRING': '', 'REMOTE_ADDR': '127.0.0.1', 'REQUEST_METHOD': 'GET', 'SERVER_NAME': 'page-request-mock', 'SCRIPT_NAME': '', 'SERVER_PORT': '80', 'SERVER_PROTOCOL': 'HTTP/1.1', 'HTTP_HOST': 'page-request-host', 'CONTENT_TYPE': 'text/html; charset=utf-8', 'wsgi.version': (1, 0), 'wsgi.url_scheme': 'http', 'wsgi.multiprocess': True, 'wsgi.multithread': False, 'wsgi.run_once': False, 'wsgi.input': StringIO() }) # Apply request middleware for middleware_method in basehandler._request_middleware: # LocaleMiddleware should never be applied a second time because # it would broke the current real request language if 'LocaleMiddleware' not in str(middleware_method.__class__): middleware_method(request) return request
python
def get_request_mock(): """Build a ``request`` mock up that is used in to render the templates in the most fidel environement as possible. This fonction is used in the get_placeholders method to render the input template and search for the placeholder within. """ basehandler = BaseHandler() basehandler.load_middleware() # http://www.python.org/dev/peps/pep-0333/ request = WSGIRequest({ 'HTTP_COOKIE': '', 'PATH_INFO': '/', 'QUERY_STRING': '', 'REMOTE_ADDR': '127.0.0.1', 'REQUEST_METHOD': 'GET', 'SERVER_NAME': 'page-request-mock', 'SCRIPT_NAME': '', 'SERVER_PORT': '80', 'SERVER_PROTOCOL': 'HTTP/1.1', 'HTTP_HOST': 'page-request-host', 'CONTENT_TYPE': 'text/html; charset=utf-8', 'wsgi.version': (1, 0), 'wsgi.url_scheme': 'http', 'wsgi.multiprocess': True, 'wsgi.multithread': False, 'wsgi.run_once': False, 'wsgi.input': StringIO() }) # Apply request middleware for middleware_method in basehandler._request_middleware: # LocaleMiddleware should never be applied a second time because # it would broke the current real request language if 'LocaleMiddleware' not in str(middleware_method.__class__): middleware_method(request) return request
[ "def", "get_request_mock", "(", ")", ":", "basehandler", "=", "BaseHandler", "(", ")", "basehandler", ".", "load_middleware", "(", ")", "# http://www.python.org/dev/peps/pep-0333/", "request", "=", "WSGIRequest", "(", "{", "'HTTP_COOKIE'", ":", "''", ",", "'PATH_INFO'", ":", "'/'", ",", "'QUERY_STRING'", ":", "''", ",", "'REMOTE_ADDR'", ":", "'127.0.0.1'", ",", "'REQUEST_METHOD'", ":", "'GET'", ",", "'SERVER_NAME'", ":", "'page-request-mock'", ",", "'SCRIPT_NAME'", ":", "''", ",", "'SERVER_PORT'", ":", "'80'", ",", "'SERVER_PROTOCOL'", ":", "'HTTP/1.1'", ",", "'HTTP_HOST'", ":", "'page-request-host'", ",", "'CONTENT_TYPE'", ":", "'text/html; charset=utf-8'", ",", "'wsgi.version'", ":", "(", "1", ",", "0", ")", ",", "'wsgi.url_scheme'", ":", "'http'", ",", "'wsgi.multiprocess'", ":", "True", ",", "'wsgi.multithread'", ":", "False", ",", "'wsgi.run_once'", ":", "False", ",", "'wsgi.input'", ":", "StringIO", "(", ")", "}", ")", "# Apply request middleware", "for", "middleware_method", "in", "basehandler", ".", "_request_middleware", ":", "# LocaleMiddleware should never be applied a second time because", "# it would broke the current real request language", "if", "'LocaleMiddleware'", "not", "in", "str", "(", "middleware_method", ".", "__class__", ")", ":", "middleware_method", "(", "request", ")", "return", "request" ]
Build a ``request`` mock up that is used in to render the templates in the most fidel environement as possible. This fonction is used in the get_placeholders method to render the input template and search for the placeholder within.
[ "Build", "a", "request", "mock", "up", "that", "is", "used", "in", "to", "render", "the", "templates", "in", "the", "most", "fidel", "environement", "as", "possible", "." ]
863f3c6098606f663994930cd8e7723ad0c07caf
https://github.com/ArabellaTech/django-basic-cms/blob/863f3c6098606f663994930cd8e7723ad0c07caf/basic_cms/http.py#L14-L51
train
ArabellaTech/django-basic-cms
basic_cms/http.py
pages_view
def pages_view(view): """ Make sure the decorated view gets the essential pages variables. """ def pages_view_decorator(request, *args, **kwargs): # if the current page is already there if(kwargs.get('current_page', False) or kwargs.get('pages_navigation', False)): return view(request, *args, **kwargs) path = kwargs.pop('path', None) lang = kwargs.pop('lang', None) if path: from basic_cms.views import details response = details(request, path=path, lang=lang, only_context=True, delegation=False) context = response extra_context_var = kwargs.pop('extra_context_var', None) if extra_context_var: kwargs.update({extra_context_var: context}) else: kwargs.update(context) return view(request, *args, **kwargs) return pages_view_decorator
python
def pages_view(view): """ Make sure the decorated view gets the essential pages variables. """ def pages_view_decorator(request, *args, **kwargs): # if the current page is already there if(kwargs.get('current_page', False) or kwargs.get('pages_navigation', False)): return view(request, *args, **kwargs) path = kwargs.pop('path', None) lang = kwargs.pop('lang', None) if path: from basic_cms.views import details response = details(request, path=path, lang=lang, only_context=True, delegation=False) context = response extra_context_var = kwargs.pop('extra_context_var', None) if extra_context_var: kwargs.update({extra_context_var: context}) else: kwargs.update(context) return view(request, *args, **kwargs) return pages_view_decorator
[ "def", "pages_view", "(", "view", ")", ":", "def", "pages_view_decorator", "(", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# if the current page is already there", "if", "(", "kwargs", ".", "get", "(", "'current_page'", ",", "False", ")", "or", "kwargs", ".", "get", "(", "'pages_navigation'", ",", "False", ")", ")", ":", "return", "view", "(", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", "path", "=", "kwargs", ".", "pop", "(", "'path'", ",", "None", ")", "lang", "=", "kwargs", ".", "pop", "(", "'lang'", ",", "None", ")", "if", "path", ":", "from", "basic_cms", ".", "views", "import", "details", "response", "=", "details", "(", "request", ",", "path", "=", "path", ",", "lang", "=", "lang", ",", "only_context", "=", "True", ",", "delegation", "=", "False", ")", "context", "=", "response", "extra_context_var", "=", "kwargs", ".", "pop", "(", "'extra_context_var'", ",", "None", ")", "if", "extra_context_var", ":", "kwargs", ".", "update", "(", "{", "extra_context_var", ":", "context", "}", ")", "else", ":", "kwargs", ".", "update", "(", "context", ")", "return", "view", "(", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", "return", "pages_view_decorator" ]
Make sure the decorated view gets the essential pages variables.
[ "Make", "sure", "the", "decorated", "view", "gets", "the", "essential", "pages", "variables", "." ]
863f3c6098606f663994930cd8e7723ad0c07caf
https://github.com/ArabellaTech/django-basic-cms/blob/863f3c6098606f663994930cd8e7723ad0c07caf/basic_cms/http.py#L54-L78
train
sirfoga/pyhal
hal/data/matrix.py
Matrix.true_neg_rate
def true_neg_rate(self): """Calculates true negative rate :return: true negative rate """ false_pos = self.matrix[1][0] true_neg = self.matrix[1][1] return divide(1.0 * true_neg, true_neg + false_pos)
python
def true_neg_rate(self): """Calculates true negative rate :return: true negative rate """ false_pos = self.matrix[1][0] true_neg = self.matrix[1][1] return divide(1.0 * true_neg, true_neg + false_pos)
[ "def", "true_neg_rate", "(", "self", ")", ":", "false_pos", "=", "self", ".", "matrix", "[", "1", "]", "[", "0", "]", "true_neg", "=", "self", ".", "matrix", "[", "1", "]", "[", "1", "]", "return", "divide", "(", "1.0", "*", "true_neg", ",", "true_neg", "+", "false_pos", ")" ]
Calculates true negative rate :return: true negative rate
[ "Calculates", "true", "negative", "rate" ]
4394d8a1f7e45bea28a255ec390f4962ee64d33a
https://github.com/sirfoga/pyhal/blob/4394d8a1f7e45bea28a255ec390f4962ee64d33a/hal/data/matrix.py#L35-L42
train
sirfoga/pyhal
hal/data/matrix.py
Matrix.f1_score
def f1_score(self): """Calculates F1 score :return: F1 score """ m_pre = self.precision() rec = self.recall() return divide(2.0, 1.0 / m_pre + 1.0 / rec)
python
def f1_score(self): """Calculates F1 score :return: F1 score """ m_pre = self.precision() rec = self.recall() return divide(2.0, 1.0 / m_pre + 1.0 / rec)
[ "def", "f1_score", "(", "self", ")", ":", "m_pre", "=", "self", ".", "precision", "(", ")", "rec", "=", "self", ".", "recall", "(", ")", "return", "divide", "(", "2.0", ",", "1.0", "/", "m_pre", "+", "1.0", "/", "rec", ")" ]
Calculates F1 score :return: F1 score
[ "Calculates", "F1", "score" ]
4394d8a1f7e45bea28a255ec390f4962ee64d33a
https://github.com/sirfoga/pyhal/blob/4394d8a1f7e45bea28a255ec390f4962ee64d33a/hal/data/matrix.py#L59-L66
train
sirfoga/pyhal
hal/data/matrix.py
Matrix.from_columns
def from_columns(columns): """Parses raw columns :param columns: matrix divided into columns :return: Matrix: Merge the columns to form a matrix """ data = [ [ column[i] for i in range(len(column)) ] for column in columns ] return Matrix(data)
python
def from_columns(columns): """Parses raw columns :param columns: matrix divided into columns :return: Matrix: Merge the columns to form a matrix """ data = [ [ column[i] for i in range(len(column)) ] for column in columns ] return Matrix(data)
[ "def", "from_columns", "(", "columns", ")", ":", "data", "=", "[", "[", "column", "[", "i", "]", "for", "i", "in", "range", "(", "len", "(", "column", ")", ")", "]", "for", "column", "in", "columns", "]", "return", "Matrix", "(", "data", ")" ]
Parses raw columns :param columns: matrix divided into columns :return: Matrix: Merge the columns to form a matrix
[ "Parses", "raw", "columns" ]
4394d8a1f7e45bea28a255ec390f4962ee64d33a
https://github.com/sirfoga/pyhal/blob/4394d8a1f7e45bea28a255ec390f4962ee64d33a/hal/data/matrix.py#L120-L133
train
sirfoga/pyhal
setup.py
get_version_details
def get_version_details(path): """Parses version file :param path: path to version file :return: version details """ with open(path, "r") as reader: lines = reader.readlines() data = { line.split(" = ")[0].replace("__", ""): line.split(" = ")[1].strip().replace("'", "") for line in lines } return data
python
def get_version_details(path): """Parses version file :param path: path to version file :return: version details """ with open(path, "r") as reader: lines = reader.readlines() data = { line.split(" = ")[0].replace("__", ""): line.split(" = ")[1].strip().replace("'", "") for line in lines } return data
[ "def", "get_version_details", "(", "path", ")", ":", "with", "open", "(", "path", ",", "\"r\"", ")", "as", "reader", ":", "lines", "=", "reader", ".", "readlines", "(", ")", "data", "=", "{", "line", ".", "split", "(", "\" = \"", ")", "[", "0", "]", ".", "replace", "(", "\"__\"", ",", "\"\"", ")", ":", "line", ".", "split", "(", "\" = \"", ")", "[", "1", "]", ".", "strip", "(", ")", ".", "replace", "(", "\"'\"", ",", "\"\"", ")", "for", "line", "in", "lines", "}", "return", "data" ]
Parses version file :param path: path to version file :return: version details
[ "Parses", "version", "file" ]
4394d8a1f7e45bea28a255ec390f4962ee64d33a
https://github.com/sirfoga/pyhal/blob/4394d8a1f7e45bea28a255ec390f4962ee64d33a/setup.py#L10-L24
train
rafaelmartins/dnsimple-dyndns
dnsimple_dyndns/dnsimple.py
DNSimple._get_record
def _get_record(self, name): """Returns the id of a record, if it exists.""" request = self._session.get(self._baseurl, params={'name': name, 'type': 'A'}) if not request.ok: raise RuntimeError('Failed to search record: %s - %s' % (self._format_hostname(name), request.json())) records = request.json() if len(records) == 0: return record = records[0] if 'record' not in record or 'id' not in record['record']: raise RuntimeError('Invalid record JSON format: %s - %s' % (self._format_hostname(name), request.json())) return int(record['record']['id'])
python
def _get_record(self, name): """Returns the id of a record, if it exists.""" request = self._session.get(self._baseurl, params={'name': name, 'type': 'A'}) if not request.ok: raise RuntimeError('Failed to search record: %s - %s' % (self._format_hostname(name), request.json())) records = request.json() if len(records) == 0: return record = records[0] if 'record' not in record or 'id' not in record['record']: raise RuntimeError('Invalid record JSON format: %s - %s' % (self._format_hostname(name), request.json())) return int(record['record']['id'])
[ "def", "_get_record", "(", "self", ",", "name", ")", ":", "request", "=", "self", ".", "_session", ".", "get", "(", "self", ".", "_baseurl", ",", "params", "=", "{", "'name'", ":", "name", ",", "'type'", ":", "'A'", "}", ")", "if", "not", "request", ".", "ok", ":", "raise", "RuntimeError", "(", "'Failed to search record: %s - %s'", "%", "(", "self", ".", "_format_hostname", "(", "name", ")", ",", "request", ".", "json", "(", ")", ")", ")", "records", "=", "request", ".", "json", "(", ")", "if", "len", "(", "records", ")", "==", "0", ":", "return", "record", "=", "records", "[", "0", "]", "if", "'record'", "not", "in", "record", "or", "'id'", "not", "in", "record", "[", "'record'", "]", ":", "raise", "RuntimeError", "(", "'Invalid record JSON format: %s - %s'", "%", "(", "self", ".", "_format_hostname", "(", "name", ")", ",", "request", ".", "json", "(", ")", ")", ")", "return", "int", "(", "record", "[", "'record'", "]", "[", "'id'", "]", ")" ]
Returns the id of a record, if it exists.
[ "Returns", "the", "id", "of", "a", "record", "if", "it", "exists", "." ]
36d9ec7508673b5354d324cf7c59128440d5bfd1
https://github.com/rafaelmartins/dnsimple-dyndns/blob/36d9ec7508673b5354d324cf7c59128440d5bfd1/dnsimple_dyndns/dnsimple.py#L29-L43
train
rafaelmartins/dnsimple-dyndns
dnsimple_dyndns/dnsimple.py
DNSimple._create_record
def _create_record(self, name, address, ttl): """Creates a new record.""" data = json.dumps({'record': {'name': name, 'record_type': 'A', 'content': address, 'ttl': ttl}}) headers = {'Content-Type': 'application/json'} request = self._session.post(self._baseurl, data=data, headers=headers) if not request.ok: raise RuntimeError('Failed to create new record: %s - %s' % (self._format_hostname(name), request.json())) record = request.json() if 'record' not in record or 'id' not in record['record']: raise RuntimeError('Invalid record JSON format: %s - %s' % (self._format_hostname(name), request.json())) return record['record']
python
def _create_record(self, name, address, ttl): """Creates a new record.""" data = json.dumps({'record': {'name': name, 'record_type': 'A', 'content': address, 'ttl': ttl}}) headers = {'Content-Type': 'application/json'} request = self._session.post(self._baseurl, data=data, headers=headers) if not request.ok: raise RuntimeError('Failed to create new record: %s - %s' % (self._format_hostname(name), request.json())) record = request.json() if 'record' not in record or 'id' not in record['record']: raise RuntimeError('Invalid record JSON format: %s - %s' % (self._format_hostname(name), request.json())) return record['record']
[ "def", "_create_record", "(", "self", ",", "name", ",", "address", ",", "ttl", ")", ":", "data", "=", "json", ".", "dumps", "(", "{", "'record'", ":", "{", "'name'", ":", "name", ",", "'record_type'", ":", "'A'", ",", "'content'", ":", "address", ",", "'ttl'", ":", "ttl", "}", "}", ")", "headers", "=", "{", "'Content-Type'", ":", "'application/json'", "}", "request", "=", "self", ".", "_session", ".", "post", "(", "self", ".", "_baseurl", ",", "data", "=", "data", ",", "headers", "=", "headers", ")", "if", "not", "request", ".", "ok", ":", "raise", "RuntimeError", "(", "'Failed to create new record: %s - %s'", "%", "(", "self", ".", "_format_hostname", "(", "name", ")", ",", "request", ".", "json", "(", ")", ")", ")", "record", "=", "request", ".", "json", "(", ")", "if", "'record'", "not", "in", "record", "or", "'id'", "not", "in", "record", "[", "'record'", "]", ":", "raise", "RuntimeError", "(", "'Invalid record JSON format: %s - %s'", "%", "(", "self", ".", "_format_hostname", "(", "name", ")", ",", "request", ".", "json", "(", ")", ")", ")", "return", "record", "[", "'record'", "]" ]
Creates a new record.
[ "Creates", "a", "new", "record", "." ]
36d9ec7508673b5354d324cf7c59128440d5bfd1
https://github.com/rafaelmartins/dnsimple-dyndns/blob/36d9ec7508673b5354d324cf7c59128440d5bfd1/dnsimple_dyndns/dnsimple.py#L45-L60
train
rafaelmartins/dnsimple-dyndns
dnsimple_dyndns/dnsimple.py
DNSimple._update_record
def _update_record(self, record_id, name, address, ttl): """Updates an existing record.""" data = json.dumps({'record': {'name': name, 'content': address, 'ttl': ttl}}) headers = {'Content-Type': 'application/json'} request = self._session.put(self._baseurl + '/%d' % record_id, data=data, headers=headers) if not request.ok: raise RuntimeError('Failed to update record: %s - %s' % (self._format_hostname(name), request.json())) record = request.json() if 'record' not in record or 'id' not in record['record']: raise RuntimeError('Invalid record JSON format: %s - %s' % (self._format_hostname(name), request.json())) return record['record']
python
def _update_record(self, record_id, name, address, ttl): """Updates an existing record.""" data = json.dumps({'record': {'name': name, 'content': address, 'ttl': ttl}}) headers = {'Content-Type': 'application/json'} request = self._session.put(self._baseurl + '/%d' % record_id, data=data, headers=headers) if not request.ok: raise RuntimeError('Failed to update record: %s - %s' % (self._format_hostname(name), request.json())) record = request.json() if 'record' not in record or 'id' not in record['record']: raise RuntimeError('Invalid record JSON format: %s - %s' % (self._format_hostname(name), request.json())) return record['record']
[ "def", "_update_record", "(", "self", ",", "record_id", ",", "name", ",", "address", ",", "ttl", ")", ":", "data", "=", "json", ".", "dumps", "(", "{", "'record'", ":", "{", "'name'", ":", "name", ",", "'content'", ":", "address", ",", "'ttl'", ":", "ttl", "}", "}", ")", "headers", "=", "{", "'Content-Type'", ":", "'application/json'", "}", "request", "=", "self", ".", "_session", ".", "put", "(", "self", ".", "_baseurl", "+", "'/%d'", "%", "record_id", ",", "data", "=", "data", ",", "headers", "=", "headers", ")", "if", "not", "request", ".", "ok", ":", "raise", "RuntimeError", "(", "'Failed to update record: %s - %s'", "%", "(", "self", ".", "_format_hostname", "(", "name", ")", ",", "request", ".", "json", "(", ")", ")", ")", "record", "=", "request", ".", "json", "(", ")", "if", "'record'", "not", "in", "record", "or", "'id'", "not", "in", "record", "[", "'record'", "]", ":", "raise", "RuntimeError", "(", "'Invalid record JSON format: %s - %s'", "%", "(", "self", ".", "_format_hostname", "(", "name", ")", ",", "request", ".", "json", "(", ")", ")", ")", "return", "record", "[", "'record'", "]" ]
Updates an existing record.
[ "Updates", "an", "existing", "record", "." ]
36d9ec7508673b5354d324cf7c59128440d5bfd1
https://github.com/rafaelmartins/dnsimple-dyndns/blob/36d9ec7508673b5354d324cf7c59128440d5bfd1/dnsimple_dyndns/dnsimple.py#L62-L77
train
rafaelmartins/dnsimple-dyndns
dnsimple_dyndns/dnsimple.py
DNSimple.update_record
def update_record(self, name, address, ttl=60): """Updates a record, creating it if not exists.""" record_id = self._get_record(name) if record_id is None: return self._create_record(name, address, ttl) return self._update_record(record_id, name, address, ttl)
python
def update_record(self, name, address, ttl=60): """Updates a record, creating it if not exists.""" record_id = self._get_record(name) if record_id is None: return self._create_record(name, address, ttl) return self._update_record(record_id, name, address, ttl)
[ "def", "update_record", "(", "self", ",", "name", ",", "address", ",", "ttl", "=", "60", ")", ":", "record_id", "=", "self", ".", "_get_record", "(", "name", ")", "if", "record_id", "is", "None", ":", "return", "self", ".", "_create_record", "(", "name", ",", "address", ",", "ttl", ")", "return", "self", ".", "_update_record", "(", "record_id", ",", "name", ",", "address", ",", "ttl", ")" ]
Updates a record, creating it if not exists.
[ "Updates", "a", "record", "creating", "it", "if", "not", "exists", "." ]
36d9ec7508673b5354d324cf7c59128440d5bfd1
https://github.com/rafaelmartins/dnsimple-dyndns/blob/36d9ec7508673b5354d324cf7c59128440d5bfd1/dnsimple_dyndns/dnsimple.py#L79-L84
train
portfors-lab/sparkle
sparkle/gui/plotting/viewbox.py
SpikeyViewBox.wheelEvent
def wheelEvent(self, ev, axis=None): """Reacts to mouse wheel movement, custom behaviour switches zoom axis when ctrl is pressed, and sets the locus of zoom, if zeroWheel is set.""" state = None # ctrl reverses mouse operation axis if ev.modifiers() == QtCore.Qt.ControlModifier: state = self.mouseEnabled() self.setMouseEnabled(not state[0], not state[1]) if self._zeroWheel: ev.pos = lambda : self.mapViewToScene(QtCore.QPoint(0,0)) super(SpikeyViewBox, self).wheelEvent(ev, axis) if state is not None: self.setMouseEnabled(*state)
python
def wheelEvent(self, ev, axis=None): """Reacts to mouse wheel movement, custom behaviour switches zoom axis when ctrl is pressed, and sets the locus of zoom, if zeroWheel is set.""" state = None # ctrl reverses mouse operation axis if ev.modifiers() == QtCore.Qt.ControlModifier: state = self.mouseEnabled() self.setMouseEnabled(not state[0], not state[1]) if self._zeroWheel: ev.pos = lambda : self.mapViewToScene(QtCore.QPoint(0,0)) super(SpikeyViewBox, self).wheelEvent(ev, axis) if state is not None: self.setMouseEnabled(*state)
[ "def", "wheelEvent", "(", "self", ",", "ev", ",", "axis", "=", "None", ")", ":", "state", "=", "None", "# ctrl reverses mouse operation axis", "if", "ev", ".", "modifiers", "(", ")", "==", "QtCore", ".", "Qt", ".", "ControlModifier", ":", "state", "=", "self", ".", "mouseEnabled", "(", ")", "self", ".", "setMouseEnabled", "(", "not", "state", "[", "0", "]", ",", "not", "state", "[", "1", "]", ")", "if", "self", ".", "_zeroWheel", ":", "ev", ".", "pos", "=", "lambda", ":", "self", ".", "mapViewToScene", "(", "QtCore", ".", "QPoint", "(", "0", ",", "0", ")", ")", "super", "(", "SpikeyViewBox", ",", "self", ")", ".", "wheelEvent", "(", "ev", ",", "axis", ")", "if", "state", "is", "not", "None", ":", "self", ".", "setMouseEnabled", "(", "*", "state", ")" ]
Reacts to mouse wheel movement, custom behaviour switches zoom axis when ctrl is pressed, and sets the locus of zoom, if zeroWheel is set.
[ "Reacts", "to", "mouse", "wheel", "movement", "custom", "behaviour", "switches", "zoom", "axis", "when", "ctrl", "is", "pressed", "and", "sets", "the", "locus", "of", "zoom", "if", "zeroWheel", "is", "set", "." ]
5fad1cf2bec58ec6b15d91da20f6236a74826110
https://github.com/portfors-lab/sparkle/blob/5fad1cf2bec58ec6b15d91da20f6236a74826110/sparkle/gui/plotting/viewbox.py#L71-L84
train
portfors-lab/sparkle
sparkle/gui/plotting/viewbox.py
SpikeyViewBoxMenu.copy
def copy(self): """Adds menus to itself, required by ViewBox""" # copied from pyqtgraph ViewBoxMenu m = QtGui.QMenu() for sm in self.subMenus(): if isinstance(sm, QtGui.QMenu): m.addMenu(sm) else: m.addAction(sm) m.setTitle(self.title()) return m
python
def copy(self): """Adds menus to itself, required by ViewBox""" # copied from pyqtgraph ViewBoxMenu m = QtGui.QMenu() for sm in self.subMenus(): if isinstance(sm, QtGui.QMenu): m.addMenu(sm) else: m.addAction(sm) m.setTitle(self.title()) return m
[ "def", "copy", "(", "self", ")", ":", "# copied from pyqtgraph ViewBoxMenu", "m", "=", "QtGui", ".", "QMenu", "(", ")", "for", "sm", "in", "self", ".", "subMenus", "(", ")", ":", "if", "isinstance", "(", "sm", ",", "QtGui", ".", "QMenu", ")", ":", "m", ".", "addMenu", "(", "sm", ")", "else", ":", "m", ".", "addAction", "(", "sm", ")", "m", ".", "setTitle", "(", "self", ".", "title", "(", ")", ")", "return", "m" ]
Adds menus to itself, required by ViewBox
[ "Adds", "menus", "to", "itself", "required", "by", "ViewBox" ]
5fad1cf2bec58ec6b15d91da20f6236a74826110
https://github.com/portfors-lab/sparkle/blob/5fad1cf2bec58ec6b15d91da20f6236a74826110/sparkle/gui/plotting/viewbox.py#L101-L111
train
sirfoga/pyhal
hal/ml/features.py
FeatureSelect.select_k_best
def select_k_best(self, k): """Selects k best features in dataset :param k: features to select :return: k best features """ x_new = SelectKBest(chi2, k=k).fit_transform(self.x_train, self.y_train) return x_new
python
def select_k_best(self, k): """Selects k best features in dataset :param k: features to select :return: k best features """ x_new = SelectKBest(chi2, k=k).fit_transform(self.x_train, self.y_train) return x_new
[ "def", "select_k_best", "(", "self", ",", "k", ")", ":", "x_new", "=", "SelectKBest", "(", "chi2", ",", "k", "=", "k", ")", ".", "fit_transform", "(", "self", ".", "x_train", ",", "self", ".", "y_train", ")", "return", "x_new" ]
Selects k best features in dataset :param k: features to select :return: k best features
[ "Selects", "k", "best", "features", "in", "dataset" ]
4394d8a1f7e45bea28a255ec390f4962ee64d33a
https://github.com/sirfoga/pyhal/blob/4394d8a1f7e45bea28a255ec390f4962ee64d33a/hal/ml/features.py#L24-L31
train
lowandrew/OLCTools
spadespipeline/depth.py
QualiMap.main
def main(self): """ Run the methods in the correct order """ logging.info('Aligning reads with bowtie2 for Qualimap') self.bowtie() self.indexing() self.pilon() self.filter() self.clear()
python
def main(self): """ Run the methods in the correct order """ logging.info('Aligning reads with bowtie2 for Qualimap') self.bowtie() self.indexing() self.pilon() self.filter() self.clear()
[ "def", "main", "(", "self", ")", ":", "logging", ".", "info", "(", "'Aligning reads with bowtie2 for Qualimap'", ")", "self", ".", "bowtie", "(", ")", "self", ".", "indexing", "(", ")", "self", ".", "pilon", "(", ")", "self", ".", "filter", "(", ")", "self", ".", "clear", "(", ")" ]
Run the methods in the correct order
[ "Run", "the", "methods", "in", "the", "correct", "order" ]
88aa90ac85f84d0bbeb03e43c29b0a9d36e4ce2a
https://github.com/lowandrew/OLCTools/blob/88aa90ac85f84d0bbeb03e43c29b0a9d36e4ce2a/spadespipeline/depth.py#L23-L32
train
lowandrew/OLCTools
spadespipeline/depth.py
QualiMap.bowtie
def bowtie(self): """ Create threads and commands for performing reference mapping for qualimap analyses """ for i in range(self.cpus): # Send the threads to the merge method. :args is empty as I'm using threads = Thread(target=self.align, args=()) # Set the daemon to true - something to do with thread management threads.setDaemon(True) # Start the threading threads.start() with progressbar(self.metadata) as bar: for sample in bar: # Initialise the mapping GenObject sample.mapping = GenObject() # Set an easier to write shortcut for sample.general sagen = sample.general if sagen.bestassemblyfile != "NA": sagen.QualimapResults = os.path.join(sagen.outputdirectory, 'qualimap_results') # Set the results folder # Create this results folder if necessary make_path(sagen.QualimapResults) # Set file names sagen.sortedbam = os.path.join(sagen.QualimapResults, '{}_sorted.bam'.format(sample.name)) filenoext = os.path.splitext(sagen.filteredfile)[0] sagen.filenoext = filenoext sagen.bowtie2results = os.path.join(sagen.QualimapResults, sample.name) # Use fancy new bowtie2 wrapper bowtie2build = Bowtie2BuildCommandLine(reference=sagen.bestassemblyfile, bt2=sagen.bowtie2results) sample.mapping.BamFile = sagen.bowtie2results + "_sorted.bam" # SAMtools sort v1.3 has different run parameters samsort = SamtoolsSortCommandline(input=sample.mapping.BamFile, o=True, out_prefix="-") samtools = [SamtoolsViewCommandline(b=True, S=True, input_file="-"), samsort] indict = {'D': 5, 'R': 1, 'num_mismatches': 0, 'seed_length': 22, 'i_func': "S,0,2.50"} # Update the dictionary with the appropriate parameters for paired- vs. single-ended assemblies try: _ = sample.general.mergedreads if len(sample.general.trimmedcorrectedfastqfiles) == 2: indict.update({'m1': sample.general.trimmedcorrectedfastqfiles[0], 'm2': sample.general.trimmedcorrectedfastqfiles[1]}) else: indict.update({'U': sample.general.trimmedcorrectedfastqfiles[0]}) except AttributeError: if len(sample.general.assemblyfastq) == 2: indict.update({'m1': sample.general.assemblyfastq[0], 'm2': sample.general.assemblyfastq[1]}) else: indict.update({'U': sample.general.assemblyfastq[0]}) bowtie2align = Bowtie2CommandLine(bt2=sagen.bowtie2results, threads=self.threads, samtools=samtools, **indict) # Convert the commands to strings to allow them to be JSON serialized sample.commands.bowtie2align = str(bowtie2align) sample.commands.bowtie2build = str(bowtie2build) self.bowqueue.put((sample, sample.commands.bowtie2build, sample.commands.bowtie2align)) else: sample.commands.samtools = "NA" sample.mapping.MeanInsertSize = 'NA' sample.mapping.MeanCoveragedata = 'NA' self.bowqueue.join()
python
def bowtie(self): """ Create threads and commands for performing reference mapping for qualimap analyses """ for i in range(self.cpus): # Send the threads to the merge method. :args is empty as I'm using threads = Thread(target=self.align, args=()) # Set the daemon to true - something to do with thread management threads.setDaemon(True) # Start the threading threads.start() with progressbar(self.metadata) as bar: for sample in bar: # Initialise the mapping GenObject sample.mapping = GenObject() # Set an easier to write shortcut for sample.general sagen = sample.general if sagen.bestassemblyfile != "NA": sagen.QualimapResults = os.path.join(sagen.outputdirectory, 'qualimap_results') # Set the results folder # Create this results folder if necessary make_path(sagen.QualimapResults) # Set file names sagen.sortedbam = os.path.join(sagen.QualimapResults, '{}_sorted.bam'.format(sample.name)) filenoext = os.path.splitext(sagen.filteredfile)[0] sagen.filenoext = filenoext sagen.bowtie2results = os.path.join(sagen.QualimapResults, sample.name) # Use fancy new bowtie2 wrapper bowtie2build = Bowtie2BuildCommandLine(reference=sagen.bestassemblyfile, bt2=sagen.bowtie2results) sample.mapping.BamFile = sagen.bowtie2results + "_sorted.bam" # SAMtools sort v1.3 has different run parameters samsort = SamtoolsSortCommandline(input=sample.mapping.BamFile, o=True, out_prefix="-") samtools = [SamtoolsViewCommandline(b=True, S=True, input_file="-"), samsort] indict = {'D': 5, 'R': 1, 'num_mismatches': 0, 'seed_length': 22, 'i_func': "S,0,2.50"} # Update the dictionary with the appropriate parameters for paired- vs. single-ended assemblies try: _ = sample.general.mergedreads if len(sample.general.trimmedcorrectedfastqfiles) == 2: indict.update({'m1': sample.general.trimmedcorrectedfastqfiles[0], 'm2': sample.general.trimmedcorrectedfastqfiles[1]}) else: indict.update({'U': sample.general.trimmedcorrectedfastqfiles[0]}) except AttributeError: if len(sample.general.assemblyfastq) == 2: indict.update({'m1': sample.general.assemblyfastq[0], 'm2': sample.general.assemblyfastq[1]}) else: indict.update({'U': sample.general.assemblyfastq[0]}) bowtie2align = Bowtie2CommandLine(bt2=sagen.bowtie2results, threads=self.threads, samtools=samtools, **indict) # Convert the commands to strings to allow them to be JSON serialized sample.commands.bowtie2align = str(bowtie2align) sample.commands.bowtie2build = str(bowtie2build) self.bowqueue.put((sample, sample.commands.bowtie2build, sample.commands.bowtie2align)) else: sample.commands.samtools = "NA" sample.mapping.MeanInsertSize = 'NA' sample.mapping.MeanCoveragedata = 'NA' self.bowqueue.join()
[ "def", "bowtie", "(", "self", ")", ":", "for", "i", "in", "range", "(", "self", ".", "cpus", ")", ":", "# Send the threads to the merge method. :args is empty as I'm using", "threads", "=", "Thread", "(", "target", "=", "self", ".", "align", ",", "args", "=", "(", ")", ")", "# Set the daemon to true - something to do with thread management", "threads", ".", "setDaemon", "(", "True", ")", "# Start the threading", "threads", ".", "start", "(", ")", "with", "progressbar", "(", "self", ".", "metadata", ")", "as", "bar", ":", "for", "sample", "in", "bar", ":", "# Initialise the mapping GenObject", "sample", ".", "mapping", "=", "GenObject", "(", ")", "# Set an easier to write shortcut for sample.general", "sagen", "=", "sample", ".", "general", "if", "sagen", ".", "bestassemblyfile", "!=", "\"NA\"", ":", "sagen", ".", "QualimapResults", "=", "os", ".", "path", ".", "join", "(", "sagen", ".", "outputdirectory", ",", "'qualimap_results'", ")", "# Set the results folder", "# Create this results folder if necessary", "make_path", "(", "sagen", ".", "QualimapResults", ")", "# Set file names", "sagen", ".", "sortedbam", "=", "os", ".", "path", ".", "join", "(", "sagen", ".", "QualimapResults", ",", "'{}_sorted.bam'", ".", "format", "(", "sample", ".", "name", ")", ")", "filenoext", "=", "os", ".", "path", ".", "splitext", "(", "sagen", ".", "filteredfile", ")", "[", "0", "]", "sagen", ".", "filenoext", "=", "filenoext", "sagen", ".", "bowtie2results", "=", "os", ".", "path", ".", "join", "(", "sagen", ".", "QualimapResults", ",", "sample", ".", "name", ")", "# Use fancy new bowtie2 wrapper", "bowtie2build", "=", "Bowtie2BuildCommandLine", "(", "reference", "=", "sagen", ".", "bestassemblyfile", ",", "bt2", "=", "sagen", ".", "bowtie2results", ")", "sample", ".", "mapping", ".", "BamFile", "=", "sagen", ".", "bowtie2results", "+", "\"_sorted.bam\"", "# SAMtools sort v1.3 has different run parameters", "samsort", "=", "SamtoolsSortCommandline", "(", "input", "=", "sample", ".", "mapping", ".", "BamFile", ",", "o", "=", "True", ",", "out_prefix", "=", "\"-\"", ")", "samtools", "=", "[", "SamtoolsViewCommandline", "(", "b", "=", "True", ",", "S", "=", "True", ",", "input_file", "=", "\"-\"", ")", ",", "samsort", "]", "indict", "=", "{", "'D'", ":", "5", ",", "'R'", ":", "1", ",", "'num_mismatches'", ":", "0", ",", "'seed_length'", ":", "22", ",", "'i_func'", ":", "\"S,0,2.50\"", "}", "# Update the dictionary with the appropriate parameters for paired- vs. single-ended assemblies", "try", ":", "_", "=", "sample", ".", "general", ".", "mergedreads", "if", "len", "(", "sample", ".", "general", ".", "trimmedcorrectedfastqfiles", ")", "==", "2", ":", "indict", ".", "update", "(", "{", "'m1'", ":", "sample", ".", "general", ".", "trimmedcorrectedfastqfiles", "[", "0", "]", ",", "'m2'", ":", "sample", ".", "general", ".", "trimmedcorrectedfastqfiles", "[", "1", "]", "}", ")", "else", ":", "indict", ".", "update", "(", "{", "'U'", ":", "sample", ".", "general", ".", "trimmedcorrectedfastqfiles", "[", "0", "]", "}", ")", "except", "AttributeError", ":", "if", "len", "(", "sample", ".", "general", ".", "assemblyfastq", ")", "==", "2", ":", "indict", ".", "update", "(", "{", "'m1'", ":", "sample", ".", "general", ".", "assemblyfastq", "[", "0", "]", ",", "'m2'", ":", "sample", ".", "general", ".", "assemblyfastq", "[", "1", "]", "}", ")", "else", ":", "indict", ".", "update", "(", "{", "'U'", ":", "sample", ".", "general", ".", "assemblyfastq", "[", "0", "]", "}", ")", "bowtie2align", "=", "Bowtie2CommandLine", "(", "bt2", "=", "sagen", ".", "bowtie2results", ",", "threads", "=", "self", ".", "threads", ",", "samtools", "=", "samtools", ",", "*", "*", "indict", ")", "# Convert the commands to strings to allow them to be JSON serialized", "sample", ".", "commands", ".", "bowtie2align", "=", "str", "(", "bowtie2align", ")", "sample", ".", "commands", ".", "bowtie2build", "=", "str", "(", "bowtie2build", ")", "self", ".", "bowqueue", ".", "put", "(", "(", "sample", ",", "sample", ".", "commands", ".", "bowtie2build", ",", "sample", ".", "commands", ".", "bowtie2align", ")", ")", "else", ":", "sample", ".", "commands", ".", "samtools", "=", "\"NA\"", "sample", ".", "mapping", ".", "MeanInsertSize", "=", "'NA'", "sample", ".", "mapping", ".", "MeanCoveragedata", "=", "'NA'", "self", ".", "bowqueue", ".", "join", "(", ")" ]
Create threads and commands for performing reference mapping for qualimap analyses
[ "Create", "threads", "and", "commands", "for", "performing", "reference", "mapping", "for", "qualimap", "analyses" ]
88aa90ac85f84d0bbeb03e43c29b0a9d36e4ce2a
https://github.com/lowandrew/OLCTools/blob/88aa90ac85f84d0bbeb03e43c29b0a9d36e4ce2a/spadespipeline/depth.py#L34-L98
train
lowandrew/OLCTools
spadespipeline/depth.py
QualiMap.pilon
def pilon(self): """ Run pilon to fix any misassemblies in the contigs - will look for SNPs and indels """ logging.info('Improving quality of assembly with pilon') for i in range(self.cpus): # Send the threads to the merge method. :args is empty as I'm using threads = Thread(target=self.pilonthreads, args=()) # Set the daemon to true - something to do with thread management threads.setDaemon(True) # Start the threading threads.start() with progressbar(self.metadata) as bar: for sample in bar: if sample.general.bestassemblyfile != 'NA': if sample.general.polish: # Set the name of the unfiltered assembly output file sample.general.contigsfile = sample.general.assemblyfile sample.mapping.pilondir = os.path.join(sample.general.QualimapResults, 'pilon') make_path(sample.mapping.pilondir) # Create the command line command sample.mapping.piloncmd = 'pilon --genome {} --bam {} --fix bases --threads {} ' \ '--outdir {} --changes --mindepth 0.25' \ .format(sample.general.contigsfile, sample.mapping.BamFile, self.threads, sample.mapping.pilondir) self.pilonqueue.put(sample) else: sample.general.contigsfile = sample.general.assemblyfile self.pilonqueue.join()
python
def pilon(self): """ Run pilon to fix any misassemblies in the contigs - will look for SNPs and indels """ logging.info('Improving quality of assembly with pilon') for i in range(self.cpus): # Send the threads to the merge method. :args is empty as I'm using threads = Thread(target=self.pilonthreads, args=()) # Set the daemon to true - something to do with thread management threads.setDaemon(True) # Start the threading threads.start() with progressbar(self.metadata) as bar: for sample in bar: if sample.general.bestassemblyfile != 'NA': if sample.general.polish: # Set the name of the unfiltered assembly output file sample.general.contigsfile = sample.general.assemblyfile sample.mapping.pilondir = os.path.join(sample.general.QualimapResults, 'pilon') make_path(sample.mapping.pilondir) # Create the command line command sample.mapping.piloncmd = 'pilon --genome {} --bam {} --fix bases --threads {} ' \ '--outdir {} --changes --mindepth 0.25' \ .format(sample.general.contigsfile, sample.mapping.BamFile, self.threads, sample.mapping.pilondir) self.pilonqueue.put(sample) else: sample.general.contigsfile = sample.general.assemblyfile self.pilonqueue.join()
[ "def", "pilon", "(", "self", ")", ":", "logging", ".", "info", "(", "'Improving quality of assembly with pilon'", ")", "for", "i", "in", "range", "(", "self", ".", "cpus", ")", ":", "# Send the threads to the merge method. :args is empty as I'm using", "threads", "=", "Thread", "(", "target", "=", "self", ".", "pilonthreads", ",", "args", "=", "(", ")", ")", "# Set the daemon to true - something to do with thread management", "threads", ".", "setDaemon", "(", "True", ")", "# Start the threading", "threads", ".", "start", "(", ")", "with", "progressbar", "(", "self", ".", "metadata", ")", "as", "bar", ":", "for", "sample", "in", "bar", ":", "if", "sample", ".", "general", ".", "bestassemblyfile", "!=", "'NA'", ":", "if", "sample", ".", "general", ".", "polish", ":", "# Set the name of the unfiltered assembly output file", "sample", ".", "general", ".", "contigsfile", "=", "sample", ".", "general", ".", "assemblyfile", "sample", ".", "mapping", ".", "pilondir", "=", "os", ".", "path", ".", "join", "(", "sample", ".", "general", ".", "QualimapResults", ",", "'pilon'", ")", "make_path", "(", "sample", ".", "mapping", ".", "pilondir", ")", "# Create the command line command", "sample", ".", "mapping", ".", "piloncmd", "=", "'pilon --genome {} --bam {} --fix bases --threads {} '", "'--outdir {} --changes --mindepth 0.25'", ".", "format", "(", "sample", ".", "general", ".", "contigsfile", ",", "sample", ".", "mapping", ".", "BamFile", ",", "self", ".", "threads", ",", "sample", ".", "mapping", ".", "pilondir", ")", "self", ".", "pilonqueue", ".", "put", "(", "sample", ")", "else", ":", "sample", ".", "general", ".", "contigsfile", "=", "sample", ".", "general", ".", "assemblyfile", "self", ".", "pilonqueue", ".", "join", "(", ")" ]
Run pilon to fix any misassemblies in the contigs - will look for SNPs and indels
[ "Run", "pilon", "to", "fix", "any", "misassemblies", "in", "the", "contigs", "-", "will", "look", "for", "SNPs", "and", "indels" ]
88aa90ac85f84d0bbeb03e43c29b0a9d36e4ce2a
https://github.com/lowandrew/OLCTools/blob/88aa90ac85f84d0bbeb03e43c29b0a9d36e4ce2a/spadespipeline/depth.py#L233-L263
train
lowandrew/OLCTools
spadespipeline/depth.py
QualiMap.filter
def filter(self): """ Filter contigs based on depth """ logging.info('Filtering contigs') for i in range(self.cpus): # Send the threads to the filter method threads = Thread(target=self.filterthreads, args=()) # Set the daemon to true - something to do with thread management threads.setDaemon(True) # Start the threading threads.start() with progressbar(self.metadata) as bar: for sample in bar: # Set the name of the unfiltered assembly output file if sample.general.bestassemblyfile != 'NA': sample.general.contigsfile = sample.general.assemblyfile self.filterqueue.put(sample) self.filterqueue.join()
python
def filter(self): """ Filter contigs based on depth """ logging.info('Filtering contigs') for i in range(self.cpus): # Send the threads to the filter method threads = Thread(target=self.filterthreads, args=()) # Set the daemon to true - something to do with thread management threads.setDaemon(True) # Start the threading threads.start() with progressbar(self.metadata) as bar: for sample in bar: # Set the name of the unfiltered assembly output file if sample.general.bestassemblyfile != 'NA': sample.general.contigsfile = sample.general.assemblyfile self.filterqueue.put(sample) self.filterqueue.join()
[ "def", "filter", "(", "self", ")", ":", "logging", ".", "info", "(", "'Filtering contigs'", ")", "for", "i", "in", "range", "(", "self", ".", "cpus", ")", ":", "# Send the threads to the filter method", "threads", "=", "Thread", "(", "target", "=", "self", ".", "filterthreads", ",", "args", "=", "(", ")", ")", "# Set the daemon to true - something to do with thread management", "threads", ".", "setDaemon", "(", "True", ")", "# Start the threading", "threads", ".", "start", "(", ")", "with", "progressbar", "(", "self", ".", "metadata", ")", "as", "bar", ":", "for", "sample", "in", "bar", ":", "# Set the name of the unfiltered assembly output file", "if", "sample", ".", "general", ".", "bestassemblyfile", "!=", "'NA'", ":", "sample", ".", "general", ".", "contigsfile", "=", "sample", ".", "general", ".", "assemblyfile", "self", ".", "filterqueue", ".", "put", "(", "sample", ")", "self", ".", "filterqueue", ".", "join", "(", ")" ]
Filter contigs based on depth
[ "Filter", "contigs", "based", "on", "depth" ]
88aa90ac85f84d0bbeb03e43c29b0a9d36e4ce2a
https://github.com/lowandrew/OLCTools/blob/88aa90ac85f84d0bbeb03e43c29b0a9d36e4ce2a/spadespipeline/depth.py#L280-L299
train
lowandrew/OLCTools
spadespipeline/depth.py
QualiMap.clear
def clear(self): """ Clear out large attributes from the metadata objects """ for sample in self.metadata: try: delattr(sample.depth, 'bases') delattr(sample.depth, 'coverage') delattr(sample.depth, 'length') delattr(sample.depth, 'stddev') except AttributeError: pass
python
def clear(self): """ Clear out large attributes from the metadata objects """ for sample in self.metadata: try: delattr(sample.depth, 'bases') delattr(sample.depth, 'coverage') delattr(sample.depth, 'length') delattr(sample.depth, 'stddev') except AttributeError: pass
[ "def", "clear", "(", "self", ")", ":", "for", "sample", "in", "self", ".", "metadata", ":", "try", ":", "delattr", "(", "sample", ".", "depth", ",", "'bases'", ")", "delattr", "(", "sample", ".", "depth", ",", "'coverage'", ")", "delattr", "(", "sample", ".", "depth", ",", "'length'", ")", "delattr", "(", "sample", ".", "depth", ",", "'stddev'", ")", "except", "AttributeError", ":", "pass" ]
Clear out large attributes from the metadata objects
[ "Clear", "out", "large", "attributes", "from", "the", "metadata", "objects" ]
88aa90ac85f84d0bbeb03e43c29b0a9d36e4ce2a
https://github.com/lowandrew/OLCTools/blob/88aa90ac85f84d0bbeb03e43c29b0a9d36e4ce2a/spadespipeline/depth.py#L350-L361
train
ArabellaTech/django-basic-cms
basic_cms/utils.py
pages_to_json
def pages_to_json(queryset): """ Return a JSON string export of the pages in queryset. """ # selection may be in the wrong order, and order matters queryset = queryset.order_by('tree_id', 'lft') return simplejson.dumps( {JSON_PAGE_EXPORT_NAME: JSON_PAGE_EXPORT_VERSION, 'pages': [page.dump_json_data() for page in queryset]}, indent=JSON_PAGE_EXPORT_INDENT, sort_keys=True)
python
def pages_to_json(queryset): """ Return a JSON string export of the pages in queryset. """ # selection may be in the wrong order, and order matters queryset = queryset.order_by('tree_id', 'lft') return simplejson.dumps( {JSON_PAGE_EXPORT_NAME: JSON_PAGE_EXPORT_VERSION, 'pages': [page.dump_json_data() for page in queryset]}, indent=JSON_PAGE_EXPORT_INDENT, sort_keys=True)
[ "def", "pages_to_json", "(", "queryset", ")", ":", "# selection may be in the wrong order, and order matters", "queryset", "=", "queryset", ".", "order_by", "(", "'tree_id'", ",", "'lft'", ")", "return", "simplejson", ".", "dumps", "(", "{", "JSON_PAGE_EXPORT_NAME", ":", "JSON_PAGE_EXPORT_VERSION", ",", "'pages'", ":", "[", "page", ".", "dump_json_data", "(", ")", "for", "page", "in", "queryset", "]", "}", ",", "indent", "=", "JSON_PAGE_EXPORT_INDENT", ",", "sort_keys", "=", "True", ")" ]
Return a JSON string export of the pages in queryset.
[ "Return", "a", "JSON", "string", "export", "of", "the", "pages", "in", "queryset", "." ]
863f3c6098606f663994930cd8e7723ad0c07caf
https://github.com/ArabellaTech/django-basic-cms/blob/863f3c6098606f663994930cd8e7723ad0c07caf/basic_cms/utils.py#L37-L46
train
ArabellaTech/django-basic-cms
basic_cms/utils.py
validate_pages_json_data
def validate_pages_json_data(d, preferred_lang): """ Check if an import of d will succeed, and return errors. errors is a list of strings. The import should proceed only if errors is empty. """ from .models import Page errors = [] seen_complete_slugs = dict( (lang[0], set()) for lang in settings.PAGE_LANGUAGES) valid_templates = set(t[0] for t in settings.get_page_templates()) valid_templates.add(settings.PAGE_DEFAULT_TEMPLATE) if d[JSON_PAGE_EXPORT_NAME] != JSON_PAGE_EXPORT_VERSION: return [_('Unsupported file version: %s') % repr( d[JSON_PAGE_EXPORT_NAME])], [] pages = d['pages'] for p in pages: # use the complete slug as a way to identify pages in errors slug = p['complete_slug'].get(preferred_lang, None) seen_parent = False for lang, s in p['complete_slug'].items(): if lang not in seen_complete_slugs: continue seen_complete_slugs[lang].add(s) if '/' not in s: # root level, no parent req'd seen_parent = True if not seen_parent: parent_slug, ignore = s.rsplit('/', 1) if parent_slug in seen_complete_slugs[lang]: seen_parent = True else: parent = Page.objects.from_path(parent_slug, lang, exclude_drafts=False) if parent and parent.get_complete_slug(lang) == parent_slug: # parent not included, but exists on site seen_parent = True if not slug: slug = s if not slug: errors.append(_("%s has no common language with this site") % (p['complete_slug'].values()[0],)) continue if not seen_parent: errors.append(_("%s did not include its parent page and a matching" " one was not found on this site") % (slug,)) if p['template'] not in valid_templates: errors.append(_("%s uses a template not found on this site: %s") % (slug, p['template'])) continue import_fields = set(p['content'].keys()) import_fields |= set(('meta_title', 'meta_description', 'meta_keywords', 'meta_author', 'fb_page_type', 'fb_image')) template_fields = set(p.name for p in get_placeholders(p['template']) if p.name not in ('title', 'slug')) template_fields |= set(('meta_title', 'meta_description', 'meta_keywords', 'meta_author', 'fb_page_type', 'fb_image')) if template_fields != import_fields: errors.append(_("%s template contents are different than our " "template: %s") % (slug, p['template'])) continue return errors
python
def validate_pages_json_data(d, preferred_lang): """ Check if an import of d will succeed, and return errors. errors is a list of strings. The import should proceed only if errors is empty. """ from .models import Page errors = [] seen_complete_slugs = dict( (lang[0], set()) for lang in settings.PAGE_LANGUAGES) valid_templates = set(t[0] for t in settings.get_page_templates()) valid_templates.add(settings.PAGE_DEFAULT_TEMPLATE) if d[JSON_PAGE_EXPORT_NAME] != JSON_PAGE_EXPORT_VERSION: return [_('Unsupported file version: %s') % repr( d[JSON_PAGE_EXPORT_NAME])], [] pages = d['pages'] for p in pages: # use the complete slug as a way to identify pages in errors slug = p['complete_slug'].get(preferred_lang, None) seen_parent = False for lang, s in p['complete_slug'].items(): if lang not in seen_complete_slugs: continue seen_complete_slugs[lang].add(s) if '/' not in s: # root level, no parent req'd seen_parent = True if not seen_parent: parent_slug, ignore = s.rsplit('/', 1) if parent_slug in seen_complete_slugs[lang]: seen_parent = True else: parent = Page.objects.from_path(parent_slug, lang, exclude_drafts=False) if parent and parent.get_complete_slug(lang) == parent_slug: # parent not included, but exists on site seen_parent = True if not slug: slug = s if not slug: errors.append(_("%s has no common language with this site") % (p['complete_slug'].values()[0],)) continue if not seen_parent: errors.append(_("%s did not include its parent page and a matching" " one was not found on this site") % (slug,)) if p['template'] not in valid_templates: errors.append(_("%s uses a template not found on this site: %s") % (slug, p['template'])) continue import_fields = set(p['content'].keys()) import_fields |= set(('meta_title', 'meta_description', 'meta_keywords', 'meta_author', 'fb_page_type', 'fb_image')) template_fields = set(p.name for p in get_placeholders(p['template']) if p.name not in ('title', 'slug')) template_fields |= set(('meta_title', 'meta_description', 'meta_keywords', 'meta_author', 'fb_page_type', 'fb_image')) if template_fields != import_fields: errors.append(_("%s template contents are different than our " "template: %s") % (slug, p['template'])) continue return errors
[ "def", "validate_pages_json_data", "(", "d", ",", "preferred_lang", ")", ":", "from", ".", "models", "import", "Page", "errors", "=", "[", "]", "seen_complete_slugs", "=", "dict", "(", "(", "lang", "[", "0", "]", ",", "set", "(", ")", ")", "for", "lang", "in", "settings", ".", "PAGE_LANGUAGES", ")", "valid_templates", "=", "set", "(", "t", "[", "0", "]", "for", "t", "in", "settings", ".", "get_page_templates", "(", ")", ")", "valid_templates", ".", "add", "(", "settings", ".", "PAGE_DEFAULT_TEMPLATE", ")", "if", "d", "[", "JSON_PAGE_EXPORT_NAME", "]", "!=", "JSON_PAGE_EXPORT_VERSION", ":", "return", "[", "_", "(", "'Unsupported file version: %s'", ")", "%", "repr", "(", "d", "[", "JSON_PAGE_EXPORT_NAME", "]", ")", "]", ",", "[", "]", "pages", "=", "d", "[", "'pages'", "]", "for", "p", "in", "pages", ":", "# use the complete slug as a way to identify pages in errors", "slug", "=", "p", "[", "'complete_slug'", "]", ".", "get", "(", "preferred_lang", ",", "None", ")", "seen_parent", "=", "False", "for", "lang", ",", "s", "in", "p", "[", "'complete_slug'", "]", ".", "items", "(", ")", ":", "if", "lang", "not", "in", "seen_complete_slugs", ":", "continue", "seen_complete_slugs", "[", "lang", "]", ".", "add", "(", "s", ")", "if", "'/'", "not", "in", "s", ":", "# root level, no parent req'd", "seen_parent", "=", "True", "if", "not", "seen_parent", ":", "parent_slug", ",", "ignore", "=", "s", ".", "rsplit", "(", "'/'", ",", "1", ")", "if", "parent_slug", "in", "seen_complete_slugs", "[", "lang", "]", ":", "seen_parent", "=", "True", "else", ":", "parent", "=", "Page", ".", "objects", ".", "from_path", "(", "parent_slug", ",", "lang", ",", "exclude_drafts", "=", "False", ")", "if", "parent", "and", "parent", ".", "get_complete_slug", "(", "lang", ")", "==", "parent_slug", ":", "# parent not included, but exists on site", "seen_parent", "=", "True", "if", "not", "slug", ":", "slug", "=", "s", "if", "not", "slug", ":", "errors", ".", "append", "(", "_", "(", "\"%s has no common language with this site\"", ")", "%", "(", "p", "[", "'complete_slug'", "]", ".", "values", "(", ")", "[", "0", "]", ",", ")", ")", "continue", "if", "not", "seen_parent", ":", "errors", ".", "append", "(", "_", "(", "\"%s did not include its parent page and a matching\"", "\" one was not found on this site\"", ")", "%", "(", "slug", ",", ")", ")", "if", "p", "[", "'template'", "]", "not", "in", "valid_templates", ":", "errors", ".", "append", "(", "_", "(", "\"%s uses a template not found on this site: %s\"", ")", "%", "(", "slug", ",", "p", "[", "'template'", "]", ")", ")", "continue", "import_fields", "=", "set", "(", "p", "[", "'content'", "]", ".", "keys", "(", ")", ")", "import_fields", "|=", "set", "(", "(", "'meta_title'", ",", "'meta_description'", ",", "'meta_keywords'", ",", "'meta_author'", ",", "'fb_page_type'", ",", "'fb_image'", ")", ")", "template_fields", "=", "set", "(", "p", ".", "name", "for", "p", "in", "get_placeholders", "(", "p", "[", "'template'", "]", ")", "if", "p", ".", "name", "not", "in", "(", "'title'", ",", "'slug'", ")", ")", "template_fields", "|=", "set", "(", "(", "'meta_title'", ",", "'meta_description'", ",", "'meta_keywords'", ",", "'meta_author'", ",", "'fb_page_type'", ",", "'fb_image'", ")", ")", "if", "template_fields", "!=", "import_fields", ":", "errors", ".", "append", "(", "_", "(", "\"%s template contents are different than our \"", "\"template: %s\"", ")", "%", "(", "slug", ",", "p", "[", "'template'", "]", ")", ")", "continue", "return", "errors" ]
Check if an import of d will succeed, and return errors. errors is a list of strings. The import should proceed only if errors is empty.
[ "Check", "if", "an", "import", "of", "d", "will", "succeed", "and", "return", "errors", "." ]
863f3c6098606f663994930cd8e7723ad0c07caf
https://github.com/ArabellaTech/django-basic-cms/blob/863f3c6098606f663994930cd8e7723ad0c07caf/basic_cms/utils.py#L92-L160
train
ArabellaTech/django-basic-cms
basic_cms/utils.py
import_po_files
def import_po_files(path='poexport', stdout=None): """ Import all the content updates from the po files into the pages. """ import polib from basic_cms.models import Page, Content source_language = settings.PAGE_DEFAULT_LANGUAGE source_list = [] pages_to_invalidate = [] for page in Page.objects.published(): source_list.extend(page.content_by_language(source_language)) if stdout is None: import sys stdout = sys.stdout if not path.endswith('/'): path += '/' for lang in settings.PAGE_LANGUAGES: if lang[0] != settings.PAGE_DEFAULT_LANGUAGE: stdout.write("Update language %s.\n" % lang[0]) po_path = path + lang[0] + '.po' po = polib.pofile(po_path) for entry in po: meta_data = entry.tcomment.split(do_not_msg)[1].split("\n") placeholder_name = meta_data[1].split('=')[1] page_id = int(meta_data[2].split('=')[1]) page = Page.objects.get(id=page_id) current_content = Content.objects.get_content(page, lang[0], placeholder_name) if current_content != entry.msgstr: stdout.write("Update page %d placeholder %s.\n" % (page_id, placeholder_name)) Content.objects.create_content_if_changed( page, lang[0], placeholder_name, entry.msgstr) if page not in pages_to_invalidate: pages_to_invalidate.append(page) for page in pages_to_invalidate: page.invalidate() stdout.write("Import finished from %s.\n" % path)
python
def import_po_files(path='poexport', stdout=None): """ Import all the content updates from the po files into the pages. """ import polib from basic_cms.models import Page, Content source_language = settings.PAGE_DEFAULT_LANGUAGE source_list = [] pages_to_invalidate = [] for page in Page.objects.published(): source_list.extend(page.content_by_language(source_language)) if stdout is None: import sys stdout = sys.stdout if not path.endswith('/'): path += '/' for lang in settings.PAGE_LANGUAGES: if lang[0] != settings.PAGE_DEFAULT_LANGUAGE: stdout.write("Update language %s.\n" % lang[0]) po_path = path + lang[0] + '.po' po = polib.pofile(po_path) for entry in po: meta_data = entry.tcomment.split(do_not_msg)[1].split("\n") placeholder_name = meta_data[1].split('=')[1] page_id = int(meta_data[2].split('=')[1]) page = Page.objects.get(id=page_id) current_content = Content.objects.get_content(page, lang[0], placeholder_name) if current_content != entry.msgstr: stdout.write("Update page %d placeholder %s.\n" % (page_id, placeholder_name)) Content.objects.create_content_if_changed( page, lang[0], placeholder_name, entry.msgstr) if page not in pages_to_invalidate: pages_to_invalidate.append(page) for page in pages_to_invalidate: page.invalidate() stdout.write("Import finished from %s.\n" % path)
[ "def", "import_po_files", "(", "path", "=", "'poexport'", ",", "stdout", "=", "None", ")", ":", "import", "polib", "from", "basic_cms", ".", "models", "import", "Page", ",", "Content", "source_language", "=", "settings", ".", "PAGE_DEFAULT_LANGUAGE", "source_list", "=", "[", "]", "pages_to_invalidate", "=", "[", "]", "for", "page", "in", "Page", ".", "objects", ".", "published", "(", ")", ":", "source_list", ".", "extend", "(", "page", ".", "content_by_language", "(", "source_language", ")", ")", "if", "stdout", "is", "None", ":", "import", "sys", "stdout", "=", "sys", ".", "stdout", "if", "not", "path", ".", "endswith", "(", "'/'", ")", ":", "path", "+=", "'/'", "for", "lang", "in", "settings", ".", "PAGE_LANGUAGES", ":", "if", "lang", "[", "0", "]", "!=", "settings", ".", "PAGE_DEFAULT_LANGUAGE", ":", "stdout", ".", "write", "(", "\"Update language %s.\\n\"", "%", "lang", "[", "0", "]", ")", "po_path", "=", "path", "+", "lang", "[", "0", "]", "+", "'.po'", "po", "=", "polib", ".", "pofile", "(", "po_path", ")", "for", "entry", "in", "po", ":", "meta_data", "=", "entry", ".", "tcomment", ".", "split", "(", "do_not_msg", ")", "[", "1", "]", ".", "split", "(", "\"\\n\"", ")", "placeholder_name", "=", "meta_data", "[", "1", "]", ".", "split", "(", "'='", ")", "[", "1", "]", "page_id", "=", "int", "(", "meta_data", "[", "2", "]", ".", "split", "(", "'='", ")", "[", "1", "]", ")", "page", "=", "Page", ".", "objects", ".", "get", "(", "id", "=", "page_id", ")", "current_content", "=", "Content", ".", "objects", ".", "get_content", "(", "page", ",", "lang", "[", "0", "]", ",", "placeholder_name", ")", "if", "current_content", "!=", "entry", ".", "msgstr", ":", "stdout", ".", "write", "(", "\"Update page %d placeholder %s.\\n\"", "%", "(", "page_id", ",", "placeholder_name", ")", ")", "Content", ".", "objects", ".", "create_content_if_changed", "(", "page", ",", "lang", "[", "0", "]", ",", "placeholder_name", ",", "entry", ".", "msgstr", ")", "if", "page", "not", "in", "pages_to_invalidate", ":", "pages_to_invalidate", ".", "append", "(", "page", ")", "for", "page", "in", "pages_to_invalidate", ":", "page", ".", "invalidate", "(", ")", "stdout", ".", "write", "(", "\"Import finished from %s.\\n\"", "%", "path", ")" ]
Import all the content updates from the po files into the pages.
[ "Import", "all", "the", "content", "updates", "from", "the", "po", "files", "into", "the", "pages", "." ]
863f3c6098606f663994930cd8e7723ad0c07caf
https://github.com/ArabellaTech/django-basic-cms/blob/863f3c6098606f663994930cd8e7723ad0c07caf/basic_cms/utils.py#L301-L342
train
portfors-lab/sparkle
sparkle/run/protocol_model.py
ProtocolTabelModel.setCalibration
def setCalibration(self, db_boost_array, frequencies, frange): """Sets calibration for all tests See :meth:`StimulusModel<sparkle.stim.stimulus_model.StimulusModel.setCalibration>`""" self.calibrationVector = db_boost_array self.calibrationFrequencies = frequencies self.calibrationFrange = frange for test in self._tests: test.setCalibration(db_boost_array, frequencies, frange)
python
def setCalibration(self, db_boost_array, frequencies, frange): """Sets calibration for all tests See :meth:`StimulusModel<sparkle.stim.stimulus_model.StimulusModel.setCalibration>`""" self.calibrationVector = db_boost_array self.calibrationFrequencies = frequencies self.calibrationFrange = frange for test in self._tests: test.setCalibration(db_boost_array, frequencies, frange)
[ "def", "setCalibration", "(", "self", ",", "db_boost_array", ",", "frequencies", ",", "frange", ")", ":", "self", ".", "calibrationVector", "=", "db_boost_array", "self", ".", "calibrationFrequencies", "=", "frequencies", "self", ".", "calibrationFrange", "=", "frange", "for", "test", "in", "self", ".", "_tests", ":", "test", ".", "setCalibration", "(", "db_boost_array", ",", "frequencies", ",", "frange", ")" ]
Sets calibration for all tests See :meth:`StimulusModel<sparkle.stim.stimulus_model.StimulusModel.setCalibration>`
[ "Sets", "calibration", "for", "all", "tests" ]
5fad1cf2bec58ec6b15d91da20f6236a74826110
https://github.com/portfors-lab/sparkle/blob/5fad1cf2bec58ec6b15d91da20f6236a74826110/sparkle/run/protocol_model.py#L20-L28
train
portfors-lab/sparkle
sparkle/run/protocol_model.py
ProtocolTabelModel.insert
def insert(self, stim, position): """Inserts a new stimulus into the list at the given position :param stim: stimulus to insert into protocol :type stim: :class:`StimulusModel<sparkle.stim.stimulus_model.StimulusModel>` :param position: index (row) of location to insert to :type position: int """ if position == -1: position = self.rowCount() stim.setReferenceVoltage(self.caldb, self.calv) stim.setCalibration(self.calibrationVector, self.calibrationFrequencies, self.calibrationFrange) self._tests.insert(position, stim)
python
def insert(self, stim, position): """Inserts a new stimulus into the list at the given position :param stim: stimulus to insert into protocol :type stim: :class:`StimulusModel<sparkle.stim.stimulus_model.StimulusModel>` :param position: index (row) of location to insert to :type position: int """ if position == -1: position = self.rowCount() stim.setReferenceVoltage(self.caldb, self.calv) stim.setCalibration(self.calibrationVector, self.calibrationFrequencies, self.calibrationFrange) self._tests.insert(position, stim)
[ "def", "insert", "(", "self", ",", "stim", ",", "position", ")", ":", "if", "position", "==", "-", "1", ":", "position", "=", "self", ".", "rowCount", "(", ")", "stim", ".", "setReferenceVoltage", "(", "self", ".", "caldb", ",", "self", ".", "calv", ")", "stim", ".", "setCalibration", "(", "self", ".", "calibrationVector", ",", "self", ".", "calibrationFrequencies", ",", "self", ".", "calibrationFrange", ")", "self", ".", "_tests", ".", "insert", "(", "position", ",", "stim", ")" ]
Inserts a new stimulus into the list at the given position :param stim: stimulus to insert into protocol :type stim: :class:`StimulusModel<sparkle.stim.stimulus_model.StimulusModel>` :param position: index (row) of location to insert to :type position: int
[ "Inserts", "a", "new", "stimulus", "into", "the", "list", "at", "the", "given", "position" ]
5fad1cf2bec58ec6b15d91da20f6236a74826110
https://github.com/portfors-lab/sparkle/blob/5fad1cf2bec58ec6b15d91da20f6236a74826110/sparkle/run/protocol_model.py#L61-L73
train
portfors-lab/sparkle
sparkle/run/protocol_model.py
ProtocolTabelModel.verify
def verify(self, windowSize=None): """Verify that this protocol model is valid. Return 0 if sucessful, a failure message otherwise :param windowSize: acquistion window size (seconds), to check against duration, check is not performed is None provided :type windowSize: float :returns: 0 (int) for success, fail message (str) otherwise """ if self.rowCount() == 0: return "Protocol must have at least one test" if self.caldb is None or self.calv is None: return "Protocol reference voltage not set" for test in self._tests: msg = test.verify(windowSize) if msg: return msg return 0
python
def verify(self, windowSize=None): """Verify that this protocol model is valid. Return 0 if sucessful, a failure message otherwise :param windowSize: acquistion window size (seconds), to check against duration, check is not performed is None provided :type windowSize: float :returns: 0 (int) for success, fail message (str) otherwise """ if self.rowCount() == 0: return "Protocol must have at least one test" if self.caldb is None or self.calv is None: return "Protocol reference voltage not set" for test in self._tests: msg = test.verify(windowSize) if msg: return msg return 0
[ "def", "verify", "(", "self", ",", "windowSize", "=", "None", ")", ":", "if", "self", ".", "rowCount", "(", ")", "==", "0", ":", "return", "\"Protocol must have at least one test\"", "if", "self", ".", "caldb", "is", "None", "or", "self", ".", "calv", "is", "None", ":", "return", "\"Protocol reference voltage not set\"", "for", "test", "in", "self", ".", "_tests", ":", "msg", "=", "test", ".", "verify", "(", "windowSize", ")", "if", "msg", ":", "return", "msg", "return", "0" ]
Verify that this protocol model is valid. Return 0 if sucessful, a failure message otherwise :param windowSize: acquistion window size (seconds), to check against duration, check is not performed is None provided :type windowSize: float :returns: 0 (int) for success, fail message (str) otherwise
[ "Verify", "that", "this", "protocol", "model", "is", "valid", ".", "Return", "0", "if", "sucessful", "a", "failure", "message", "otherwise" ]
5fad1cf2bec58ec6b15d91da20f6236a74826110
https://github.com/portfors-lab/sparkle/blob/5fad1cf2bec58ec6b15d91da20f6236a74826110/sparkle/run/protocol_model.py#L79-L95
train
dchaplinsky/LT2OpenCorpora
lt2opencorpora/convert.py
open_any
def open_any(filename): """ Helper to open also compressed files """ if filename.endswith(".gz"): return gzip.open if filename.endswith(".bz2"): return bz2.BZ2File return open
python
def open_any(filename): """ Helper to open also compressed files """ if filename.endswith(".gz"): return gzip.open if filename.endswith(".bz2"): return bz2.BZ2File return open
[ "def", "open_any", "(", "filename", ")", ":", "if", "filename", ".", "endswith", "(", "\".gz\"", ")", ":", "return", "gzip", ".", "open", "if", "filename", ".", "endswith", "(", "\".bz2\"", ")", ":", "return", "bz2", ".", "BZ2File", "return", "open" ]
Helper to open also compressed files
[ "Helper", "to", "open", "also", "compressed", "files" ]
7bf48098ec2db4c8955a660fd0c1b80a16e43054
https://github.com/dchaplinsky/LT2OpenCorpora/blob/7bf48098ec2db4c8955a660fd0c1b80a16e43054/lt2opencorpora/convert.py#L24-L34
train
dchaplinsky/LT2OpenCorpora
lt2opencorpora/convert.py
TagSet._get_group_no
def _get_group_no(self, tag_name): """ Takes tag name and returns the number of the group to which tag belongs """ if tag_name in self.full: return self.groups.index(self.full[tag_name]["parent"]) else: return len(self.groups)
python
def _get_group_no(self, tag_name): """ Takes tag name and returns the number of the group to which tag belongs """ if tag_name in self.full: return self.groups.index(self.full[tag_name]["parent"]) else: return len(self.groups)
[ "def", "_get_group_no", "(", "self", ",", "tag_name", ")", ":", "if", "tag_name", "in", "self", ".", "full", ":", "return", "self", ".", "groups", ".", "index", "(", "self", ".", "full", "[", "tag_name", "]", "[", "\"parent\"", "]", ")", "else", ":", "return", "len", "(", "self", ".", "groups", ")" ]
Takes tag name and returns the number of the group to which tag belongs
[ "Takes", "tag", "name", "and", "returns", "the", "number", "of", "the", "group", "to", "which", "tag", "belongs" ]
7bf48098ec2db4c8955a660fd0c1b80a16e43054
https://github.com/dchaplinsky/LT2OpenCorpora/blob/7bf48098ec2db4c8955a660fd0c1b80a16e43054/lt2opencorpora/convert.py#L90-L98
train
Frzk/Ellis
ellis_actions/ipset.py
Ipset.add
async def add(self, setname, ip, timeout=0): """ Adds the given IP address to the given ipset. If a timeout is given, the IP will stay in the ipset for the given duration. Else it's added forever. The resulting command looks like this: ``ipset add -exist ellis_blacklist4 192.0.2.10 timeout 14400`` """ args = ['add', '-exist', setname, ip, 'timeout', timeout] return await self.start(__class__.CMD, *args)
python
async def add(self, setname, ip, timeout=0): """ Adds the given IP address to the given ipset. If a timeout is given, the IP will stay in the ipset for the given duration. Else it's added forever. The resulting command looks like this: ``ipset add -exist ellis_blacklist4 192.0.2.10 timeout 14400`` """ args = ['add', '-exist', setname, ip, 'timeout', timeout] return await self.start(__class__.CMD, *args)
[ "async", "def", "add", "(", "self", ",", "setname", ",", "ip", ",", "timeout", "=", "0", ")", ":", "args", "=", "[", "'add'", ",", "'-exist'", ",", "setname", ",", "ip", ",", "'timeout'", ",", "timeout", "]", "return", "await", "self", ".", "start", "(", "__class__", ".", "CMD", ",", "*", "args", ")" ]
Adds the given IP address to the given ipset. If a timeout is given, the IP will stay in the ipset for the given duration. Else it's added forever. The resulting command looks like this: ``ipset add -exist ellis_blacklist4 192.0.2.10 timeout 14400``
[ "Adds", "the", "given", "IP", "address", "to", "the", "given", "ipset", ".", "If", "a", "timeout", "is", "given", "the", "IP", "will", "stay", "in", "the", "ipset", "for", "the", "given", "duration", ".", "Else", "it", "s", "added", "forever", "." ]
39ce8987cbc503354cf1f45927344186a8b18363
https://github.com/Frzk/Ellis/blob/39ce8987cbc503354cf1f45927344186a8b18363/ellis_actions/ipset.py#L35-L49
train
Frzk/Ellis
ellis_actions/ipset.py
Ipset.list
async def list(self, setname=None): """ Lists the existing ipsets. If setname is given, only lists this ipset. The resulting command looks like one of the following: * ``ipset list`` * ``ipset list ellis_blacklist4`` """ args = ['list'] if setname is not None: args.append(setname) return await self.start(__class__.CMD, *args)
python
async def list(self, setname=None): """ Lists the existing ipsets. If setname is given, only lists this ipset. The resulting command looks like one of the following: * ``ipset list`` * ``ipset list ellis_blacklist4`` """ args = ['list'] if setname is not None: args.append(setname) return await self.start(__class__.CMD, *args)
[ "async", "def", "list", "(", "self", ",", "setname", "=", "None", ")", ":", "args", "=", "[", "'list'", "]", "if", "setname", "is", "not", "None", ":", "args", ".", "append", "(", "setname", ")", "return", "await", "self", ".", "start", "(", "__class__", ".", "CMD", ",", "*", "args", ")" ]
Lists the existing ipsets. If setname is given, only lists this ipset. The resulting command looks like one of the following: * ``ipset list`` * ``ipset list ellis_blacklist4``
[ "Lists", "the", "existing", "ipsets", "." ]
39ce8987cbc503354cf1f45927344186a8b18363
https://github.com/Frzk/Ellis/blob/39ce8987cbc503354cf1f45927344186a8b18363/ellis_actions/ipset.py#L51-L68
train
portfors-lab/sparkle
sparkle/run/list_runner.py
ListAcquisitionRunner.setup
def setup(self, interval): """Prepares the tests for execution, interval in ms""" self.trace_counter = 0 self._halt = False self.interval = interval
python
def setup(self, interval): """Prepares the tests for execution, interval in ms""" self.trace_counter = 0 self._halt = False self.interval = interval
[ "def", "setup", "(", "self", ",", "interval", ")", ":", "self", ".", "trace_counter", "=", "0", "self", ".", "_halt", "=", "False", "self", ".", "interval", "=", "interval" ]
Prepares the tests for execution, interval in ms
[ "Prepares", "the", "tests", "for", "execution", "interval", "in", "ms" ]
5fad1cf2bec58ec6b15d91da20f6236a74826110
https://github.com/portfors-lab/sparkle/blob/5fad1cf2bec58ec6b15d91da20f6236a74826110/sparkle/run/list_runner.py#L49-L54
train
portfors-lab/sparkle
sparkle/run/list_runner.py
ListAcquisitionRunner.run
def run(self): """Runs the acquisition""" self._initialize_run() stimuli = self.protocol_model.allTests() self.acq_thread = threading.Thread(target=self._worker, args=(stimuli,), ) # save the current calibration to data file doc if self.save_data: info = {'calibration_used': self.calname, 'calibration_range': self.cal_frange} self.datafile.set_metadata(self.current_dataset_name, info) # save the start time and set last tick to expired, so first # acquisition loop iteration executes immediately self.start_time = time.time() self.last_tick = self.start_time - (self.interval/1000) self.acq_thread.start() return self.acq_thread
python
def run(self): """Runs the acquisition""" self._initialize_run() stimuli = self.protocol_model.allTests() self.acq_thread = threading.Thread(target=self._worker, args=(stimuli,), ) # save the current calibration to data file doc if self.save_data: info = {'calibration_used': self.calname, 'calibration_range': self.cal_frange} self.datafile.set_metadata(self.current_dataset_name, info) # save the start time and set last tick to expired, so first # acquisition loop iteration executes immediately self.start_time = time.time() self.last_tick = self.start_time - (self.interval/1000) self.acq_thread.start() return self.acq_thread
[ "def", "run", "(", "self", ")", ":", "self", ".", "_initialize_run", "(", ")", "stimuli", "=", "self", ".", "protocol_model", ".", "allTests", "(", ")", "self", ".", "acq_thread", "=", "threading", ".", "Thread", "(", "target", "=", "self", ".", "_worker", ",", "args", "=", "(", "stimuli", ",", ")", ",", ")", "# save the current calibration to data file doc ", "if", "self", ".", "save_data", ":", "info", "=", "{", "'calibration_used'", ":", "self", ".", "calname", ",", "'calibration_range'", ":", "self", ".", "cal_frange", "}", "self", ".", "datafile", ".", "set_metadata", "(", "self", ".", "current_dataset_name", ",", "info", ")", "# save the start time and set last tick to expired, so first", "# acquisition loop iteration executes immediately", "self", ".", "start_time", "=", "time", ".", "time", "(", ")", "self", ".", "last_tick", "=", "self", ".", "start_time", "-", "(", "self", ".", "interval", "/", "1000", ")", "self", ".", "acq_thread", ".", "start", "(", ")", "return", "self", ".", "acq_thread" ]
Runs the acquisition
[ "Runs", "the", "acquisition" ]
5fad1cf2bec58ec6b15d91da20f6236a74826110
https://github.com/portfors-lab/sparkle/blob/5fad1cf2bec58ec6b15d91da20f6236a74826110/sparkle/run/list_runner.py#L56-L75
train
sirfoga/pyhal
hal/ml/predict.py
BasePrediction.train
def train(self, x_data, y_data): """Trains model on inputs :param x_data: x matrix :param y_data: y array """ x_train, _, y_train, _ = train_test_split( x_data, y_data, test_size=0.67, random_state=None ) # cross-split self.model.fit(x_train, y_train)
python
def train(self, x_data, y_data): """Trains model on inputs :param x_data: x matrix :param y_data: y array """ x_train, _, y_train, _ = train_test_split( x_data, y_data, test_size=0.67, random_state=None ) # cross-split self.model.fit(x_train, y_train)
[ "def", "train", "(", "self", ",", "x_data", ",", "y_data", ")", ":", "x_train", ",", "_", ",", "y_train", ",", "_", "=", "train_test_split", "(", "x_data", ",", "y_data", ",", "test_size", "=", "0.67", ",", "random_state", "=", "None", ")", "# cross-split", "self", ".", "model", ".", "fit", "(", "x_train", ",", "y_train", ")" ]
Trains model on inputs :param x_data: x matrix :param y_data: y array
[ "Trains", "model", "on", "inputs" ]
4394d8a1f7e45bea28a255ec390f4962ee64d33a
https://github.com/sirfoga/pyhal/blob/4394d8a1f7e45bea28a255ec390f4962ee64d33a/hal/ml/predict.py#L21-L34
train
sirfoga/pyhal
hal/strings/utils.py
get_max_similar
def get_max_similar(string, lst): """Finds most similar string in list :param string: String to find :param lst: Strings available :return: Max similarity and index of max similar """ max_similarity, index = 0.0, -1 for i, candidate in enumerate(lst): sim = how_similar_are(str(string), str(candidate)) if sim > max_similarity: max_similarity, index = sim, i return max_similarity, index
python
def get_max_similar(string, lst): """Finds most similar string in list :param string: String to find :param lst: Strings available :return: Max similarity and index of max similar """ max_similarity, index = 0.0, -1 for i, candidate in enumerate(lst): sim = how_similar_are(str(string), str(candidate)) if sim > max_similarity: max_similarity, index = sim, i return max_similarity, index
[ "def", "get_max_similar", "(", "string", ",", "lst", ")", ":", "max_similarity", ",", "index", "=", "0.0", ",", "-", "1", "for", "i", ",", "candidate", "in", "enumerate", "(", "lst", ")", ":", "sim", "=", "how_similar_are", "(", "str", "(", "string", ")", ",", "str", "(", "candidate", ")", ")", "if", "sim", ">", "max_similarity", ":", "max_similarity", ",", "index", "=", "sim", ",", "i", "return", "max_similarity", ",", "index" ]
Finds most similar string in list :param string: String to find :param lst: Strings available :return: Max similarity and index of max similar
[ "Finds", "most", "similar", "string", "in", "list" ]
4394d8a1f7e45bea28a255ec390f4962ee64d33a
https://github.com/sirfoga/pyhal/blob/4394d8a1f7e45bea28a255ec390f4962ee64d33a/hal/strings/utils.py#L18-L30
train
sirfoga/pyhal
hal/strings/utils.py
get_average_length_of_string
def get_average_length_of_string(strings): """Computes average length of words :param strings: list of words :return: Average length of word on list """ if not strings: return 0 return sum(len(word) for word in strings) / len(strings)
python
def get_average_length_of_string(strings): """Computes average length of words :param strings: list of words :return: Average length of word on list """ if not strings: return 0 return sum(len(word) for word in strings) / len(strings)
[ "def", "get_average_length_of_string", "(", "strings", ")", ":", "if", "not", "strings", ":", "return", "0", "return", "sum", "(", "len", "(", "word", ")", "for", "word", "in", "strings", ")", "/", "len", "(", "strings", ")" ]
Computes average length of words :param strings: list of words :return: Average length of word on list
[ "Computes", "average", "length", "of", "words" ]
4394d8a1f7e45bea28a255ec390f4962ee64d33a
https://github.com/sirfoga/pyhal/blob/4394d8a1f7e45bea28a255ec390f4962ee64d33a/hal/strings/utils.py#L33-L42
train
sirfoga/pyhal
hal/wrappers/errors.py
true_false_returns
def true_false_returns(func): """Executes function, if error returns False, else True :param func: function to call :return: True iff ok, else False """ @functools.wraps(func) def _execute(*args, **kwargs): """Executes function, if error returns False, else True :param args: args of function :param kwargs: extra args of function :param *args: args :param **kwargs: extra args :return: True iff ok, else False """ try: func(*args, **kwargs) return True except: return False return _execute
python
def true_false_returns(func): """Executes function, if error returns False, else True :param func: function to call :return: True iff ok, else False """ @functools.wraps(func) def _execute(*args, **kwargs): """Executes function, if error returns False, else True :param args: args of function :param kwargs: extra args of function :param *args: args :param **kwargs: extra args :return: True iff ok, else False """ try: func(*args, **kwargs) return True except: return False return _execute
[ "def", "true_false_returns", "(", "func", ")", ":", "@", "functools", ".", "wraps", "(", "func", ")", "def", "_execute", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "\"\"\"Executes function, if error returns False, else True\n\n :param args: args of function\n :param kwargs: extra args of function\n :param *args: args\n :param **kwargs: extra args\n :return: True iff ok, else False\n \"\"\"", "try", ":", "func", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "True", "except", ":", "return", "False", "return", "_execute" ]
Executes function, if error returns False, else True :param func: function to call :return: True iff ok, else False
[ "Executes", "function", "if", "error", "returns", "False", "else", "True" ]
4394d8a1f7e45bea28a255ec390f4962ee64d33a
https://github.com/sirfoga/pyhal/blob/4394d8a1f7e45bea28a255ec390f4962ee64d33a/hal/wrappers/errors.py#L8-L32
train
sirfoga/pyhal
hal/wrappers/errors.py
none_returns
def none_returns(func): """Executes function, if error returns None else value of function :param func: function to call :return: None else value of function """ @functools.wraps(func) def _execute(*args, **kwargs): """Executes function, if error returns None else value of function :param args: args of function :param kwargs: extra args of function :param *args: args :param **kwargs: extra args :return: None else value of function """ try: return func(*args, **kwargs) except: return None return _execute
python
def none_returns(func): """Executes function, if error returns None else value of function :param func: function to call :return: None else value of function """ @functools.wraps(func) def _execute(*args, **kwargs): """Executes function, if error returns None else value of function :param args: args of function :param kwargs: extra args of function :param *args: args :param **kwargs: extra args :return: None else value of function """ try: return func(*args, **kwargs) except: return None return _execute
[ "def", "none_returns", "(", "func", ")", ":", "@", "functools", ".", "wraps", "(", "func", ")", "def", "_execute", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "\"\"\"Executes function, if error returns None else value of function\n\n :param args: args of function\n :param kwargs: extra args of function\n :param *args: args\n :param **kwargs: extra args\n :return: None else value of function\n \"\"\"", "try", ":", "return", "func", "(", "*", "args", ",", "*", "*", "kwargs", ")", "except", ":", "return", "None", "return", "_execute" ]
Executes function, if error returns None else value of function :param func: function to call :return: None else value of function
[ "Executes", "function", "if", "error", "returns", "None", "else", "value", "of", "function" ]
4394d8a1f7e45bea28a255ec390f4962ee64d33a
https://github.com/sirfoga/pyhal/blob/4394d8a1f7e45bea28a255ec390f4962ee64d33a/hal/wrappers/errors.py#L35-L58
train
JukeboxPipeline/jukeboxmaya
src/jukeboxmaya/reftrack/asset.py
select_dag_nodes
def select_dag_nodes(reftrack): """Select all dag nodes of the given reftrack :param reftrack: The reftrack to select the dagnodes for :type reftrack: :class:`jukeboxcore.reftrack.Reftrack` :returns: None :rtype: None :raises: None """ refobj = reftrack.get_refobj() if not refobj: return parentns = common.get_namespace(refobj) ns = cmds.getAttr("%s.namespace" % refobj) fullns = ":".join((parentns.rstrip(":"), ns.lstrip(":"))) c = cmds.namespaceInfo(fullns, listOnlyDependencyNodes=True, dagPath=True, recurse=True) dag = cmds.ls(c, dag=True, ap=True) cmds.select(dag, replace=True)
python
def select_dag_nodes(reftrack): """Select all dag nodes of the given reftrack :param reftrack: The reftrack to select the dagnodes for :type reftrack: :class:`jukeboxcore.reftrack.Reftrack` :returns: None :rtype: None :raises: None """ refobj = reftrack.get_refobj() if not refobj: return parentns = common.get_namespace(refobj) ns = cmds.getAttr("%s.namespace" % refobj) fullns = ":".join((parentns.rstrip(":"), ns.lstrip(":"))) c = cmds.namespaceInfo(fullns, listOnlyDependencyNodes=True, dagPath=True, recurse=True) dag = cmds.ls(c, dag=True, ap=True) cmds.select(dag, replace=True)
[ "def", "select_dag_nodes", "(", "reftrack", ")", ":", "refobj", "=", "reftrack", ".", "get_refobj", "(", ")", "if", "not", "refobj", ":", "return", "parentns", "=", "common", ".", "get_namespace", "(", "refobj", ")", "ns", "=", "cmds", ".", "getAttr", "(", "\"%s.namespace\"", "%", "refobj", ")", "fullns", "=", "\":\"", ".", "join", "(", "(", "parentns", ".", "rstrip", "(", "\":\"", ")", ",", "ns", ".", "lstrip", "(", "\":\"", ")", ")", ")", "c", "=", "cmds", ".", "namespaceInfo", "(", "fullns", ",", "listOnlyDependencyNodes", "=", "True", ",", "dagPath", "=", "True", ",", "recurse", "=", "True", ")", "dag", "=", "cmds", ".", "ls", "(", "c", ",", "dag", "=", "True", ",", "ap", "=", "True", ")", "cmds", ".", "select", "(", "dag", ",", "replace", "=", "True", ")" ]
Select all dag nodes of the given reftrack :param reftrack: The reftrack to select the dagnodes for :type reftrack: :class:`jukeboxcore.reftrack.Reftrack` :returns: None :rtype: None :raises: None
[ "Select", "all", "dag", "nodes", "of", "the", "given", "reftrack" ]
c8d6318d53cdb5493453c4a6b65ef75bdb2d5f2c
https://github.com/JukeboxPipeline/jukeboxmaya/blob/c8d6318d53cdb5493453c4a6b65ef75bdb2d5f2c/src/jukeboxmaya/reftrack/asset.py#L38-L55
train
JukeboxPipeline/jukeboxmaya
src/jukeboxmaya/reftrack/asset.py
AssetReftypeInterface.get_scenenode
def get_scenenode(self, nodes): """Get the scenenode in the given nodes There should only be one scenenode in nodes! :param nodes: :type nodes: :returns: None :rtype: None :raises: AssertionError """ scenenodes = cmds.ls(nodes, type='jb_sceneNode') assert scenenodes, "Found no scene nodes!" return sorted(scenenodes)[0]
python
def get_scenenode(self, nodes): """Get the scenenode in the given nodes There should only be one scenenode in nodes! :param nodes: :type nodes: :returns: None :rtype: None :raises: AssertionError """ scenenodes = cmds.ls(nodes, type='jb_sceneNode') assert scenenodes, "Found no scene nodes!" return sorted(scenenodes)[0]
[ "def", "get_scenenode", "(", "self", ",", "nodes", ")", ":", "scenenodes", "=", "cmds", ".", "ls", "(", "nodes", ",", "type", "=", "'jb_sceneNode'", ")", "assert", "scenenodes", ",", "\"Found no scene nodes!\"", "return", "sorted", "(", "scenenodes", ")", "[", "0", "]" ]
Get the scenenode in the given nodes There should only be one scenenode in nodes! :param nodes: :type nodes: :returns: None :rtype: None :raises: AssertionError
[ "Get", "the", "scenenode", "in", "the", "given", "nodes" ]
c8d6318d53cdb5493453c4a6b65ef75bdb2d5f2c
https://github.com/JukeboxPipeline/jukeboxmaya/blob/c8d6318d53cdb5493453c4a6b65ef75bdb2d5f2c/src/jukeboxmaya/reftrack/asset.py#L85-L98
train
JukeboxPipeline/jukeboxmaya
src/jukeboxmaya/reftrack/asset.py
AssetReftypeInterface.reference
def reference(self, refobj, taskfileinfo): """Reference the given taskfileinfo into the scene and return the created reference node The created reference node will be used on :meth:`RefobjInterface.set_reference` to set the reference on a reftrack node. Do not call :meth:`RefobjInterface.set_reference` yourself. This will also create a group node and group all dagnodes under a appropriate node. :param refobj: the reftrack node that will be linked to the reference :type refobj: str :param taskfileinfo: The taskfileinfo that holds the information for what to reference :type taskfileinfo: :class:`jukeboxcore.filesys.TaskFileInfo` :returns: the reference node that was created and should set on the appropriate reftrack node :rtype: str :raises: None """ # work in root namespace with common.preserve_namespace(":"): jbfile = JB_File(taskfileinfo) filepath = jbfile.get_fullpath() ns_suggestion = reftrack.get_namespace(taskfileinfo) newnodes = cmds.file(filepath, reference=True, namespace=ns_suggestion, returnNewNodes=True) # You could also use the filename returned by the file command to query the reference node. # Atm there is a but, that if you import the file before, the command fails. # So we get all new reference nodes and query the one that is not referenced for refnode in cmds.ls(newnodes, type='reference'): if not cmds.referenceQuery(refnode, isNodeReferenced=True): node = refnode break ns = cmds.referenceQuery(node, namespace=True) # query the actual new namespace content = cmds.namespaceInfo(ns, listOnlyDependencyNodes=True, dagPath=True) # get the content # connect reftrack with scenenode scenenode = self.get_scenenode(content) self.get_refobjinter().connect_reftrack_scenenode(refobj, scenenode) reccontent = cmds.namespaceInfo(ns, listOnlyDependencyNodes=True, dagPath=True, recurse=True) # get the content + content of children dagcontent = cmds.ls(reccontent, ap=True, assemblies=True) # get only the top level dagnodes so we can group them if not dagcontent: return node # no need for a top group if there are not dagnodes to group # group the dagnodes grpname = reftrack.get_groupname(taskfileinfo) reftrack.group_content(dagcontent, ns, grpname, "jb_asset") return node
python
def reference(self, refobj, taskfileinfo): """Reference the given taskfileinfo into the scene and return the created reference node The created reference node will be used on :meth:`RefobjInterface.set_reference` to set the reference on a reftrack node. Do not call :meth:`RefobjInterface.set_reference` yourself. This will also create a group node and group all dagnodes under a appropriate node. :param refobj: the reftrack node that will be linked to the reference :type refobj: str :param taskfileinfo: The taskfileinfo that holds the information for what to reference :type taskfileinfo: :class:`jukeboxcore.filesys.TaskFileInfo` :returns: the reference node that was created and should set on the appropriate reftrack node :rtype: str :raises: None """ # work in root namespace with common.preserve_namespace(":"): jbfile = JB_File(taskfileinfo) filepath = jbfile.get_fullpath() ns_suggestion = reftrack.get_namespace(taskfileinfo) newnodes = cmds.file(filepath, reference=True, namespace=ns_suggestion, returnNewNodes=True) # You could also use the filename returned by the file command to query the reference node. # Atm there is a but, that if you import the file before, the command fails. # So we get all new reference nodes and query the one that is not referenced for refnode in cmds.ls(newnodes, type='reference'): if not cmds.referenceQuery(refnode, isNodeReferenced=True): node = refnode break ns = cmds.referenceQuery(node, namespace=True) # query the actual new namespace content = cmds.namespaceInfo(ns, listOnlyDependencyNodes=True, dagPath=True) # get the content # connect reftrack with scenenode scenenode = self.get_scenenode(content) self.get_refobjinter().connect_reftrack_scenenode(refobj, scenenode) reccontent = cmds.namespaceInfo(ns, listOnlyDependencyNodes=True, dagPath=True, recurse=True) # get the content + content of children dagcontent = cmds.ls(reccontent, ap=True, assemblies=True) # get only the top level dagnodes so we can group them if not dagcontent: return node # no need for a top group if there are not dagnodes to group # group the dagnodes grpname = reftrack.get_groupname(taskfileinfo) reftrack.group_content(dagcontent, ns, grpname, "jb_asset") return node
[ "def", "reference", "(", "self", ",", "refobj", ",", "taskfileinfo", ")", ":", "# work in root namespace", "with", "common", ".", "preserve_namespace", "(", "\":\"", ")", ":", "jbfile", "=", "JB_File", "(", "taskfileinfo", ")", "filepath", "=", "jbfile", ".", "get_fullpath", "(", ")", "ns_suggestion", "=", "reftrack", ".", "get_namespace", "(", "taskfileinfo", ")", "newnodes", "=", "cmds", ".", "file", "(", "filepath", ",", "reference", "=", "True", ",", "namespace", "=", "ns_suggestion", ",", "returnNewNodes", "=", "True", ")", "# You could also use the filename returned by the file command to query the reference node.", "# Atm there is a but, that if you import the file before, the command fails.", "# So we get all new reference nodes and query the one that is not referenced", "for", "refnode", "in", "cmds", ".", "ls", "(", "newnodes", ",", "type", "=", "'reference'", ")", ":", "if", "not", "cmds", ".", "referenceQuery", "(", "refnode", ",", "isNodeReferenced", "=", "True", ")", ":", "node", "=", "refnode", "break", "ns", "=", "cmds", ".", "referenceQuery", "(", "node", ",", "namespace", "=", "True", ")", "# query the actual new namespace", "content", "=", "cmds", ".", "namespaceInfo", "(", "ns", ",", "listOnlyDependencyNodes", "=", "True", ",", "dagPath", "=", "True", ")", "# get the content", "# connect reftrack with scenenode", "scenenode", "=", "self", ".", "get_scenenode", "(", "content", ")", "self", ".", "get_refobjinter", "(", ")", ".", "connect_reftrack_scenenode", "(", "refobj", ",", "scenenode", ")", "reccontent", "=", "cmds", ".", "namespaceInfo", "(", "ns", ",", "listOnlyDependencyNodes", "=", "True", ",", "dagPath", "=", "True", ",", "recurse", "=", "True", ")", "# get the content + content of children", "dagcontent", "=", "cmds", ".", "ls", "(", "reccontent", ",", "ap", "=", "True", ",", "assemblies", "=", "True", ")", "# get only the top level dagnodes so we can group them", "if", "not", "dagcontent", ":", "return", "node", "# no need for a top group if there are not dagnodes to group", "# group the dagnodes", "grpname", "=", "reftrack", ".", "get_groupname", "(", "taskfileinfo", ")", "reftrack", ".", "group_content", "(", "dagcontent", ",", "ns", ",", "grpname", ",", "\"jb_asset\"", ")", "return", "node" ]
Reference the given taskfileinfo into the scene and return the created reference node The created reference node will be used on :meth:`RefobjInterface.set_reference` to set the reference on a reftrack node. Do not call :meth:`RefobjInterface.set_reference` yourself. This will also create a group node and group all dagnodes under a appropriate node. :param refobj: the reftrack node that will be linked to the reference :type refobj: str :param taskfileinfo: The taskfileinfo that holds the information for what to reference :type taskfileinfo: :class:`jukeboxcore.filesys.TaskFileInfo` :returns: the reference node that was created and should set on the appropriate reftrack node :rtype: str :raises: None
[ "Reference", "the", "given", "taskfileinfo", "into", "the", "scene", "and", "return", "the", "created", "reference", "node" ]
c8d6318d53cdb5493453c4a6b65ef75bdb2d5f2c
https://github.com/JukeboxPipeline/jukeboxmaya/blob/c8d6318d53cdb5493453c4a6b65ef75bdb2d5f2c/src/jukeboxmaya/reftrack/asset.py#L100-L142
train
JukeboxPipeline/jukeboxmaya
src/jukeboxmaya/reftrack/asset.py
AssetReftypeInterface.replace
def replace(self, refobj, reference, taskfileinfo): """Replace the given reference with the given taskfileinfo :param refobj: the refobj that is linked to the reference :param reference: the reference object. E.g. in Maya a reference node :param taskfileinfo: the taskfileinfo that will replace the old entity :type taskfileinfo: :class:`jukeboxcore.filesys.TaskFileInfo` :returns: None :rtype: None :raises: None """ jbfile = JB_File(taskfileinfo) filepath = jbfile.get_fullpath() cmds.file(filepath, loadReference=reference) ns = cmds.referenceQuery(reference, namespace=True) # query the actual new namespace content = cmds.namespaceInfo(ns, listOnlyDependencyNodes=True, dagPath=True) # get the content scenenode = self.get_scenenode(content) # get the scene node self.get_refobjinter().connect_reftrack_scenenode(refobj, scenenode)
python
def replace(self, refobj, reference, taskfileinfo): """Replace the given reference with the given taskfileinfo :param refobj: the refobj that is linked to the reference :param reference: the reference object. E.g. in Maya a reference node :param taskfileinfo: the taskfileinfo that will replace the old entity :type taskfileinfo: :class:`jukeboxcore.filesys.TaskFileInfo` :returns: None :rtype: None :raises: None """ jbfile = JB_File(taskfileinfo) filepath = jbfile.get_fullpath() cmds.file(filepath, loadReference=reference) ns = cmds.referenceQuery(reference, namespace=True) # query the actual new namespace content = cmds.namespaceInfo(ns, listOnlyDependencyNodes=True, dagPath=True) # get the content scenenode = self.get_scenenode(content) # get the scene node self.get_refobjinter().connect_reftrack_scenenode(refobj, scenenode)
[ "def", "replace", "(", "self", ",", "refobj", ",", "reference", ",", "taskfileinfo", ")", ":", "jbfile", "=", "JB_File", "(", "taskfileinfo", ")", "filepath", "=", "jbfile", ".", "get_fullpath", "(", ")", "cmds", ".", "file", "(", "filepath", ",", "loadReference", "=", "reference", ")", "ns", "=", "cmds", ".", "referenceQuery", "(", "reference", ",", "namespace", "=", "True", ")", "# query the actual new namespace", "content", "=", "cmds", ".", "namespaceInfo", "(", "ns", ",", "listOnlyDependencyNodes", "=", "True", ",", "dagPath", "=", "True", ")", "# get the content", "scenenode", "=", "self", ".", "get_scenenode", "(", "content", ")", "# get the scene node", "self", ".", "get_refobjinter", "(", ")", ".", "connect_reftrack_scenenode", "(", "refobj", ",", "scenenode", ")" ]
Replace the given reference with the given taskfileinfo :param refobj: the refobj that is linked to the reference :param reference: the reference object. E.g. in Maya a reference node :param taskfileinfo: the taskfileinfo that will replace the old entity :type taskfileinfo: :class:`jukeboxcore.filesys.TaskFileInfo` :returns: None :rtype: None :raises: None
[ "Replace", "the", "given", "reference", "with", "the", "given", "taskfileinfo" ]
c8d6318d53cdb5493453c4a6b65ef75bdb2d5f2c
https://github.com/JukeboxPipeline/jukeboxmaya/blob/c8d6318d53cdb5493453c4a6b65ef75bdb2d5f2c/src/jukeboxmaya/reftrack/asset.py#L176-L193
train