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
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
MonashBI/arcana
arcana/pipeline/base.py
Pipeline._make_inputnode
def _make_inputnode(self, frequency): """ Generates an input node for the given frequency. It also adds implicit file format conversion nodes to the pipeline. Parameters ---------- frequency : str The frequency (i.e. 'per_session', 'per_visit', 'per_subject' or 'per_study') of the input node to retrieve """ # Check to see whether there are any outputs for the given frequency inputs = list(self.frequency_inputs(frequency)) # Get list of input names for the requested frequency, addding fields # to hold iterator IDs input_names = [i.name for i in inputs] input_names.extend(self.study.FREQUENCIES[frequency]) if not input_names: raise ArcanaError( "No inputs to '{}' pipeline for requested freqency '{}'" .format(self.name, frequency)) # Generate input node and connect it to appropriate nodes inputnode = self.add('{}_inputnode'.format(frequency), IdentityInterface(fields=input_names)) # Loop through list of nodes connected to study data specs and # connect them to the newly created input node for input in inputs: # @ReservedAssignment # Keep track of previous conversion nodes to avoid replicating the # conversion for inputs that are used in multiple places prev_conv_nodes = {} for (node, node_in, format, # @ReservedAssignment @IgnorePep8 conv_kwargs) in self._input_conns[input.name]: # If fileset formats differ between study and pipeline # inputs create converter node (if one hasn't been already) # and connect input to that before connecting to inputnode if self.requires_conversion(input, format): try: conv = format.converter_from(input.format, **conv_kwargs) except ArcanaNoConverterError as e: e.msg += ( "which is required to convert '{}' from {} to {} " "for '{}' input of '{}' node".format( input.name, input.format, format, node_in, node.name)) raise e try: in_node = prev_conv_nodes[format.name] except KeyError: in_node = prev_conv_nodes[format.name] = self.add( 'conv_{}_to_{}_format'.format(input.name, format.name), conv.interface, inputs={conv.input: (inputnode, input.name)}, requirements=conv.requirements, mem_gb=conv.mem_gb, wall_time=conv.wall_time) in_node_out = conv.output else: in_node = inputnode in_node_out = input.name self.connect(in_node, in_node_out, node, node_in) # Connect iterator inputs for iterator, conns in self._iterator_conns.items(): # Check to see if this is the right frequency for the iterator # input, i.e. if it is the only iterator for this frequency if self.study.FREQUENCIES[frequency] == (iterator,): for (node, node_in, format) in conns: # @ReservedAssignment self.connect(inputnode, iterator, node, node_in) return inputnode
python
def _make_inputnode(self, frequency): """ Generates an input node for the given frequency. It also adds implicit file format conversion nodes to the pipeline. Parameters ---------- frequency : str The frequency (i.e. 'per_session', 'per_visit', 'per_subject' or 'per_study') of the input node to retrieve """ # Check to see whether there are any outputs for the given frequency inputs = list(self.frequency_inputs(frequency)) # Get list of input names for the requested frequency, addding fields # to hold iterator IDs input_names = [i.name for i in inputs] input_names.extend(self.study.FREQUENCIES[frequency]) if not input_names: raise ArcanaError( "No inputs to '{}' pipeline for requested freqency '{}'" .format(self.name, frequency)) # Generate input node and connect it to appropriate nodes inputnode = self.add('{}_inputnode'.format(frequency), IdentityInterface(fields=input_names)) # Loop through list of nodes connected to study data specs and # connect them to the newly created input node for input in inputs: # @ReservedAssignment # Keep track of previous conversion nodes to avoid replicating the # conversion for inputs that are used in multiple places prev_conv_nodes = {} for (node, node_in, format, # @ReservedAssignment @IgnorePep8 conv_kwargs) in self._input_conns[input.name]: # If fileset formats differ between study and pipeline # inputs create converter node (if one hasn't been already) # and connect input to that before connecting to inputnode if self.requires_conversion(input, format): try: conv = format.converter_from(input.format, **conv_kwargs) except ArcanaNoConverterError as e: e.msg += ( "which is required to convert '{}' from {} to {} " "for '{}' input of '{}' node".format( input.name, input.format, format, node_in, node.name)) raise e try: in_node = prev_conv_nodes[format.name] except KeyError: in_node = prev_conv_nodes[format.name] = self.add( 'conv_{}_to_{}_format'.format(input.name, format.name), conv.interface, inputs={conv.input: (inputnode, input.name)}, requirements=conv.requirements, mem_gb=conv.mem_gb, wall_time=conv.wall_time) in_node_out = conv.output else: in_node = inputnode in_node_out = input.name self.connect(in_node, in_node_out, node, node_in) # Connect iterator inputs for iterator, conns in self._iterator_conns.items(): # Check to see if this is the right frequency for the iterator # input, i.e. if it is the only iterator for this frequency if self.study.FREQUENCIES[frequency] == (iterator,): for (node, node_in, format) in conns: # @ReservedAssignment self.connect(inputnode, iterator, node, node_in) return inputnode
[ "def", "_make_inputnode", "(", "self", ",", "frequency", ")", ":", "# Check to see whether there are any outputs for the given frequency", "inputs", "=", "list", "(", "self", ".", "frequency_inputs", "(", "frequency", ")", ")", "# Get list of input names for the requested fre...
Generates an input node for the given frequency. It also adds implicit file format conversion nodes to the pipeline. Parameters ---------- frequency : str The frequency (i.e. 'per_session', 'per_visit', 'per_subject' or 'per_study') of the input node to retrieve
[ "Generates", "an", "input", "node", "for", "the", "given", "frequency", ".", "It", "also", "adds", "implicit", "file", "format", "conversion", "nodes", "to", "the", "pipeline", "." ]
d6271a29d13733d00422d11417af8d200be62acc
https://github.com/MonashBI/arcana/blob/d6271a29d13733d00422d11417af8d200be62acc/arcana/pipeline/base.py#L712-L781
train
51,700
MonashBI/arcana
arcana/pipeline/base.py
Pipeline._make_outputnode
def _make_outputnode(self, frequency): """ Generates an output node for the given frequency. It also adds implicit file format conversion nodes to the pipeline. Parameters ---------- frequency : str The frequency (i.e. 'per_session', 'per_visit', 'per_subject' or 'per_study') of the output node to retrieve """ # Check to see whether there are any outputs for the given frequency outputs = list(self.frequency_outputs(frequency)) if not outputs: raise ArcanaError( "No outputs to '{}' pipeline for requested freqency '{}'" .format(self.name, frequency)) # Get list of output names for the requested frequency, addding fields # to hold iterator IDs output_names = [o.name for o in outputs] # Generate output node and connect it to appropriate nodes outputnode = self.add('{}_outputnode'.format(frequency), IdentityInterface(fields=output_names)) # Loop through list of nodes connected to study data specs and # connect them to the newly created output node for output in outputs: # @ReservedAssignment (node, node_out, format, # @ReservedAssignment @IgnorePep8 conv_kwargs) = self._output_conns[output.name] # If fileset formats differ between study and pipeline # outputs create converter node (if one hasn't been already) # and connect output to that before connecting to outputnode if self.requires_conversion(output, format): conv = output.format.converter_from(format, **conv_kwargs) node = self.add( 'conv_{}_from_{}_format'.format(output.name, format.name), conv.interface, inputs={conv.input: (node, node_out)}, requirements=conv.requirements, mem_gb=conv.mem_gb, wall_time=conv.wall_time) node_out = conv.output self.connect(node, node_out, outputnode, output.name) return outputnode
python
def _make_outputnode(self, frequency): """ Generates an output node for the given frequency. It also adds implicit file format conversion nodes to the pipeline. Parameters ---------- frequency : str The frequency (i.e. 'per_session', 'per_visit', 'per_subject' or 'per_study') of the output node to retrieve """ # Check to see whether there are any outputs for the given frequency outputs = list(self.frequency_outputs(frequency)) if not outputs: raise ArcanaError( "No outputs to '{}' pipeline for requested freqency '{}'" .format(self.name, frequency)) # Get list of output names for the requested frequency, addding fields # to hold iterator IDs output_names = [o.name for o in outputs] # Generate output node and connect it to appropriate nodes outputnode = self.add('{}_outputnode'.format(frequency), IdentityInterface(fields=output_names)) # Loop through list of nodes connected to study data specs and # connect them to the newly created output node for output in outputs: # @ReservedAssignment (node, node_out, format, # @ReservedAssignment @IgnorePep8 conv_kwargs) = self._output_conns[output.name] # If fileset formats differ between study and pipeline # outputs create converter node (if one hasn't been already) # and connect output to that before connecting to outputnode if self.requires_conversion(output, format): conv = output.format.converter_from(format, **conv_kwargs) node = self.add( 'conv_{}_from_{}_format'.format(output.name, format.name), conv.interface, inputs={conv.input: (node, node_out)}, requirements=conv.requirements, mem_gb=conv.mem_gb, wall_time=conv.wall_time) node_out = conv.output self.connect(node, node_out, outputnode, output.name) return outputnode
[ "def", "_make_outputnode", "(", "self", ",", "frequency", ")", ":", "# Check to see whether there are any outputs for the given frequency", "outputs", "=", "list", "(", "self", ".", "frequency_outputs", "(", "frequency", ")", ")", "if", "not", "outputs", ":", "raise",...
Generates an output node for the given frequency. It also adds implicit file format conversion nodes to the pipeline. Parameters ---------- frequency : str The frequency (i.e. 'per_session', 'per_visit', 'per_subject' or 'per_study') of the output node to retrieve
[ "Generates", "an", "output", "node", "for", "the", "given", "frequency", ".", "It", "also", "adds", "implicit", "file", "format", "conversion", "nodes", "to", "the", "pipeline", "." ]
d6271a29d13733d00422d11417af8d200be62acc
https://github.com/MonashBI/arcana/blob/d6271a29d13733d00422d11417af8d200be62acc/arcana/pipeline/base.py#L783-L825
train
51,701
MonashBI/arcana
arcana/pipeline/base.py
Pipeline._gen_prov
def _gen_prov(self): """ Extracts provenance information from the pipeline into a PipelineProv object Returns ------- prov : dict[str, *] A dictionary containing the provenance information to record for the pipeline """ # Export worfklow graph to node-link data format wf_dict = nx_json.node_link_data(self.workflow._graph) # Replace references to Node objects with the node's provenance # information and convert to a dict organised by node name to allow it # to be compared more easily. Also change link node-references from # node index to node ID so it is not dependent on the order the nodes # are written to the dictionary (which for Python < 3.7 is guaranteed # to be the same between identical runs) for link in wf_dict['links']: if int(networkx_version.split('.')[0]) < 2: # @UndefinedVariable link['source'] = wf_dict['nodes'][link['source']]['id'].name link['target'] = wf_dict['nodes'][link['target']]['id'].name else: link['source'] = link['source'].name link['target'] = link['target'].name wf_dict['nodes'] = {n['id'].name: n['id'].prov for n in wf_dict['nodes']} # Roundtrip to JSON to convert any tuples into lists so dictionaries # can be compared directly wf_dict = json.loads(json.dumps(wf_dict)) dependency_versions = {d: extract_package_version(d) for d in ARCANA_DEPENDENCIES} pkg_versions = {'arcana': __version__} pkg_versions.update((k, v) for k, v in dependency_versions.items() if v is not None) prov = { '__prov_version__': PROVENANCE_VERSION, 'name': self.name, 'workflow': wf_dict, 'study': self.study.prov, 'pkg_versions': pkg_versions, 'python_version': sys.version, 'joined_ids': self._joined_ids()} return prov
python
def _gen_prov(self): """ Extracts provenance information from the pipeline into a PipelineProv object Returns ------- prov : dict[str, *] A dictionary containing the provenance information to record for the pipeline """ # Export worfklow graph to node-link data format wf_dict = nx_json.node_link_data(self.workflow._graph) # Replace references to Node objects with the node's provenance # information and convert to a dict organised by node name to allow it # to be compared more easily. Also change link node-references from # node index to node ID so it is not dependent on the order the nodes # are written to the dictionary (which for Python < 3.7 is guaranteed # to be the same between identical runs) for link in wf_dict['links']: if int(networkx_version.split('.')[0]) < 2: # @UndefinedVariable link['source'] = wf_dict['nodes'][link['source']]['id'].name link['target'] = wf_dict['nodes'][link['target']]['id'].name else: link['source'] = link['source'].name link['target'] = link['target'].name wf_dict['nodes'] = {n['id'].name: n['id'].prov for n in wf_dict['nodes']} # Roundtrip to JSON to convert any tuples into lists so dictionaries # can be compared directly wf_dict = json.loads(json.dumps(wf_dict)) dependency_versions = {d: extract_package_version(d) for d in ARCANA_DEPENDENCIES} pkg_versions = {'arcana': __version__} pkg_versions.update((k, v) for k, v in dependency_versions.items() if v is not None) prov = { '__prov_version__': PROVENANCE_VERSION, 'name': self.name, 'workflow': wf_dict, 'study': self.study.prov, 'pkg_versions': pkg_versions, 'python_version': sys.version, 'joined_ids': self._joined_ids()} return prov
[ "def", "_gen_prov", "(", "self", ")", ":", "# Export worfklow graph to node-link data format", "wf_dict", "=", "nx_json", ".", "node_link_data", "(", "self", ".", "workflow", ".", "_graph", ")", "# Replace references to Node objects with the node's provenance", "# information...
Extracts provenance information from the pipeline into a PipelineProv object Returns ------- prov : dict[str, *] A dictionary containing the provenance information to record for the pipeline
[ "Extracts", "provenance", "information", "from", "the", "pipeline", "into", "a", "PipelineProv", "object" ]
d6271a29d13733d00422d11417af8d200be62acc
https://github.com/MonashBI/arcana/blob/d6271a29d13733d00422d11417af8d200be62acc/arcana/pipeline/base.py#L827-L871
train
51,702
MonashBI/arcana
arcana/pipeline/base.py
Pipeline.expected_record
def expected_record(self, node): """ Constructs the provenance record that would be saved in the given node if the pipeline was run on the current state of the repository Parameters ---------- node : arcana.repository.tree.TreeNode A node of the Tree representation of the study data stored in the repository (i.e. a Session, Visit, Subject or Tree node) Returns ------- expected_record : arcana.provenance.Record The record that would be produced if the pipeline is run over the study tree. """ exp_inputs = {} # Get checksums/values of all inputs that would have been used in # previous runs of an equivalent pipeline to compare with that saved # in provenance to see if any have been updated. for inpt in self.inputs: # @ReservedAssignment # Get iterators present in the input that aren't in this node # and need to be joined iterators_to_join = (self.iterators(inpt.frequency) - self.iterators(node.frequency)) if not iterators_to_join: # No iterators to join so we can just extract the checksums # of the corresponding input exp_inputs[inpt.name] = inpt.collection.item( node.subject_id, node.visit_id).checksums elif len(iterators_to_join) == 1: # Get list of checksums dicts for each node of the input # frequency that relates to the current node exp_inputs[inpt.name] = [ inpt.collection.item(n.subject_id, n.visit_id).checksums for n in node.nodes(inpt.frequency)] else: # In the case where the node is the whole treee and the input # is per_seession, we need to create a list of lists to match # how the checksums are joined in the processor exp_inputs[inpt.name] = [] for subj in node.subjects: exp_inputs[inpt.name].append([ inpt.collection.item(s.subject_id, s.visit_id).checksums for s in subj.sessions]) # Get checksums/value for all outputs of the pipeline. We are assuming # that they exist here (otherwise they will be None) exp_outputs = { o.name: o.collection.item(node.subject_id, node.visit_id).checksums for o in self.outputs} exp_prov = copy(self.prov) if PY2: # Need to convert to unicode strings for Python 2 exp_inputs = json.loads(json.dumps(exp_inputs)) exp_outputs = json.loads(json.dumps(exp_outputs)) exp_prov['inputs'] = exp_inputs exp_prov['outputs'] = exp_outputs exp_prov['joined_ids'] = self._joined_ids() return Record( self.name, node.frequency, node.subject_id, node.visit_id, self.study.name, exp_prov)
python
def expected_record(self, node): """ Constructs the provenance record that would be saved in the given node if the pipeline was run on the current state of the repository Parameters ---------- node : arcana.repository.tree.TreeNode A node of the Tree representation of the study data stored in the repository (i.e. a Session, Visit, Subject or Tree node) Returns ------- expected_record : arcana.provenance.Record The record that would be produced if the pipeline is run over the study tree. """ exp_inputs = {} # Get checksums/values of all inputs that would have been used in # previous runs of an equivalent pipeline to compare with that saved # in provenance to see if any have been updated. for inpt in self.inputs: # @ReservedAssignment # Get iterators present in the input that aren't in this node # and need to be joined iterators_to_join = (self.iterators(inpt.frequency) - self.iterators(node.frequency)) if not iterators_to_join: # No iterators to join so we can just extract the checksums # of the corresponding input exp_inputs[inpt.name] = inpt.collection.item( node.subject_id, node.visit_id).checksums elif len(iterators_to_join) == 1: # Get list of checksums dicts for each node of the input # frequency that relates to the current node exp_inputs[inpt.name] = [ inpt.collection.item(n.subject_id, n.visit_id).checksums for n in node.nodes(inpt.frequency)] else: # In the case where the node is the whole treee and the input # is per_seession, we need to create a list of lists to match # how the checksums are joined in the processor exp_inputs[inpt.name] = [] for subj in node.subjects: exp_inputs[inpt.name].append([ inpt.collection.item(s.subject_id, s.visit_id).checksums for s in subj.sessions]) # Get checksums/value for all outputs of the pipeline. We are assuming # that they exist here (otherwise they will be None) exp_outputs = { o.name: o.collection.item(node.subject_id, node.visit_id).checksums for o in self.outputs} exp_prov = copy(self.prov) if PY2: # Need to convert to unicode strings for Python 2 exp_inputs = json.loads(json.dumps(exp_inputs)) exp_outputs = json.loads(json.dumps(exp_outputs)) exp_prov['inputs'] = exp_inputs exp_prov['outputs'] = exp_outputs exp_prov['joined_ids'] = self._joined_ids() return Record( self.name, node.frequency, node.subject_id, node.visit_id, self.study.name, exp_prov)
[ "def", "expected_record", "(", "self", ",", "node", ")", ":", "exp_inputs", "=", "{", "}", "# Get checksums/values of all inputs that would have been used in", "# previous runs of an equivalent pipeline to compare with that saved", "# in provenance to see if any have been updated.", "f...
Constructs the provenance record that would be saved in the given node if the pipeline was run on the current state of the repository Parameters ---------- node : arcana.repository.tree.TreeNode A node of the Tree representation of the study data stored in the repository (i.e. a Session, Visit, Subject or Tree node) Returns ------- expected_record : arcana.provenance.Record The record that would be produced if the pipeline is run over the study tree.
[ "Constructs", "the", "provenance", "record", "that", "would", "be", "saved", "in", "the", "given", "node", "if", "the", "pipeline", "was", "run", "on", "the", "current", "state", "of", "the", "repository" ]
d6271a29d13733d00422d11417af8d200be62acc
https://github.com/MonashBI/arcana/blob/d6271a29d13733d00422d11417af8d200be62acc/arcana/pipeline/base.py#L873-L935
train
51,703
MonashBI/arcana
arcana/repository/base.py
Repository.tree
def tree(self, subject_ids=None, visit_ids=None, **kwargs): """ Return the tree of subject and sessions information within a project in the XNAT repository Parameters ---------- subject_ids : list(str) List of subject IDs with which to filter the tree with. If None all are returned visit_ids : list(str) List of visit IDs with which to filter the tree with. If None all are returned Returns ------- tree : arcana.repository.Tree A hierarchical tree of subject, session and fileset information for the repository """ # Find all data present in the repository (filtered by the passed IDs) return Tree.construct( self, *self.find_data(subject_ids=subject_ids, visit_ids=visit_ids), **kwargs)
python
def tree(self, subject_ids=None, visit_ids=None, **kwargs): """ Return the tree of subject and sessions information within a project in the XNAT repository Parameters ---------- subject_ids : list(str) List of subject IDs with which to filter the tree with. If None all are returned visit_ids : list(str) List of visit IDs with which to filter the tree with. If None all are returned Returns ------- tree : arcana.repository.Tree A hierarchical tree of subject, session and fileset information for the repository """ # Find all data present in the repository (filtered by the passed IDs) return Tree.construct( self, *self.find_data(subject_ids=subject_ids, visit_ids=visit_ids), **kwargs)
[ "def", "tree", "(", "self", ",", "subject_ids", "=", "None", ",", "visit_ids", "=", "None", ",", "*", "*", "kwargs", ")", ":", "# Find all data present in the repository (filtered by the passed IDs)", "return", "Tree", ".", "construct", "(", "self", ",", "*", "s...
Return the tree of subject and sessions information within a project in the XNAT repository Parameters ---------- subject_ids : list(str) List of subject IDs with which to filter the tree with. If None all are returned visit_ids : list(str) List of visit IDs with which to filter the tree with. If None all are returned Returns ------- tree : arcana.repository.Tree A hierarchical tree of subject, session and fileset information for the repository
[ "Return", "the", "tree", "of", "subject", "and", "sessions", "information", "within", "a", "project", "in", "the", "XNAT", "repository" ]
d6271a29d13733d00422d11417af8d200be62acc
https://github.com/MonashBI/arcana/blob/d6271a29d13733d00422d11417af8d200be62acc/arcana/repository/base.py#L167-L190
train
51,704
MonashBI/arcana
arcana/repository/base.py
Repository.cached_tree
def cached_tree(self, subject_ids=None, visit_ids=None, fill=False): """ Access the repository tree and caches it for subsequent accesses Parameters ---------- subject_ids : list(str) List of subject IDs with which to filter the tree with. If None all are returned visit_ids : list(str) List of visit IDs with which to filter the tree with. If None all are returned fill : bool Create empty sessions for any that are missing in the subject_id x visit_id block. Typically only used if all the inputs to the study are coming from different repositories to the one that the derived products are stored in Returns ------- tree : arcana.repository.Tree A hierarchical tree of subject, vist, session information and that of the filesets and fields they contain """ if subject_ids is not None: subject_ids = frozenset(subject_ids) if visit_ids is not None: visit_ids = frozenset(visit_ids) try: tree = self._cache[subject_ids][visit_ids] except KeyError: if fill: fill_subjects = subject_ids fill_visits = visit_ids else: fill_subjects = fill_visits = None tree = self.tree( subject_ids=subject_ids, visit_ids=visit_ids, fill_visits=fill_visits, fill_subjects=fill_subjects) # Save the tree within the cache under the given subject/ # visit ID filters and the IDs that were actually returned self._cache[subject_ids][visit_ids] = self._cache[ frozenset(tree.subject_ids)][frozenset(tree.visit_ids)] = tree return tree
python
def cached_tree(self, subject_ids=None, visit_ids=None, fill=False): """ Access the repository tree and caches it for subsequent accesses Parameters ---------- subject_ids : list(str) List of subject IDs with which to filter the tree with. If None all are returned visit_ids : list(str) List of visit IDs with which to filter the tree with. If None all are returned fill : bool Create empty sessions for any that are missing in the subject_id x visit_id block. Typically only used if all the inputs to the study are coming from different repositories to the one that the derived products are stored in Returns ------- tree : arcana.repository.Tree A hierarchical tree of subject, vist, session information and that of the filesets and fields they contain """ if subject_ids is not None: subject_ids = frozenset(subject_ids) if visit_ids is not None: visit_ids = frozenset(visit_ids) try: tree = self._cache[subject_ids][visit_ids] except KeyError: if fill: fill_subjects = subject_ids fill_visits = visit_ids else: fill_subjects = fill_visits = None tree = self.tree( subject_ids=subject_ids, visit_ids=visit_ids, fill_visits=fill_visits, fill_subjects=fill_subjects) # Save the tree within the cache under the given subject/ # visit ID filters and the IDs that were actually returned self._cache[subject_ids][visit_ids] = self._cache[ frozenset(tree.subject_ids)][frozenset(tree.visit_ids)] = tree return tree
[ "def", "cached_tree", "(", "self", ",", "subject_ids", "=", "None", ",", "visit_ids", "=", "None", ",", "fill", "=", "False", ")", ":", "if", "subject_ids", "is", "not", "None", ":", "subject_ids", "=", "frozenset", "(", "subject_ids", ")", "if", "visit_...
Access the repository tree and caches it for subsequent accesses Parameters ---------- subject_ids : list(str) List of subject IDs with which to filter the tree with. If None all are returned visit_ids : list(str) List of visit IDs with which to filter the tree with. If None all are returned fill : bool Create empty sessions for any that are missing in the subject_id x visit_id block. Typically only used if all the inputs to the study are coming from different repositories to the one that the derived products are stored in Returns ------- tree : arcana.repository.Tree A hierarchical tree of subject, vist, session information and that of the filesets and fields they contain
[ "Access", "the", "repository", "tree", "and", "caches", "it", "for", "subsequent", "accesses" ]
d6271a29d13733d00422d11417af8d200be62acc
https://github.com/MonashBI/arcana/blob/d6271a29d13733d00422d11417af8d200be62acc/arcana/repository/base.py#L192-L236
train
51,705
MonashBI/arcana
arcana/data/file_format.py
FileFormat.resource_names
def resource_names(self, repo_type): """ Names of resources used to store the format on a given repository type. Defaults to the name of the name of the format """ try: names = self._resource_names[repo_type] except KeyError: names = [self.name, self.name.upper()] return names
python
def resource_names(self, repo_type): """ Names of resources used to store the format on a given repository type. Defaults to the name of the name of the format """ try: names = self._resource_names[repo_type] except KeyError: names = [self.name, self.name.upper()] return names
[ "def", "resource_names", "(", "self", ",", "repo_type", ")", ":", "try", ":", "names", "=", "self", ".", "_resource_names", "[", "repo_type", "]", "except", "KeyError", ":", "names", "=", "[", "self", ".", "name", ",", "self", ".", "name", ".", "upper"...
Names of resources used to store the format on a given repository type. Defaults to the name of the name of the format
[ "Names", "of", "resources", "used", "to", "store", "the", "format", "on", "a", "given", "repository", "type", ".", "Defaults", "to", "the", "name", "of", "the", "name", "of", "the", "format" ]
d6271a29d13733d00422d11417af8d200be62acc
https://github.com/MonashBI/arcana/blob/d6271a29d13733d00422d11417af8d200be62acc/arcana/data/file_format.py#L150-L159
train
51,706
MonashBI/arcana
arcana/data/file_format.py
FileFormat.default_aux_file_paths
def default_aux_file_paths(self, primary_path): """ Get the default paths for auxiliary files relative to the path of the primary file, i.e. the same name as the primary path with a different extension Parameters ---------- primary_path : str Path to the primary file in the fileset Returns ------- aux_paths : dict[str, str] A dictionary of auxiliary file names and default paths """ return dict((n, primary_path[:-len(self.ext)] + ext) for n, ext in self.aux_files.items())
python
def default_aux_file_paths(self, primary_path): """ Get the default paths for auxiliary files relative to the path of the primary file, i.e. the same name as the primary path with a different extension Parameters ---------- primary_path : str Path to the primary file in the fileset Returns ------- aux_paths : dict[str, str] A dictionary of auxiliary file names and default paths """ return dict((n, primary_path[:-len(self.ext)] + ext) for n, ext in self.aux_files.items())
[ "def", "default_aux_file_paths", "(", "self", ",", "primary_path", ")", ":", "return", "dict", "(", "(", "n", ",", "primary_path", "[", ":", "-", "len", "(", "self", ".", "ext", ")", "]", "+", "ext", ")", "for", "n", ",", "ext", "in", "self", ".", ...
Get the default paths for auxiliary files relative to the path of the primary file, i.e. the same name as the primary path with a different extension Parameters ---------- primary_path : str Path to the primary file in the fileset Returns ------- aux_paths : dict[str, str] A dictionary of auxiliary file names and default paths
[ "Get", "the", "default", "paths", "for", "auxiliary", "files", "relative", "to", "the", "path", "of", "the", "primary", "file", "i", ".", "e", ".", "the", "same", "name", "as", "the", "primary", "path", "with", "a", "different", "extension" ]
d6271a29d13733d00422d11417af8d200be62acc
https://github.com/MonashBI/arcana/blob/d6271a29d13733d00422d11417af8d200be62acc/arcana/data/file_format.py#L161-L178
train
51,707
MonashBI/arcana
arcana/data/file_format.py
FileFormat.matches
def matches(self, fileset): """ Checks to see whether the format matches the given fileset Parameters ---------- fileset : Fileset The fileset to check """ if fileset._resource_name is not None: return (fileset._resource_name in self.resource_names( fileset.repository.type)) elif self.directory: if op.isdir(fileset.path): if self.within_dir_exts is None: return True else: # Get set of all extensions in the directory return self.within_dir_exts == frozenset( split_extension(f)[1] for f in os.listdir(fileset.path) if not f.startswith('.')) else: return False else: if op.isfile(fileset.path): all_paths = [fileset.path] + fileset._potential_aux_files try: primary_path = self.assort_files(all_paths)[0] except ArcanaFileFormatError: return False else: return primary_path == fileset.path else: return False
python
def matches(self, fileset): """ Checks to see whether the format matches the given fileset Parameters ---------- fileset : Fileset The fileset to check """ if fileset._resource_name is not None: return (fileset._resource_name in self.resource_names( fileset.repository.type)) elif self.directory: if op.isdir(fileset.path): if self.within_dir_exts is None: return True else: # Get set of all extensions in the directory return self.within_dir_exts == frozenset( split_extension(f)[1] for f in os.listdir(fileset.path) if not f.startswith('.')) else: return False else: if op.isfile(fileset.path): all_paths = [fileset.path] + fileset._potential_aux_files try: primary_path = self.assort_files(all_paths)[0] except ArcanaFileFormatError: return False else: return primary_path == fileset.path else: return False
[ "def", "matches", "(", "self", ",", "fileset", ")", ":", "if", "fileset", ".", "_resource_name", "is", "not", "None", ":", "return", "(", "fileset", ".", "_resource_name", "in", "self", ".", "resource_names", "(", "fileset", ".", "repository", ".", "type",...
Checks to see whether the format matches the given fileset Parameters ---------- fileset : Fileset The fileset to check
[ "Checks", "to", "see", "whether", "the", "format", "matches", "the", "given", "fileset" ]
d6271a29d13733d00422d11417af8d200be62acc
https://github.com/MonashBI/arcana/blob/d6271a29d13733d00422d11417af8d200be62acc/arcana/data/file_format.py#L269-L302
train
51,708
MonashBI/arcana
arcana/data/file_format.py
FileFormat.set_converter
def set_converter(self, file_format, converter): """ Register a Converter and the FileFormat that it is able to convert from Parameters ---------- converter : Converter The converter to register file_format : FileFormat The file format that can be converted into this format """ self._converters[file_format.name] = (file_format, converter)
python
def set_converter(self, file_format, converter): """ Register a Converter and the FileFormat that it is able to convert from Parameters ---------- converter : Converter The converter to register file_format : FileFormat The file format that can be converted into this format """ self._converters[file_format.name] = (file_format, converter)
[ "def", "set_converter", "(", "self", ",", "file_format", ",", "converter", ")", ":", "self", ".", "_converters", "[", "file_format", ".", "name", "]", "=", "(", "file_format", ",", "converter", ")" ]
Register a Converter and the FileFormat that it is able to convert from Parameters ---------- converter : Converter The converter to register file_format : FileFormat The file format that can be converted into this format
[ "Register", "a", "Converter", "and", "the", "FileFormat", "that", "it", "is", "able", "to", "convert", "from" ]
d6271a29d13733d00422d11417af8d200be62acc
https://github.com/MonashBI/arcana/blob/d6271a29d13733d00422d11417af8d200be62acc/arcana/data/file_format.py#L304-L315
train
51,709
gwww/elkm1
elkm1_lib/util.py
parse_url
def parse_url(url): """Parse a Elk connection string """ scheme, dest = url.split('://') host = None ssl_context = None if scheme == 'elk': host, port = dest.split(':') if ':' in dest else (dest, 2101) elif scheme == 'elks': host, port = dest.split(':') if ':' in dest else (dest, 2601) ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLSv1) ssl_context.verify_mode = ssl.CERT_NONE elif scheme == 'serial': host, port = dest.split(':') if ':' in dest else (dest, 115200) else: raise ValueError("Invalid scheme '%s'" % scheme) return (scheme, host, int(port), ssl_context)
python
def parse_url(url): """Parse a Elk connection string """ scheme, dest = url.split('://') host = None ssl_context = None if scheme == 'elk': host, port = dest.split(':') if ':' in dest else (dest, 2101) elif scheme == 'elks': host, port = dest.split(':') if ':' in dest else (dest, 2601) ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLSv1) ssl_context.verify_mode = ssl.CERT_NONE elif scheme == 'serial': host, port = dest.split(':') if ':' in dest else (dest, 115200) else: raise ValueError("Invalid scheme '%s'" % scheme) return (scheme, host, int(port), ssl_context)
[ "def", "parse_url", "(", "url", ")", ":", "scheme", ",", "dest", "=", "url", ".", "split", "(", "'://'", ")", "host", "=", "None", "ssl_context", "=", "None", "if", "scheme", "==", "'elk'", ":", "host", ",", "port", "=", "dest", ".", "split", "(", ...
Parse a Elk connection string
[ "Parse", "a", "Elk", "connection", "string" ]
078d0de30840c3fab46f1f8534d98df557931e91
https://github.com/gwww/elkm1/blob/078d0de30840c3fab46f1f8534d98df557931e91/elkm1_lib/util.py#L14-L29
train
51,710
gwww/elkm1
elkm1_lib/util.py
pretty_const
def pretty_const(value): """Make a constant pretty for printing in GUI""" words = value.split('_') pretty = words[0].capitalize() for word in words[1:]: pretty += ' ' + word.lower() return pretty
python
def pretty_const(value): """Make a constant pretty for printing in GUI""" words = value.split('_') pretty = words[0].capitalize() for word in words[1:]: pretty += ' ' + word.lower() return pretty
[ "def", "pretty_const", "(", "value", ")", ":", "words", "=", "value", ".", "split", "(", "'_'", ")", "pretty", "=", "words", "[", "0", "]", ".", "capitalize", "(", ")", "for", "word", "in", "words", "[", "1", ":", "]", ":", "pretty", "+=", "' '",...
Make a constant pretty for printing in GUI
[ "Make", "a", "constant", "pretty", "for", "printing", "in", "GUI" ]
078d0de30840c3fab46f1f8534d98df557931e91
https://github.com/gwww/elkm1/blob/078d0de30840c3fab46f1f8534d98df557931e91/elkm1_lib/util.py#L32-L38
train
51,711
gwww/elkm1
elkm1_lib/util.py
username
def username(elk, user_number): """Return name of user.""" if user_number >= 0 and user_number < elk.users.max_elements: return elk.users[user_number].name if user_number == 201: return "*Program*" if user_number == 202: return "*Elk RP*" if user_number == 203: return "*Quick arm*" return ""
python
def username(elk, user_number): """Return name of user.""" if user_number >= 0 and user_number < elk.users.max_elements: return elk.users[user_number].name if user_number == 201: return "*Program*" if user_number == 202: return "*Elk RP*" if user_number == 203: return "*Quick arm*" return ""
[ "def", "username", "(", "elk", ",", "user_number", ")", ":", "if", "user_number", ">=", "0", "and", "user_number", "<", "elk", ".", "users", ".", "max_elements", ":", "return", "elk", ".", "users", "[", "user_number", "]", ".", "name", "if", "user_number...
Return name of user.
[ "Return", "name", "of", "user", "." ]
078d0de30840c3fab46f1f8534d98df557931e91
https://github.com/gwww/elkm1/blob/078d0de30840c3fab46f1f8534d98df557931e91/elkm1_lib/util.py#L40-L50
train
51,712
gwww/elkm1
elkm1_lib/elk.py
Elk._connect
async def _connect(self, connection_lost_callbk=None): """Asyncio connection to Elk.""" self.connection_lost_callbk = connection_lost_callbk url = self._config['url'] LOG.info("Connecting to ElkM1 at %s", url) scheme, dest, param, ssl_context = parse_url(url) conn = partial(Connection, self.loop, self._connected, self._disconnected, self._got_data, self._timeout) try: if scheme == 'serial': await serial_asyncio.create_serial_connection( self.loop, conn, dest, baudrate=param) else: await asyncio.wait_for(self.loop.create_connection( conn, host=dest, port=param, ssl=ssl_context), timeout=30) except (ValueError, OSError, asyncio.TimeoutError) as err: LOG.warning("Could not connect to ElkM1 (%s). Retrying in %d seconds", err, self._connection_retry_timer) self.loop.call_later(self._connection_retry_timer, self.connect) self._connection_retry_timer = 2 * self._connection_retry_timer \ if self._connection_retry_timer < 32 else 60
python
async def _connect(self, connection_lost_callbk=None): """Asyncio connection to Elk.""" self.connection_lost_callbk = connection_lost_callbk url = self._config['url'] LOG.info("Connecting to ElkM1 at %s", url) scheme, dest, param, ssl_context = parse_url(url) conn = partial(Connection, self.loop, self._connected, self._disconnected, self._got_data, self._timeout) try: if scheme == 'serial': await serial_asyncio.create_serial_connection( self.loop, conn, dest, baudrate=param) else: await asyncio.wait_for(self.loop.create_connection( conn, host=dest, port=param, ssl=ssl_context), timeout=30) except (ValueError, OSError, asyncio.TimeoutError) as err: LOG.warning("Could not connect to ElkM1 (%s). Retrying in %d seconds", err, self._connection_retry_timer) self.loop.call_later(self._connection_retry_timer, self.connect) self._connection_retry_timer = 2 * self._connection_retry_timer \ if self._connection_retry_timer < 32 else 60
[ "async", "def", "_connect", "(", "self", ",", "connection_lost_callbk", "=", "None", ")", ":", "self", ".", "connection_lost_callbk", "=", "connection_lost_callbk", "url", "=", "self", ".", "_config", "[", "'url'", "]", "LOG", ".", "info", "(", "\"Connecting t...
Asyncio connection to Elk.
[ "Asyncio", "connection", "to", "Elk", "." ]
078d0de30840c3fab46f1f8534d98df557931e91
https://github.com/gwww/elkm1/blob/078d0de30840c3fab46f1f8534d98df557931e91/elkm1_lib/elk.py#L50-L70
train
51,713
gwww/elkm1
elkm1_lib/elk.py
Elk._connected
def _connected(self, transport, conn): """Login and sync the ElkM1 panel to memory.""" LOG.info("Connected to ElkM1") self._conn = conn self._transport = transport self._connection_retry_timer = 1 if url_scheme_is_secure(self._config['url']): self._conn.write_data(self._config['userid'], raw=True) self._conn.write_data(self._config['password'], raw=True) self.call_sync_handlers() if not self._config['url'].startswith('serial://'): self._heartbeat = self.loop.call_later(120, self._reset_connection)
python
def _connected(self, transport, conn): """Login and sync the ElkM1 panel to memory.""" LOG.info("Connected to ElkM1") self._conn = conn self._transport = transport self._connection_retry_timer = 1 if url_scheme_is_secure(self._config['url']): self._conn.write_data(self._config['userid'], raw=True) self._conn.write_data(self._config['password'], raw=True) self.call_sync_handlers() if not self._config['url'].startswith('serial://'): self._heartbeat = self.loop.call_later(120, self._reset_connection)
[ "def", "_connected", "(", "self", ",", "transport", ",", "conn", ")", ":", "LOG", ".", "info", "(", "\"Connected to ElkM1\"", ")", "self", ".", "_conn", "=", "conn", "self", ".", "_transport", "=", "transport", "self", ".", "_connection_retry_timer", "=", ...
Login and sync the ElkM1 panel to memory.
[ "Login", "and", "sync", "the", "ElkM1", "panel", "to", "memory", "." ]
078d0de30840c3fab46f1f8534d98df557931e91
https://github.com/gwww/elkm1/blob/078d0de30840c3fab46f1f8534d98df557931e91/elkm1_lib/elk.py#L72-L83
train
51,714
gwww/elkm1
elkm1_lib/elk.py
Elk.send
def send(self, msg): """Send a message to Elk panel.""" if self._conn: self._conn.write_data(msg.message, msg.response_command)
python
def send(self, msg): """Send a message to Elk panel.""" if self._conn: self._conn.write_data(msg.message, msg.response_command)
[ "def", "send", "(", "self", ",", "msg", ")", ":", "if", "self", ".", "_conn", ":", "self", ".", "_conn", ".", "write_data", "(", "msg", ".", "message", ",", "msg", ".", "response_command", ")" ]
Send a message to Elk panel.
[ "Send", "a", "message", "to", "Elk", "panel", "." ]
078d0de30840c3fab46f1f8534d98df557931e91
https://github.com/gwww/elkm1/blob/078d0de30840c3fab46f1f8534d98df557931e91/elkm1_lib/elk.py#L156-L159
train
51,715
gwww/elkm1
elkm1_lib/zones.py
Zones.sync
def sync(self): """Retrieve zones from ElkM1""" self.elk.send(az_encode()) self.elk.send(zd_encode()) self.elk.send(zp_encode()) self.elk.send(zs_encode()) self.get_descriptions(TextDescriptions.ZONE.value)
python
def sync(self): """Retrieve zones from ElkM1""" self.elk.send(az_encode()) self.elk.send(zd_encode()) self.elk.send(zp_encode()) self.elk.send(zs_encode()) self.get_descriptions(TextDescriptions.ZONE.value)
[ "def", "sync", "(", "self", ")", ":", "self", ".", "elk", ".", "send", "(", "az_encode", "(", ")", ")", "self", ".", "elk", ".", "send", "(", "zd_encode", "(", ")", ")", "self", ".", "elk", ".", "send", "(", "zp_encode", "(", ")", ")", "self", ...
Retrieve zones from ElkM1
[ "Retrieve", "zones", "from", "ElkM1" ]
078d0de30840c3fab46f1f8534d98df557931e91
https://github.com/gwww/elkm1/blob/078d0de30840c3fab46f1f8534d98df557931e91/elkm1_lib/zones.py#L50-L56
train
51,716
erikvw/django-collect-offline
django_collect_offline/offline_model.py
OfflineModel.has_offline_historical_manager_or_raise
def has_offline_historical_manager_or_raise(self): """Raises an exception if model uses a history manager and historical model history_id is not a UUIDField. Note: expected to use edc_model.HistoricalRecords instead of simple_history.HistoricalRecords. """ try: model = self.instance.__class__.history.model except AttributeError: model = self.instance.__class__ field = [field for field in model._meta.fields if field.name == "history_id"] if field and not isinstance(field[0], UUIDField): raise OfflineHistoricalManagerError( f"Field 'history_id' of historical model " f"'{model._meta.app_label}.{model._meta.model_name}' " "must be an UUIDfield. " "For history = HistoricalRecords() use edc_model.HistoricalRecords instead of " "simple_history.HistoricalRecords(). " f"See '{self.instance._meta.app_label}.{self.instance._meta.model_name}'." )
python
def has_offline_historical_manager_or_raise(self): """Raises an exception if model uses a history manager and historical model history_id is not a UUIDField. Note: expected to use edc_model.HistoricalRecords instead of simple_history.HistoricalRecords. """ try: model = self.instance.__class__.history.model except AttributeError: model = self.instance.__class__ field = [field for field in model._meta.fields if field.name == "history_id"] if field and not isinstance(field[0], UUIDField): raise OfflineHistoricalManagerError( f"Field 'history_id' of historical model " f"'{model._meta.app_label}.{model._meta.model_name}' " "must be an UUIDfield. " "For history = HistoricalRecords() use edc_model.HistoricalRecords instead of " "simple_history.HistoricalRecords(). " f"See '{self.instance._meta.app_label}.{self.instance._meta.model_name}'." )
[ "def", "has_offline_historical_manager_or_raise", "(", "self", ")", ":", "try", ":", "model", "=", "self", ".", "instance", ".", "__class__", ".", "history", ".", "model", "except", "AttributeError", ":", "model", "=", "self", ".", "instance", ".", "__class__"...
Raises an exception if model uses a history manager and historical model history_id is not a UUIDField. Note: expected to use edc_model.HistoricalRecords instead of simple_history.HistoricalRecords.
[ "Raises", "an", "exception", "if", "model", "uses", "a", "history", "manager", "and", "historical", "model", "history_id", "is", "not", "a", "UUIDField", "." ]
3d5efd66c68e2db4b060a82b070ae490dc399ca7
https://github.com/erikvw/django-collect-offline/blob/3d5efd66c68e2db4b060a82b070ae490dc399ca7/django_collect_offline/offline_model.py#L71-L91
train
51,717
erikvw/django-collect-offline
django_collect_offline/offline_model.py
OfflineModel.primary_key_field
def primary_key_field(self): """Return the primary key field. Is `id` in most cases. Is `history_id` for Historical models. """ return [field for field in self.instance._meta.fields if field.primary_key][0]
python
def primary_key_field(self): """Return the primary key field. Is `id` in most cases. Is `history_id` for Historical models. """ return [field for field in self.instance._meta.fields if field.primary_key][0]
[ "def", "primary_key_field", "(", "self", ")", ":", "return", "[", "field", "for", "field", "in", "self", ".", "instance", ".", "_meta", ".", "fields", "if", "field", ".", "primary_key", "]", "[", "0", "]" ]
Return the primary key field. Is `id` in most cases. Is `history_id` for Historical models.
[ "Return", "the", "primary", "key", "field", "." ]
3d5efd66c68e2db4b060a82b070ae490dc399ca7
https://github.com/erikvw/django-collect-offline/blob/3d5efd66c68e2db4b060a82b070ae490dc399ca7/django_collect_offline/offline_model.py#L103-L108
train
51,718
erikvw/django-collect-offline
django_collect_offline/offline_model.py
OfflineModel.to_outgoing_transaction
def to_outgoing_transaction(self, using, created=None, deleted=None): """ Serialize the model instance to an AES encrypted json object and saves the json object to the OutgoingTransaction model. """ OutgoingTransaction = django_apps.get_model( "django_collect_offline", "OutgoingTransaction" ) created = True if created is None else created action = INSERT if created else UPDATE timestamp_datetime = ( self.instance.created if created else self.instance.modified ) if not timestamp_datetime: timestamp_datetime = get_utcnow() if deleted: timestamp_datetime = get_utcnow() action = DELETE outgoing_transaction = None if self.is_serialized: hostname = socket.gethostname() outgoing_transaction = OutgoingTransaction.objects.using(using).create( tx_name=self.instance._meta.label_lower, tx_pk=getattr(self.instance, self.primary_key_field.name), tx=self.encrypted_json(), timestamp=timestamp_datetime.strftime("%Y%m%d%H%M%S%f"), producer=f"{hostname}-{using}", action=action, using=using, ) return outgoing_transaction
python
def to_outgoing_transaction(self, using, created=None, deleted=None): """ Serialize the model instance to an AES encrypted json object and saves the json object to the OutgoingTransaction model. """ OutgoingTransaction = django_apps.get_model( "django_collect_offline", "OutgoingTransaction" ) created = True if created is None else created action = INSERT if created else UPDATE timestamp_datetime = ( self.instance.created if created else self.instance.modified ) if not timestamp_datetime: timestamp_datetime = get_utcnow() if deleted: timestamp_datetime = get_utcnow() action = DELETE outgoing_transaction = None if self.is_serialized: hostname = socket.gethostname() outgoing_transaction = OutgoingTransaction.objects.using(using).create( tx_name=self.instance._meta.label_lower, tx_pk=getattr(self.instance, self.primary_key_field.name), tx=self.encrypted_json(), timestamp=timestamp_datetime.strftime("%Y%m%d%H%M%S%f"), producer=f"{hostname}-{using}", action=action, using=using, ) return outgoing_transaction
[ "def", "to_outgoing_transaction", "(", "self", ",", "using", ",", "created", "=", "None", ",", "deleted", "=", "None", ")", ":", "OutgoingTransaction", "=", "django_apps", ".", "get_model", "(", "\"django_collect_offline\"", ",", "\"OutgoingTransaction\"", ")", "c...
Serialize the model instance to an AES encrypted json object and saves the json object to the OutgoingTransaction model.
[ "Serialize", "the", "model", "instance", "to", "an", "AES", "encrypted", "json", "object", "and", "saves", "the", "json", "object", "to", "the", "OutgoingTransaction", "model", "." ]
3d5efd66c68e2db4b060a82b070ae490dc399ca7
https://github.com/erikvw/django-collect-offline/blob/3d5efd66c68e2db4b060a82b070ae490dc399ca7/django_collect_offline/offline_model.py#L110-L139
train
51,719
erikvw/django-collect-offline
django_collect_offline/offline_model.py
OfflineModel.encrypted_json
def encrypted_json(self): """Returns an encrypted json serialized from self. """ json = serialize(objects=[self.instance]) encrypted_json = Cryptor().aes_encrypt(json, LOCAL_MODE) return encrypted_json
python
def encrypted_json(self): """Returns an encrypted json serialized from self. """ json = serialize(objects=[self.instance]) encrypted_json = Cryptor().aes_encrypt(json, LOCAL_MODE) return encrypted_json
[ "def", "encrypted_json", "(", "self", ")", ":", "json", "=", "serialize", "(", "objects", "=", "[", "self", ".", "instance", "]", ")", "encrypted_json", "=", "Cryptor", "(", ")", ".", "aes_encrypt", "(", "json", ",", "LOCAL_MODE", ")", "return", "encrypt...
Returns an encrypted json serialized from self.
[ "Returns", "an", "encrypted", "json", "serialized", "from", "self", "." ]
3d5efd66c68e2db4b060a82b070ae490dc399ca7
https://github.com/erikvw/django-collect-offline/blob/3d5efd66c68e2db4b060a82b070ae490dc399ca7/django_collect_offline/offline_model.py#L141-L146
train
51,720
MonashBI/arcana
arcana/environment/modules.py
ModulesEnv.map_req
def map_req(self, requirement): """ Maps the name of an Requirement class to the name of the corresponding module in the environment Parameters ---------- requirement : Requirement The requirement to map to the name of a module on the system """ if isinstance(self._packages_map, dict): local_name = self._packages_map.get(requirement, requirement.name) else: local_name = self._packages_map(requirement) return local_name
python
def map_req(self, requirement): """ Maps the name of an Requirement class to the name of the corresponding module in the environment Parameters ---------- requirement : Requirement The requirement to map to the name of a module on the system """ if isinstance(self._packages_map, dict): local_name = self._packages_map.get(requirement, requirement.name) else: local_name = self._packages_map(requirement) return local_name
[ "def", "map_req", "(", "self", ",", "requirement", ")", ":", "if", "isinstance", "(", "self", ".", "_packages_map", ",", "dict", ")", ":", "local_name", "=", "self", ".", "_packages_map", ".", "get", "(", "requirement", ",", "requirement", ".", "name", "...
Maps the name of an Requirement class to the name of the corresponding module in the environment Parameters ---------- requirement : Requirement The requirement to map to the name of a module on the system
[ "Maps", "the", "name", "of", "an", "Requirement", "class", "to", "the", "name", "of", "the", "corresponding", "module", "in", "the", "environment" ]
d6271a29d13733d00422d11417af8d200be62acc
https://github.com/MonashBI/arcana/blob/d6271a29d13733d00422d11417af8d200be62acc/arcana/environment/modules.py#L169-L183
train
51,721
MonashBI/arcana
arcana/environment/modules.py
ModulesEnv.map_version
def map_version(self, requirement, local_version): """ Maps a local version name to one recognised by the Requirement class Parameters ---------- requirement : str Name of the requirement version : str version string """ if isinstance(self._versions_map, dict): version = self._versions_map.get(requirement, {}).get( local_version, local_version) else: version = self._versions_map(requirement, local_version) return version
python
def map_version(self, requirement, local_version): """ Maps a local version name to one recognised by the Requirement class Parameters ---------- requirement : str Name of the requirement version : str version string """ if isinstance(self._versions_map, dict): version = self._versions_map.get(requirement, {}).get( local_version, local_version) else: version = self._versions_map(requirement, local_version) return version
[ "def", "map_version", "(", "self", ",", "requirement", ",", "local_version", ")", ":", "if", "isinstance", "(", "self", ".", "_versions_map", ",", "dict", ")", ":", "version", "=", "self", ".", "_versions_map", ".", "get", "(", "requirement", ",", "{", "...
Maps a local version name to one recognised by the Requirement class Parameters ---------- requirement : str Name of the requirement version : str version string
[ "Maps", "a", "local", "version", "name", "to", "one", "recognised", "by", "the", "Requirement", "class" ]
d6271a29d13733d00422d11417af8d200be62acc
https://github.com/MonashBI/arcana/blob/d6271a29d13733d00422d11417af8d200be62acc/arcana/environment/modules.py#L185-L201
train
51,722
vedvyas/doxytag2zealdb
doxytag2zealdb/doxytagfile.py
TagfileProcessor.init_tag_processors
def init_tag_processors(self): '''Register the TagProcessors that are bundled with doxytag2zealdb.''' register = self.register_tag_processor register('class', classTagProcessor(**self.opts)) register('file', fileTagProcessor(**self.opts)) register('namespace', namespaceTagProcessor(**self.opts)) register('struct', structTagProcessor(**self.opts)) register('union', unionTagProcessor(**self.opts)) register('function', functionTagProcessor(**self.opts)) register('define', defineTagProcessor(**self.opts)) register('enumeration', enumerationTagProcessor(**self.opts)) register('enumvalue', enumvalueTagProcessor(**self.opts)) register('typedef', typedefTagProcessor(**self.opts)) register('variable', variableTagProcessor(**self.opts))
python
def init_tag_processors(self): '''Register the TagProcessors that are bundled with doxytag2zealdb.''' register = self.register_tag_processor register('class', classTagProcessor(**self.opts)) register('file', fileTagProcessor(**self.opts)) register('namespace', namespaceTagProcessor(**self.opts)) register('struct', structTagProcessor(**self.opts)) register('union', unionTagProcessor(**self.opts)) register('function', functionTagProcessor(**self.opts)) register('define', defineTagProcessor(**self.opts)) register('enumeration', enumerationTagProcessor(**self.opts)) register('enumvalue', enumvalueTagProcessor(**self.opts)) register('typedef', typedefTagProcessor(**self.opts)) register('variable', variableTagProcessor(**self.opts))
[ "def", "init_tag_processors", "(", "self", ")", ":", "register", "=", "self", ".", "register_tag_processor", "register", "(", "'class'", ",", "classTagProcessor", "(", "*", "*", "self", ".", "opts", ")", ")", "register", "(", "'file'", ",", "fileTagProcessor",...
Register the TagProcessors that are bundled with doxytag2zealdb.
[ "Register", "the", "TagProcessors", "that", "are", "bundled", "with", "doxytag2zealdb", "." ]
8b07a88af6794248f8cfdabb0fda9dd61c777127
https://github.com/vedvyas/doxytag2zealdb/blob/8b07a88af6794248f8cfdabb0fda9dd61c777127/doxytag2zealdb/doxytagfile.py#L76-L90
train
51,723
vedvyas/doxytag2zealdb
doxytag2zealdb/doxytagfile.py
TagfileProcessor.process
def process(self): '''Run all tag processors.''' for tag_proc in self.tag_procs: before_count = self.entry_count self.run_tag_processor(tag_proc) after_count = self.entry_count if self.verbose: print('Inserted %d entries for "%s" tag processor' % ( after_count - before_count, tag_proc), file=sys.stderr) if self.verbose: print('Inserted %d entries overall' % self.entry_count, file=sys.stderr)
python
def process(self): '''Run all tag processors.''' for tag_proc in self.tag_procs: before_count = self.entry_count self.run_tag_processor(tag_proc) after_count = self.entry_count if self.verbose: print('Inserted %d entries for "%s" tag processor' % ( after_count - before_count, tag_proc), file=sys.stderr) if self.verbose: print('Inserted %d entries overall' % self.entry_count, file=sys.stderr)
[ "def", "process", "(", "self", ")", ":", "for", "tag_proc", "in", "self", ".", "tag_procs", ":", "before_count", "=", "self", ".", "entry_count", "self", ".", "run_tag_processor", "(", "tag_proc", ")", "after_count", "=", "self", ".", "entry_count", "if", ...
Run all tag processors.
[ "Run", "all", "tag", "processors", "." ]
8b07a88af6794248f8cfdabb0fda9dd61c777127
https://github.com/vedvyas/doxytag2zealdb/blob/8b07a88af6794248f8cfdabb0fda9dd61c777127/doxytag2zealdb/doxytagfile.py#L111-L124
train
51,724
vedvyas/doxytag2zealdb
doxytag2zealdb/doxytagfile.py
TagfileProcessor.run_tag_processor
def run_tag_processor(self, tag_proc_name): '''Run a tag processor. Args: tag_proc_name: A string key that maps to the TagProcessor to run. ''' tag_processor = self.tag_procs[tag_proc_name] for tag in tag_processor.find(self.soup): self.process_tag(tag_proc_name, tag)
python
def run_tag_processor(self, tag_proc_name): '''Run a tag processor. Args: tag_proc_name: A string key that maps to the TagProcessor to run. ''' tag_processor = self.tag_procs[tag_proc_name] for tag in tag_processor.find(self.soup): self.process_tag(tag_proc_name, tag)
[ "def", "run_tag_processor", "(", "self", ",", "tag_proc_name", ")", ":", "tag_processor", "=", "self", ".", "tag_procs", "[", "tag_proc_name", "]", "for", "tag", "in", "tag_processor", ".", "find", "(", "self", ".", "soup", ")", ":", "self", ".", "process_...
Run a tag processor. Args: tag_proc_name: A string key that maps to the TagProcessor to run.
[ "Run", "a", "tag", "processor", "." ]
8b07a88af6794248f8cfdabb0fda9dd61c777127
https://github.com/vedvyas/doxytag2zealdb/blob/8b07a88af6794248f8cfdabb0fda9dd61c777127/doxytag2zealdb/doxytagfile.py#L126-L135
train
51,725
vedvyas/doxytag2zealdb
doxytag2zealdb/doxytagfile.py
TagfileProcessor.process_tag
def process_tag(self, tag_proc_name, tag): '''Process a tag with a tag processor and insert a DB entry. Args: tag_proc_name: A string key that maps to the TagProcessor to use. tag: A BeautifulSoup Tag to process. ''' tag_processor = self.tag_procs[tag_proc_name] db_entry = (tag_processor.get_name(tag), tag_processor.get_entry_type(tag), tag_processor.get_filename(tag)) self.zeal_db.insert(*db_entry) self.entry_count += 1
python
def process_tag(self, tag_proc_name, tag): '''Process a tag with a tag processor and insert a DB entry. Args: tag_proc_name: A string key that maps to the TagProcessor to use. tag: A BeautifulSoup Tag to process. ''' tag_processor = self.tag_procs[tag_proc_name] db_entry = (tag_processor.get_name(tag), tag_processor.get_entry_type(tag), tag_processor.get_filename(tag)) self.zeal_db.insert(*db_entry) self.entry_count += 1
[ "def", "process_tag", "(", "self", ",", "tag_proc_name", ",", "tag", ")", ":", "tag_processor", "=", "self", ".", "tag_procs", "[", "tag_proc_name", "]", "db_entry", "=", "(", "tag_processor", ".", "get_name", "(", "tag", ")", ",", "tag_processor", ".", "g...
Process a tag with a tag processor and insert a DB entry. Args: tag_proc_name: A string key that maps to the TagProcessor to use. tag: A BeautifulSoup Tag to process.
[ "Process", "a", "tag", "with", "a", "tag", "processor", "and", "insert", "a", "DB", "entry", "." ]
8b07a88af6794248f8cfdabb0fda9dd61c777127
https://github.com/vedvyas/doxytag2zealdb/blob/8b07a88af6794248f8cfdabb0fda9dd61c777127/doxytag2zealdb/doxytagfile.py#L137-L152
train
51,726
MonashBI/arcana
arcana/processor/slurm.py
ArcanaSlurmGraphPlugin._get_args
def _get_args(self, node, keywords): """ Intercept calls to get template and return our own node-specific template """ args = super(ArcanaSlurmGraphPlugin, self)._get_args( node, keywords) # Substitute the template arg with the node-specific one new_args = [] for name, arg in zip(keywords, args): if name == 'template': new_args.append(self._processor.slurm_template(node)) else: new_args.append(arg) return tuple(new_args)
python
def _get_args(self, node, keywords): """ Intercept calls to get template and return our own node-specific template """ args = super(ArcanaSlurmGraphPlugin, self)._get_args( node, keywords) # Substitute the template arg with the node-specific one new_args = [] for name, arg in zip(keywords, args): if name == 'template': new_args.append(self._processor.slurm_template(node)) else: new_args.append(arg) return tuple(new_args)
[ "def", "_get_args", "(", "self", ",", "node", ",", "keywords", ")", ":", "args", "=", "super", "(", "ArcanaSlurmGraphPlugin", ",", "self", ")", ".", "_get_args", "(", "node", ",", "keywords", ")", "# Substitute the template arg with the node-specific one", "new_ar...
Intercept calls to get template and return our own node-specific template
[ "Intercept", "calls", "to", "get", "template", "and", "return", "our", "own", "node", "-", "specific", "template" ]
d6271a29d13733d00422d11417af8d200be62acc
https://github.com/MonashBI/arcana/blob/d6271a29d13733d00422d11417af8d200be62acc/arcana/processor/slurm.py#L16-L30
train
51,727
MonashBI/arcana
arcana/processor/slurm.py
SlurmProc.wall_time_str
def wall_time_str(self, wall_time): """ Returns the wall time in the format required for the sbatch script """ days = int(wall_time // 1440) hours = int((wall_time - days * 1440) // 60) minutes = int(math.floor(wall_time - days * 1440 - hours * 60)) seconds = int((wall_time - math.floor(wall_time)) * 60) return "{}-{:0>2}:{:0>2}:{:0>2}".format(days, hours, minutes, seconds)
python
def wall_time_str(self, wall_time): """ Returns the wall time in the format required for the sbatch script """ days = int(wall_time // 1440) hours = int((wall_time - days * 1440) // 60) minutes = int(math.floor(wall_time - days * 1440 - hours * 60)) seconds = int((wall_time - math.floor(wall_time)) * 60) return "{}-{:0>2}:{:0>2}:{:0>2}".format(days, hours, minutes, seconds)
[ "def", "wall_time_str", "(", "self", ",", "wall_time", ")", ":", "days", "=", "int", "(", "wall_time", "//", "1440", ")", "hours", "=", "int", "(", "(", "wall_time", "-", "days", "*", "1440", ")", "//", "60", ")", "minutes", "=", "int", "(", "math"...
Returns the wall time in the format required for the sbatch script
[ "Returns", "the", "wall", "time", "in", "the", "format", "required", "for", "the", "sbatch", "script" ]
d6271a29d13733d00422d11417af8d200be62acc
https://github.com/MonashBI/arcana/blob/d6271a29d13733d00422d11417af8d200be62acc/arcana/processor/slurm.py#L139-L147
train
51,728
gwww/elkm1
elkm1_lib/panel.py
Panel.sync
def sync(self): """Retrieve panel information from ElkM1""" self._elk.add_handler('VN', self._vn_handler) self._elk.add_handler('XK', self._xk_handler) self._elk.add_handler('RP', self._rp_handler) self._elk.add_handler('IE', self._elk.call_sync_handlers) self._elk.add_handler('SS', self._ss_handler) self._elk.send(vn_encode()) self._elk.send(lw_encode()) self._elk.send(ss_encode())
python
def sync(self): """Retrieve panel information from ElkM1""" self._elk.add_handler('VN', self._vn_handler) self._elk.add_handler('XK', self._xk_handler) self._elk.add_handler('RP', self._rp_handler) self._elk.add_handler('IE', self._elk.call_sync_handlers) self._elk.add_handler('SS', self._ss_handler) self._elk.send(vn_encode()) self._elk.send(lw_encode()) self._elk.send(ss_encode())
[ "def", "sync", "(", "self", ")", ":", "self", ".", "_elk", ".", "add_handler", "(", "'VN'", ",", "self", ".", "_vn_handler", ")", "self", ".", "_elk", ".", "add_handler", "(", "'XK'", ",", "self", ".", "_xk_handler", ")", "self", ".", "_elk", ".", ...
Retrieve panel information from ElkM1
[ "Retrieve", "panel", "information", "from", "ElkM1" ]
078d0de30840c3fab46f1f8534d98df557931e91
https://github.com/gwww/elkm1/blob/078d0de30840c3fab46f1f8534d98df557931e91/elkm1_lib/panel.py#L19-L28
train
51,729
MonashBI/arcana
arcana/data/base.py
BaseData.renamed
def renamed(self, name): """ Duplicate the datum and rename it """ duplicate = copy(self) duplicate._name = name return duplicate
python
def renamed(self, name): """ Duplicate the datum and rename it """ duplicate = copy(self) duplicate._name = name return duplicate
[ "def", "renamed", "(", "self", ",", "name", ")", ":", "duplicate", "=", "copy", "(", "self", ")", "duplicate", ".", "_name", "=", "name", "return", "duplicate" ]
Duplicate the datum and rename it
[ "Duplicate", "the", "datum", "and", "rename", "it" ]
d6271a29d13733d00422d11417af8d200be62acc
https://github.com/MonashBI/arcana/blob/d6271a29d13733d00422d11417af8d200be62acc/arcana/data/base.py#L72-L78
train
51,730
MonashBI/arcana
arcana/environment/requirement/base.py
Version.compare
def compare(self, other): """ Compares the version with another Parameters ---------- other : Version The version to compare to """ if self._req != other._req: raise ArcanaUsageError( "Can't compare versions of different requirements {} and {}" .format(self._req, other._req)) # Compare main sequence if self._seq < other._seq: return -1 elif self._seq > other._seq: return 1 # If main sequence is equal check prerelease. If a prerelease is # None then it is a full release which is > then a prerelease so we # just assign it 'z' (which is greater than 'a', 'b' and 'rc') s = self._prerelease if self._prerelease is not None else ('z',) o = other._prerelease if other._prerelease is not None else ('z',) if s < o: return -1 if s > o: return 1 # If both main sequence and prereleases are equal, compare post release s = self._post if self._post is not None else 0 o = other._post if other._post is not None else 0 if s < o: return -1 if s > o: return 1 # If both main sequence and prereleases are equal, compare development # release s = self._dev if self._dev is not None else 0 o = other._dev if other._dev is not None else 0 if s < o: return -1 if s > o: return 1 assert self == other return 0
python
def compare(self, other): """ Compares the version with another Parameters ---------- other : Version The version to compare to """ if self._req != other._req: raise ArcanaUsageError( "Can't compare versions of different requirements {} and {}" .format(self._req, other._req)) # Compare main sequence if self._seq < other._seq: return -1 elif self._seq > other._seq: return 1 # If main sequence is equal check prerelease. If a prerelease is # None then it is a full release which is > then a prerelease so we # just assign it 'z' (which is greater than 'a', 'b' and 'rc') s = self._prerelease if self._prerelease is not None else ('z',) o = other._prerelease if other._prerelease is not None else ('z',) if s < o: return -1 if s > o: return 1 # If both main sequence and prereleases are equal, compare post release s = self._post if self._post is not None else 0 o = other._post if other._post is not None else 0 if s < o: return -1 if s > o: return 1 # If both main sequence and prereleases are equal, compare development # release s = self._dev if self._dev is not None else 0 o = other._dev if other._dev is not None else 0 if s < o: return -1 if s > o: return 1 assert self == other return 0
[ "def", "compare", "(", "self", ",", "other", ")", ":", "if", "self", ".", "_req", "!=", "other", ".", "_req", ":", "raise", "ArcanaUsageError", "(", "\"Can't compare versions of different requirements {} and {}\"", ".", "format", "(", "self", ".", "_req", ",", ...
Compares the version with another Parameters ---------- other : Version The version to compare to
[ "Compares", "the", "version", "with", "another" ]
d6271a29d13733d00422d11417af8d200be62acc
https://github.com/MonashBI/arcana/blob/d6271a29d13733d00422d11417af8d200be62acc/arcana/environment/requirement/base.py#L108-L151
train
51,731
MonashBI/arcana
arcana/environment/requirement/base.py
BaseRequirement.v
def v(self, version, max_version=None, **kwargs): """ Returns either a single requirement version or a requirement version range depending on whether two arguments are supplied or one Parameters ---------- version : str | Version Either a version of the requirement, or the first version in a range of acceptable versions """ if not isinstance(version, Version): version = self.version_cls(self, version, **kwargs) # Return a version range instead of version if max_version is not None: if not isinstance(max_version, Version): max_version = self.version_cls(self, max_version, **kwargs) version = VersionRange(version, max_version) return version
python
def v(self, version, max_version=None, **kwargs): """ Returns either a single requirement version or a requirement version range depending on whether two arguments are supplied or one Parameters ---------- version : str | Version Either a version of the requirement, or the first version in a range of acceptable versions """ if not isinstance(version, Version): version = self.version_cls(self, version, **kwargs) # Return a version range instead of version if max_version is not None: if not isinstance(max_version, Version): max_version = self.version_cls(self, max_version, **kwargs) version = VersionRange(version, max_version) return version
[ "def", "v", "(", "self", ",", "version", ",", "max_version", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "not", "isinstance", "(", "version", ",", "Version", ")", ":", "version", "=", "self", ".", "version_cls", "(", "self", ",", "version",...
Returns either a single requirement version or a requirement version range depending on whether two arguments are supplied or one Parameters ---------- version : str | Version Either a version of the requirement, or the first version in a range of acceptable versions
[ "Returns", "either", "a", "single", "requirement", "version", "or", "a", "requirement", "version", "range", "depending", "on", "whether", "two", "arguments", "are", "supplied", "or", "one" ]
d6271a29d13733d00422d11417af8d200be62acc
https://github.com/MonashBI/arcana/blob/d6271a29d13733d00422d11417af8d200be62acc/arcana/environment/requirement/base.py#L393-L411
train
51,732
vedvyas/doxytag2zealdb
doxytag2zealdb/zealdb.py
ZealDB.open
def open(self): '''Open a connection to the database. If a connection appears to be open already, transactions are committed and it is closed before proceeding. After establishing the connection, the searchIndex table is prepared (and dropped if it already exists). ''' if self.conn is not None: self.close() self.conn = sqlite3.connect(self.filename) self.cursor = self.conn.cursor() c = self.cursor c.execute('SELECT name FROM sqlite_master WHERE type="table"') if (u'searchIndex',) in c: c.execute('DROP TABLE searchIndex') if self.verbose: print('Dropped existing table', file=sys.stderr) c.executescript( ''' CREATE TABLE searchIndex (id INTEGER PRIMARY KEY, name TEXT, type TEXT, path TEXT); CREATE UNIQUE INDEX anchor ON searchIndex (name, type, path); ''' )
python
def open(self): '''Open a connection to the database. If a connection appears to be open already, transactions are committed and it is closed before proceeding. After establishing the connection, the searchIndex table is prepared (and dropped if it already exists). ''' if self.conn is not None: self.close() self.conn = sqlite3.connect(self.filename) self.cursor = self.conn.cursor() c = self.cursor c.execute('SELECT name FROM sqlite_master WHERE type="table"') if (u'searchIndex',) in c: c.execute('DROP TABLE searchIndex') if self.verbose: print('Dropped existing table', file=sys.stderr) c.executescript( ''' CREATE TABLE searchIndex (id INTEGER PRIMARY KEY, name TEXT, type TEXT, path TEXT); CREATE UNIQUE INDEX anchor ON searchIndex (name, type, path); ''' )
[ "def", "open", "(", "self", ")", ":", "if", "self", ".", "conn", "is", "not", "None", ":", "self", ".", "close", "(", ")", "self", ".", "conn", "=", "sqlite3", ".", "connect", "(", "self", ".", "filename", ")", "self", ".", "cursor", "=", "self",...
Open a connection to the database. If a connection appears to be open already, transactions are committed and it is closed before proceeding. After establishing the connection, the searchIndex table is prepared (and dropped if it already exists).
[ "Open", "a", "connection", "to", "the", "database", "." ]
8b07a88af6794248f8cfdabb0fda9dd61c777127
https://github.com/vedvyas/doxytag2zealdb/blob/8b07a88af6794248f8cfdabb0fda9dd61c777127/doxytag2zealdb/zealdb.py#L77-L105
train
51,733
erikvw/django-collect-offline
django_collect_offline/transaction/serialize.py
serialize
def serialize(objects=None): """A simple wrapper of Django's serializer with defaults for JSON and natural keys. Note: use_natural_primary_keys is False as once a pk is set, it should not be changed throughout the distributed data. """ return serializers.serialize( "json", objects, ensure_ascii=True, use_natural_foreign_keys=True, use_natural_primary_keys=False, )
python
def serialize(objects=None): """A simple wrapper of Django's serializer with defaults for JSON and natural keys. Note: use_natural_primary_keys is False as once a pk is set, it should not be changed throughout the distributed data. """ return serializers.serialize( "json", objects, ensure_ascii=True, use_natural_foreign_keys=True, use_natural_primary_keys=False, )
[ "def", "serialize", "(", "objects", "=", "None", ")", ":", "return", "serializers", ".", "serialize", "(", "\"json\"", ",", "objects", ",", "ensure_ascii", "=", "True", ",", "use_natural_foreign_keys", "=", "True", ",", "use_natural_primary_keys", "=", "False", ...
A simple wrapper of Django's serializer with defaults for JSON and natural keys. Note: use_natural_primary_keys is False as once a pk is set, it should not be changed throughout the distributed data.
[ "A", "simple", "wrapper", "of", "Django", "s", "serializer", "with", "defaults", "for", "JSON", "and", "natural", "keys", "." ]
3d5efd66c68e2db4b060a82b070ae490dc399ca7
https://github.com/erikvw/django-collect-offline/blob/3d5efd66c68e2db4b060a82b070ae490dc399ca7/django_collect_offline/transaction/serialize.py#L4-L19
train
51,734
MonashBI/arcana
arcana/study/base.py
Study.branch
def branch(self, name, values=None): # @UnusedVariable @IgnorePep8 """ Checks whether the given switch matches the value provided Parameters ---------- name : str The name of the parameter to retrieve value : str | None The value(s) of the switch to match if a non-boolean switch """ if isinstance(values, basestring): values = [values] spec = self.parameter_spec(name) if not isinstance(spec, SwitchSpec): raise ArcanaUsageError( "{} is standard parameter not a switch".format(spec)) switch = self._get_parameter(name) if spec.is_boolean: if values is not None: raise ArcanaDesignError( "Should not provide values ({}) to boolean switch " "'{}' in {}".format( values, name, self._param_error_location)) in_branch = switch.value else: if values is None: raise ArcanaDesignError( "Value(s) need(s) to be provided non-boolean switch" " '{}' in {}".format( name, self._param_error_location)) # Register parameter as being used by the pipeline unrecognised_values = set(values) - set(spec.choices) if unrecognised_values: raise ArcanaDesignError( "Provided value(s) ('{}') for switch '{}' in {} " "is not a valid option ('{}')".format( "', '".join(unrecognised_values), name, self._param_error_location, "', '".join(spec.choices))) in_branch = switch.value in values return in_branch
python
def branch(self, name, values=None): # @UnusedVariable @IgnorePep8 """ Checks whether the given switch matches the value provided Parameters ---------- name : str The name of the parameter to retrieve value : str | None The value(s) of the switch to match if a non-boolean switch """ if isinstance(values, basestring): values = [values] spec = self.parameter_spec(name) if not isinstance(spec, SwitchSpec): raise ArcanaUsageError( "{} is standard parameter not a switch".format(spec)) switch = self._get_parameter(name) if spec.is_boolean: if values is not None: raise ArcanaDesignError( "Should not provide values ({}) to boolean switch " "'{}' in {}".format( values, name, self._param_error_location)) in_branch = switch.value else: if values is None: raise ArcanaDesignError( "Value(s) need(s) to be provided non-boolean switch" " '{}' in {}".format( name, self._param_error_location)) # Register parameter as being used by the pipeline unrecognised_values = set(values) - set(spec.choices) if unrecognised_values: raise ArcanaDesignError( "Provided value(s) ('{}') for switch '{}' in {} " "is not a valid option ('{}')".format( "', '".join(unrecognised_values), name, self._param_error_location, "', '".join(spec.choices))) in_branch = switch.value in values return in_branch
[ "def", "branch", "(", "self", ",", "name", ",", "values", "=", "None", ")", ":", "# @UnusedVariable @IgnorePep8", "if", "isinstance", "(", "values", ",", "basestring", ")", ":", "values", "=", "[", "values", "]", "spec", "=", "self", ".", "parameter_spec",...
Checks whether the given switch matches the value provided Parameters ---------- name : str The name of the parameter to retrieve value : str | None The value(s) of the switch to match if a non-boolean switch
[ "Checks", "whether", "the", "given", "switch", "matches", "the", "value", "provided" ]
d6271a29d13733d00422d11417af8d200be62acc
https://github.com/MonashBI/arcana/blob/d6271a29d13733d00422d11417af8d200be62acc/arcana/study/base.py#L593-L634
train
51,735
MonashBI/arcana
arcana/study/base.py
Study.unhandled_branch
def unhandled_branch(self, name): """ Convenient method for raising exception if a pipeline doesn't handle a particular switch value Parameters ---------- name : str Name of the switch value : str Value of the switch which hasn't been handled """ raise ArcanaDesignError( "'{}' value of '{}' switch in {} is not handled" .format(self._get_parameter(name), name, self._param_error_location))
python
def unhandled_branch(self, name): """ Convenient method for raising exception if a pipeline doesn't handle a particular switch value Parameters ---------- name : str Name of the switch value : str Value of the switch which hasn't been handled """ raise ArcanaDesignError( "'{}' value of '{}' switch in {} is not handled" .format(self._get_parameter(name), name, self._param_error_location))
[ "def", "unhandled_branch", "(", "self", ",", "name", ")", ":", "raise", "ArcanaDesignError", "(", "\"'{}' value of '{}' switch in {} is not handled\"", ".", "format", "(", "self", ".", "_get_parameter", "(", "name", ")", ",", "name", ",", "self", ".", "_param_erro...
Convenient method for raising exception if a pipeline doesn't handle a particular switch value Parameters ---------- name : str Name of the switch value : str Value of the switch which hasn't been handled
[ "Convenient", "method", "for", "raising", "exception", "if", "a", "pipeline", "doesn", "t", "handle", "a", "particular", "switch", "value" ]
d6271a29d13733d00422d11417af8d200be62acc
https://github.com/MonashBI/arcana/blob/d6271a29d13733d00422d11417af8d200be62acc/arcana/study/base.py#L636-L651
train
51,736
MonashBI/arcana
arcana/study/base.py
Study.save_workflow_graph_for
def save_workflow_graph_for(self, spec_name, fname, full=False, style='flat', **kwargs): """ Saves a graph of the workflow to generate the requested spec_name Parameters ---------- spec_name : str Name of the spec to generate the graph for fname : str The filename for the saved graph style : str The style of the graph, can be one of can be one of 'orig', 'flat', 'exec', 'hierarchical' """ pipeline = self.spec(spec_name).pipeline if full: workflow = pe.Workflow(name='{}_gen'.format(spec_name), base_dir=self.processor.work_dir) self.processor._connect_pipeline( pipeline, workflow, **kwargs) else: workflow = pipeline._workflow fname = op.expanduser(fname) if not fname.endswith('.png'): fname += '.png' dotfilename = fname[:-4] + '.dot' workflow.write_graph(graph2use=style, dotfilename=dotfilename)
python
def save_workflow_graph_for(self, spec_name, fname, full=False, style='flat', **kwargs): """ Saves a graph of the workflow to generate the requested spec_name Parameters ---------- spec_name : str Name of the spec to generate the graph for fname : str The filename for the saved graph style : str The style of the graph, can be one of can be one of 'orig', 'flat', 'exec', 'hierarchical' """ pipeline = self.spec(spec_name).pipeline if full: workflow = pe.Workflow(name='{}_gen'.format(spec_name), base_dir=self.processor.work_dir) self.processor._connect_pipeline( pipeline, workflow, **kwargs) else: workflow = pipeline._workflow fname = op.expanduser(fname) if not fname.endswith('.png'): fname += '.png' dotfilename = fname[:-4] + '.dot' workflow.write_graph(graph2use=style, dotfilename=dotfilename)
[ "def", "save_workflow_graph_for", "(", "self", ",", "spec_name", ",", "fname", ",", "full", "=", "False", ",", "style", "=", "'flat'", ",", "*", "*", "kwargs", ")", ":", "pipeline", "=", "self", ".", "spec", "(", "spec_name", ")", ".", "pipeline", "if"...
Saves a graph of the workflow to generate the requested spec_name Parameters ---------- spec_name : str Name of the spec to generate the graph for fname : str The filename for the saved graph style : str The style of the graph, can be one of can be one of 'orig', 'flat', 'exec', 'hierarchical'
[ "Saves", "a", "graph", "of", "the", "workflow", "to", "generate", "the", "requested", "spec_name" ]
d6271a29d13733d00422d11417af8d200be62acc
https://github.com/MonashBI/arcana/blob/d6271a29d13733d00422d11417af8d200be62acc/arcana/study/base.py#L669-L697
train
51,737
MonashBI/arcana
arcana/study/base.py
Study.spec
def spec(self, name): """ Returns either the input corresponding to a fileset or field field spec or a spec or parameter that has either been passed to the study as an input or can be derived. Parameters ---------- name : Str | BaseData | Parameter A parameter, fileset or field or name of one """ # If the provided "name" is actually a data item or parameter then # replace it with its name. if isinstance(name, (BaseData, Parameter)): name = name.name # If name is a parameter than return the parameter spec if name in self._param_specs: return self._param_specs[name] else: return self.bound_spec(name)
python
def spec(self, name): """ Returns either the input corresponding to a fileset or field field spec or a spec or parameter that has either been passed to the study as an input or can be derived. Parameters ---------- name : Str | BaseData | Parameter A parameter, fileset or field or name of one """ # If the provided "name" is actually a data item or parameter then # replace it with its name. if isinstance(name, (BaseData, Parameter)): name = name.name # If name is a parameter than return the parameter spec if name in self._param_specs: return self._param_specs[name] else: return self.bound_spec(name)
[ "def", "spec", "(", "self", ",", "name", ")", ":", "# If the provided \"name\" is actually a data item or parameter then", "# replace it with its name.", "if", "isinstance", "(", "name", ",", "(", "BaseData", ",", "Parameter", ")", ")", ":", "name", "=", "name", "."...
Returns either the input corresponding to a fileset or field field spec or a spec or parameter that has either been passed to the study as an input or can be derived. Parameters ---------- name : Str | BaseData | Parameter A parameter, fileset or field or name of one
[ "Returns", "either", "the", "input", "corresponding", "to", "a", "fileset", "or", "field", "field", "spec", "or", "a", "spec", "or", "parameter", "that", "has", "either", "been", "passed", "to", "the", "study", "as", "an", "input", "or", "can", "be", "de...
d6271a29d13733d00422d11417af8d200be62acc
https://github.com/MonashBI/arcana/blob/d6271a29d13733d00422d11417af8d200be62acc/arcana/study/base.py#L699-L718
train
51,738
MonashBI/arcana
arcana/study/base.py
Study.bound_spec
def bound_spec(self, name): """ Returns an input selector or derived spec bound to the study, i.e. where the repository tree is checked for existing outputs Parameters ---------- name : Str A name of a fileset or field """ # If the provided "name" is actually a data item or parameter then # replace it with its name. if isinstance(name, BaseData): name = name.name # Get the spec from the class spec = self.data_spec(name) try: bound = self._inputs[name] except KeyError: if not spec.derived and spec.default is None: raise ArcanaMissingDataException( "Acquired (i.e. non-generated) fileset '{}' " "was not supplied when the study '{}' was " "initiated".format(name, self.name)) else: try: bound = self._bound_specs[name] except KeyError: bound = self._bound_specs[name] = spec.bind(self) return bound
python
def bound_spec(self, name): """ Returns an input selector or derived spec bound to the study, i.e. where the repository tree is checked for existing outputs Parameters ---------- name : Str A name of a fileset or field """ # If the provided "name" is actually a data item or parameter then # replace it with its name. if isinstance(name, BaseData): name = name.name # Get the spec from the class spec = self.data_spec(name) try: bound = self._inputs[name] except KeyError: if not spec.derived and spec.default is None: raise ArcanaMissingDataException( "Acquired (i.e. non-generated) fileset '{}' " "was not supplied when the study '{}' was " "initiated".format(name, self.name)) else: try: bound = self._bound_specs[name] except KeyError: bound = self._bound_specs[name] = spec.bind(self) return bound
[ "def", "bound_spec", "(", "self", ",", "name", ")", ":", "# If the provided \"name\" is actually a data item or parameter then", "# replace it with its name.", "if", "isinstance", "(", "name", ",", "BaseData", ")", ":", "name", "=", "name", ".", "name", "# Get the spec ...
Returns an input selector or derived spec bound to the study, i.e. where the repository tree is checked for existing outputs Parameters ---------- name : Str A name of a fileset or field
[ "Returns", "an", "input", "selector", "or", "derived", "spec", "bound", "to", "the", "study", "i", ".", "e", ".", "where", "the", "repository", "tree", "is", "checked", "for", "existing", "outputs" ]
d6271a29d13733d00422d11417af8d200be62acc
https://github.com/MonashBI/arcana/blob/d6271a29d13733d00422d11417af8d200be62acc/arcana/study/base.py#L720-L749
train
51,739
MonashBI/arcana
arcana/study/base.py
Study.data_spec
def data_spec(cls, name): """ Return the fileset_spec, i.e. the template of the fileset expected to be supplied or generated corresponding to the fileset_spec name. Parameters ---------- name : Str Name of the fileset_spec to return """ # If the provided "name" is actually a data item or parameter then # replace it with its name. if isinstance(name, BaseData): name = name.name try: return cls._data_specs[name] except KeyError: raise ArcanaNameError( name, "No fileset spec named '{}' in {}, available:\n{}" .format(name, cls.__name__, "\n".join(list(cls._data_specs.keys()))))
python
def data_spec(cls, name): """ Return the fileset_spec, i.e. the template of the fileset expected to be supplied or generated corresponding to the fileset_spec name. Parameters ---------- name : Str Name of the fileset_spec to return """ # If the provided "name" is actually a data item or parameter then # replace it with its name. if isinstance(name, BaseData): name = name.name try: return cls._data_specs[name] except KeyError: raise ArcanaNameError( name, "No fileset spec named '{}' in {}, available:\n{}" .format(name, cls.__name__, "\n".join(list(cls._data_specs.keys()))))
[ "def", "data_spec", "(", "cls", ",", "name", ")", ":", "# If the provided \"name\" is actually a data item or parameter then", "# replace it with its name.", "if", "isinstance", "(", "name", ",", "BaseData", ")", ":", "name", "=", "name", ".", "name", "try", ":", "r...
Return the fileset_spec, i.e. the template of the fileset expected to be supplied or generated corresponding to the fileset_spec name. Parameters ---------- name : Str Name of the fileset_spec to return
[ "Return", "the", "fileset_spec", "i", ".", "e", ".", "the", "template", "of", "the", "fileset", "expected", "to", "be", "supplied", "or", "generated", "corresponding", "to", "the", "fileset_spec", "name", "." ]
d6271a29d13733d00422d11417af8d200be62acc
https://github.com/MonashBI/arcana/blob/d6271a29d13733d00422d11417af8d200be62acc/arcana/study/base.py#L752-L773
train
51,740
MonashBI/arcana
arcana/study/base.py
Study.cache_inputs
def cache_inputs(self): """ Runs the Study's repository source node for each of the inputs of the study, thereby caching any data required from remote repositorys. Useful when launching many parallel jobs that will all try to concurrently access the remote repository, and probably lead to timeout errors. """ workflow = pe.Workflow(name='cache_download', base_dir=self.processor.work_dir) subjects = pe.Node(IdentityInterface(['subject_id']), name='subjects', environment=self.environment) sessions = pe.Node(IdentityInterface(['subject_id', 'visit_id']), name='sessions', environment=self.environment) subjects.iterables = ('subject_id', tuple(self.subject_ids)) sessions.iterables = ('visit_id', tuple(self.visit_ids)) source = pe.Node(RepositorySource( self.bound_spec(i).collection for i in self.inputs), name='source') workflow.connect(subjects, 'subject_id', sessions, 'subject_id') workflow.connect(sessions, 'subject_id', source, 'subject_id') workflow.connect(sessions, 'visit_id', source, 'visit_id') workflow.run()
python
def cache_inputs(self): """ Runs the Study's repository source node for each of the inputs of the study, thereby caching any data required from remote repositorys. Useful when launching many parallel jobs that will all try to concurrently access the remote repository, and probably lead to timeout errors. """ workflow = pe.Workflow(name='cache_download', base_dir=self.processor.work_dir) subjects = pe.Node(IdentityInterface(['subject_id']), name='subjects', environment=self.environment) sessions = pe.Node(IdentityInterface(['subject_id', 'visit_id']), name='sessions', environment=self.environment) subjects.iterables = ('subject_id', tuple(self.subject_ids)) sessions.iterables = ('visit_id', tuple(self.visit_ids)) source = pe.Node(RepositorySource( self.bound_spec(i).collection for i in self.inputs), name='source') workflow.connect(subjects, 'subject_id', sessions, 'subject_id') workflow.connect(sessions, 'subject_id', source, 'subject_id') workflow.connect(sessions, 'visit_id', source, 'visit_id') workflow.run()
[ "def", "cache_inputs", "(", "self", ")", ":", "workflow", "=", "pe", ".", "Workflow", "(", "name", "=", "'cache_download'", ",", "base_dir", "=", "self", ".", "processor", ".", "work_dir", ")", "subjects", "=", "pe", ".", "Node", "(", "IdentityInterface", ...
Runs the Study's repository source node for each of the inputs of the study, thereby caching any data required from remote repositorys. Useful when launching many parallel jobs that will all try to concurrently access the remote repository, and probably lead to timeout errors.
[ "Runs", "the", "Study", "s", "repository", "source", "node", "for", "each", "of", "the", "inputs", "of", "the", "study", "thereby", "caching", "any", "data", "required", "from", "remote", "repositorys", ".", "Useful", "when", "launching", "many", "parallel", ...
d6271a29d13733d00422d11417af8d200be62acc
https://github.com/MonashBI/arcana/blob/d6271a29d13733d00422d11417af8d200be62acc/arcana/study/base.py#L837-L858
train
51,741
MonashBI/arcana
arcana/study/base.py
Study.provided
def provided(self, spec_name, default_okay=True): """ Checks to see whether the corresponding data spec was provided an explicit input, as opposed to derivatives or missing optional inputs Parameters ---------- spec_name : str Name of a data spec """ try: spec = self.bound_spec(spec_name) except ArcanaMissingDataException: return False if isinstance(spec, BaseInputSpec): return spec.default is not None and default_okay else: return True
python
def provided(self, spec_name, default_okay=True): """ Checks to see whether the corresponding data spec was provided an explicit input, as opposed to derivatives or missing optional inputs Parameters ---------- spec_name : str Name of a data spec """ try: spec = self.bound_spec(spec_name) except ArcanaMissingDataException: return False if isinstance(spec, BaseInputSpec): return spec.default is not None and default_okay else: return True
[ "def", "provided", "(", "self", ",", "spec_name", ",", "default_okay", "=", "True", ")", ":", "try", ":", "spec", "=", "self", ".", "bound_spec", "(", "spec_name", ")", "except", "ArcanaMissingDataException", ":", "return", "False", "if", "isinstance", "(", ...
Checks to see whether the corresponding data spec was provided an explicit input, as opposed to derivatives or missing optional inputs Parameters ---------- spec_name : str Name of a data spec
[ "Checks", "to", "see", "whether", "the", "corresponding", "data", "spec", "was", "provided", "an", "explicit", "input", "as", "opposed", "to", "derivatives", "or", "missing", "optional", "inputs" ]
d6271a29d13733d00422d11417af8d200be62acc
https://github.com/MonashBI/arcana/blob/d6271a29d13733d00422d11417af8d200be62acc/arcana/study/base.py#L869-L886
train
51,742
MonashBI/arcana
arcana/study/base.py
Study.freq_from_iterators
def freq_from_iterators(cls, iterators): """ Returns the frequency corresponding to the given iterators """ return { set(it): f for f, it in cls.FREQUENCIES.items()}[set(iterators)]
python
def freq_from_iterators(cls, iterators): """ Returns the frequency corresponding to the given iterators """ return { set(it): f for f, it in cls.FREQUENCIES.items()}[set(iterators)]
[ "def", "freq_from_iterators", "(", "cls", ",", "iterators", ")", ":", "return", "{", "set", "(", "it", ")", ":", "f", "for", "f", ",", "it", "in", "cls", ".", "FREQUENCIES", ".", "items", "(", ")", "}", "[", "set", "(", "iterators", ")", "]" ]
Returns the frequency corresponding to the given iterators
[ "Returns", "the", "frequency", "corresponding", "to", "the", "given", "iterators" ]
d6271a29d13733d00422d11417af8d200be62acc
https://github.com/MonashBI/arcana/blob/d6271a29d13733d00422d11417af8d200be62acc/arcana/study/base.py#L889-L894
train
51,743
MonashBI/arcana
arcana/study/base.py
Study.prov
def prov(self): """ Extracts provenance information from the study for storage alongside generated derivatives. Typically for reference purposes only as only the pipeline workflow, inputs and outputs are checked by default when determining which sessions require reprocessing. Returns ------- prov : dict[str, *] A dictionary containing the provenance information to record for the study """ # Get list of repositories where inputs to the study are stored input_repos = list(set((i.repository for i in self.inputs))) inputs = {} for input in self.inputs: # @ReservedAssignment inputs[input.name] = { 'repository_index': input_repos.index(input.repository)} if input.frequency == 'per_study': inputs[input.name]['names'] = next(input.collection).name elif input.frequency == 'per_subject': inputs[input.name]['names'] = {i.subject_id: i.name for i in input.collection} elif input.frequency == 'per_visit': inputs[input.name]['names'] = {i.visit_id: i.name for i in input.collection} elif input.frequency == 'per_session': names = defaultdict(dict) for item in input.collection: names[item.subject_id][item.visit_id] = item.name # Convert from defaultdict to dict inputs[input.name]['names'] = dict(names.items()) return { 'name': self.name, 'type': get_class_info(type(self)), 'parameters': {p.name: p.value for p in self.parameters}, 'inputs': inputs, 'environment': self.environment.prov, 'repositories': [r.prov for r in input_repos], 'processor': self.processor.prov, 'subject_ids': self.subject_ids, 'visit_ids': self.visit_ids}
python
def prov(self): """ Extracts provenance information from the study for storage alongside generated derivatives. Typically for reference purposes only as only the pipeline workflow, inputs and outputs are checked by default when determining which sessions require reprocessing. Returns ------- prov : dict[str, *] A dictionary containing the provenance information to record for the study """ # Get list of repositories where inputs to the study are stored input_repos = list(set((i.repository for i in self.inputs))) inputs = {} for input in self.inputs: # @ReservedAssignment inputs[input.name] = { 'repository_index': input_repos.index(input.repository)} if input.frequency == 'per_study': inputs[input.name]['names'] = next(input.collection).name elif input.frequency == 'per_subject': inputs[input.name]['names'] = {i.subject_id: i.name for i in input.collection} elif input.frequency == 'per_visit': inputs[input.name]['names'] = {i.visit_id: i.name for i in input.collection} elif input.frequency == 'per_session': names = defaultdict(dict) for item in input.collection: names[item.subject_id][item.visit_id] = item.name # Convert from defaultdict to dict inputs[input.name]['names'] = dict(names.items()) return { 'name': self.name, 'type': get_class_info(type(self)), 'parameters': {p.name: p.value for p in self.parameters}, 'inputs': inputs, 'environment': self.environment.prov, 'repositories': [r.prov for r in input_repos], 'processor': self.processor.prov, 'subject_ids': self.subject_ids, 'visit_ids': self.visit_ids}
[ "def", "prov", "(", "self", ")", ":", "# Get list of repositories where inputs to the study are stored", "input_repos", "=", "list", "(", "set", "(", "(", "i", ".", "repository", "for", "i", "in", "self", ".", "inputs", ")", ")", ")", "inputs", "=", "{", "}"...
Extracts provenance information from the study for storage alongside generated derivatives. Typically for reference purposes only as only the pipeline workflow, inputs and outputs are checked by default when determining which sessions require reprocessing. Returns ------- prov : dict[str, *] A dictionary containing the provenance information to record for the study
[ "Extracts", "provenance", "information", "from", "the", "study", "for", "storage", "alongside", "generated", "derivatives", ".", "Typically", "for", "reference", "purposes", "only", "as", "only", "the", "pipeline", "workflow", "inputs", "and", "outputs", "are", "c...
d6271a29d13733d00422d11417af8d200be62acc
https://github.com/MonashBI/arcana/blob/d6271a29d13733d00422d11417af8d200be62acc/arcana/study/base.py#L897-L939
train
51,744
gwww/elkm1
elkm1_lib/areas.py
Area.display_message
def display_message(self, clear, beep, timeout, line1, line2): """Display a message on all of the keypads in this area.""" self._elk.send( dm_encode(self._index, clear, beep, timeout, line1, line2) )
python
def display_message(self, clear, beep, timeout, line1, line2): """Display a message on all of the keypads in this area.""" self._elk.send( dm_encode(self._index, clear, beep, timeout, line1, line2) )
[ "def", "display_message", "(", "self", ",", "clear", ",", "beep", ",", "timeout", ",", "line1", ",", "line2", ")", ":", "self", ".", "_elk", ".", "send", "(", "dm_encode", "(", "self", ".", "_index", ",", "clear", ",", "beep", ",", "timeout", ",", ...
Display a message on all of the keypads in this area.
[ "Display", "a", "message", "on", "all", "of", "the", "keypads", "in", "this", "area", "." ]
078d0de30840c3fab46f1f8534d98df557931e91
https://github.com/gwww/elkm1/blob/078d0de30840c3fab46f1f8534d98df557931e91/elkm1_lib/areas.py#L28-L32
train
51,745
gwww/elkm1
elkm1_lib/lights.py
Lights.sync
def sync(self): """Retrieve lights from ElkM1""" for i in range(4): self.elk.send(ps_encode(i)) self.get_descriptions(TextDescriptions.LIGHT.value)
python
def sync(self): """Retrieve lights from ElkM1""" for i in range(4): self.elk.send(ps_encode(i)) self.get_descriptions(TextDescriptions.LIGHT.value)
[ "def", "sync", "(", "self", ")", ":", "for", "i", "in", "range", "(", "4", ")", ":", "self", ".", "elk", ".", "send", "(", "ps_encode", "(", "i", ")", ")", "self", ".", "get_descriptions", "(", "TextDescriptions", ".", "LIGHT", ".", "value", ")" ]
Retrieve lights from ElkM1
[ "Retrieve", "lights", "from", "ElkM1" ]
078d0de30840c3fab46f1f8534d98df557931e91
https://github.com/gwww/elkm1/blob/078d0de30840c3fab46f1f8534d98df557931e91/elkm1_lib/lights.py#L35-L39
train
51,746
MonashBI/arcana
arcana/utils/base.py
split_extension
def split_extension(path): """ A extension splitter that checks for compound extensions such as 'file.nii.gz' Parameters ---------- filename : str A filename to split into base and extension Returns ------- base : str The base part of the string, i.e. 'file' of 'file.nii.gz' ext : str The extension part of the string, i.e. 'nii.gz' of 'file.nii.gz' """ for double_ext in double_exts: if path.endswith(double_ext): return path[:-len(double_ext)], double_ext dirname = os.path.dirname(path) filename = os.path.basename(path) parts = filename.split('.') if len(parts) == 1: base = filename ext = None else: ext = '.' + parts[-1] base = '.'.join(parts[:-1]) return os.path.join(dirname, base), ext
python
def split_extension(path): """ A extension splitter that checks for compound extensions such as 'file.nii.gz' Parameters ---------- filename : str A filename to split into base and extension Returns ------- base : str The base part of the string, i.e. 'file' of 'file.nii.gz' ext : str The extension part of the string, i.e. 'nii.gz' of 'file.nii.gz' """ for double_ext in double_exts: if path.endswith(double_ext): return path[:-len(double_ext)], double_ext dirname = os.path.dirname(path) filename = os.path.basename(path) parts = filename.split('.') if len(parts) == 1: base = filename ext = None else: ext = '.' + parts[-1] base = '.'.join(parts[:-1]) return os.path.join(dirname, base), ext
[ "def", "split_extension", "(", "path", ")", ":", "for", "double_ext", "in", "double_exts", ":", "if", "path", ".", "endswith", "(", "double_ext", ")", ":", "return", "path", "[", ":", "-", "len", "(", "double_ext", ")", "]", ",", "double_ext", "dirname",...
A extension splitter that checks for compound extensions such as 'file.nii.gz' Parameters ---------- filename : str A filename to split into base and extension Returns ------- base : str The base part of the string, i.e. 'file' of 'file.nii.gz' ext : str The extension part of the string, i.e. 'nii.gz' of 'file.nii.gz'
[ "A", "extension", "splitter", "that", "checks", "for", "compound", "extensions", "such", "as", "file", ".", "nii", ".", "gz" ]
d6271a29d13733d00422d11417af8d200be62acc
https://github.com/MonashBI/arcana/blob/d6271a29d13733d00422d11417af8d200be62acc/arcana/utils/base.py#L45-L74
train
51,747
MonashBI/arcana
arcana/utils/base.py
parse_single_value
def parse_single_value(value): """ Tries to convert to int, float and then gives up and assumes the value is of type string. Useful when excepting values that may be string representations of numerical values """ if isinstance(value, basestring): try: if value.startswith('"') and value.endswith('"'): value = str(value[1:-1]) elif '.' in value: value = float(value) else: value = int(value) except ValueError: value = str(value) elif not isinstance(value, (int, float)): raise ArcanaUsageError( "Unrecognised type for single value {}".format(value)) return value
python
def parse_single_value(value): """ Tries to convert to int, float and then gives up and assumes the value is of type string. Useful when excepting values that may be string representations of numerical values """ if isinstance(value, basestring): try: if value.startswith('"') and value.endswith('"'): value = str(value[1:-1]) elif '.' in value: value = float(value) else: value = int(value) except ValueError: value = str(value) elif not isinstance(value, (int, float)): raise ArcanaUsageError( "Unrecognised type for single value {}".format(value)) return value
[ "def", "parse_single_value", "(", "value", ")", ":", "if", "isinstance", "(", "value", ",", "basestring", ")", ":", "try", ":", "if", "value", ".", "startswith", "(", "'\"'", ")", "and", "value", ".", "endswith", "(", "'\"'", ")", ":", "value", "=", ...
Tries to convert to int, float and then gives up and assumes the value is of type string. Useful when excepting values that may be string representations of numerical values
[ "Tries", "to", "convert", "to", "int", "float", "and", "then", "gives", "up", "and", "assumes", "the", "value", "is", "of", "type", "string", ".", "Useful", "when", "excepting", "values", "that", "may", "be", "string", "representations", "of", "numerical", ...
d6271a29d13733d00422d11417af8d200be62acc
https://github.com/MonashBI/arcana/blob/d6271a29d13733d00422d11417af8d200be62acc/arcana/utils/base.py#L103-L122
train
51,748
erikvw/django-collect-offline
django_collect_offline/signals.py
serialize_m2m_on_save
def serialize_m2m_on_save(sender, action, instance, using, **kwargs): """ Part of the serialize transaction process that ensures m2m are serialized correctly. Skip those not registered. """ if action == "post_add": try: wrapped_instance = site_offline_models.get_wrapped_instance(instance) except ModelNotRegistered: pass else: wrapped_instance.to_outgoing_transaction(using, created=True)
python
def serialize_m2m_on_save(sender, action, instance, using, **kwargs): """ Part of the serialize transaction process that ensures m2m are serialized correctly. Skip those not registered. """ if action == "post_add": try: wrapped_instance = site_offline_models.get_wrapped_instance(instance) except ModelNotRegistered: pass else: wrapped_instance.to_outgoing_transaction(using, created=True)
[ "def", "serialize_m2m_on_save", "(", "sender", ",", "action", ",", "instance", ",", "using", ",", "*", "*", "kwargs", ")", ":", "if", "action", "==", "\"post_add\"", ":", "try", ":", "wrapped_instance", "=", "site_offline_models", ".", "get_wrapped_instance", ...
Part of the serialize transaction process that ensures m2m are serialized correctly. Skip those not registered.
[ "Part", "of", "the", "serialize", "transaction", "process", "that", "ensures", "m2m", "are", "serialized", "correctly", "." ]
3d5efd66c68e2db4b060a82b070ae490dc399ca7
https://github.com/erikvw/django-collect-offline/blob/3d5efd66c68e2db4b060a82b070ae490dc399ca7/django_collect_offline/signals.py#L19-L31
train
51,749
erikvw/django-collect-offline
django_collect_offline/signals.py
serialize_on_save
def serialize_on_save(sender, instance, raw, created, using, **kwargs): """ Serialize the model instance as an OutgoingTransaction. Skip those not registered. """ if not raw: if "historical" not in instance._meta.label_lower: try: wrapped_instance = site_offline_models.get_wrapped_instance(instance) except ModelNotRegistered: pass else: wrapped_instance.to_outgoing_transaction(using, created=created)
python
def serialize_on_save(sender, instance, raw, created, using, **kwargs): """ Serialize the model instance as an OutgoingTransaction. Skip those not registered. """ if not raw: if "historical" not in instance._meta.label_lower: try: wrapped_instance = site_offline_models.get_wrapped_instance(instance) except ModelNotRegistered: pass else: wrapped_instance.to_outgoing_transaction(using, created=created)
[ "def", "serialize_on_save", "(", "sender", ",", "instance", ",", "raw", ",", "created", ",", "using", ",", "*", "*", "kwargs", ")", ":", "if", "not", "raw", ":", "if", "\"historical\"", "not", "in", "instance", ".", "_meta", ".", "label_lower", ":", "t...
Serialize the model instance as an OutgoingTransaction. Skip those not registered.
[ "Serialize", "the", "model", "instance", "as", "an", "OutgoingTransaction", "." ]
3d5efd66c68e2db4b060a82b070ae490dc399ca7
https://github.com/erikvw/django-collect-offline/blob/3d5efd66c68e2db4b060a82b070ae490dc399ca7/django_collect_offline/signals.py#L35-L47
train
51,750
erikvw/django-collect-offline
django_collect_offline/signals.py
serialize_history_on_post_create
def serialize_history_on_post_create(history_instance, using, **kwargs): """ Serialize the history instance as an OutgoingTransaction. Skip those not registered. """ try: wrapped_instance = site_offline_models.get_wrapped_instance(history_instance) except ModelNotRegistered: pass else: wrapped_instance.to_outgoing_transaction(using, created=True)
python
def serialize_history_on_post_create(history_instance, using, **kwargs): """ Serialize the history instance as an OutgoingTransaction. Skip those not registered. """ try: wrapped_instance = site_offline_models.get_wrapped_instance(history_instance) except ModelNotRegistered: pass else: wrapped_instance.to_outgoing_transaction(using, created=True)
[ "def", "serialize_history_on_post_create", "(", "history_instance", ",", "using", ",", "*", "*", "kwargs", ")", ":", "try", ":", "wrapped_instance", "=", "site_offline_models", ".", "get_wrapped_instance", "(", "history_instance", ")", "except", "ModelNotRegistered", ...
Serialize the history instance as an OutgoingTransaction. Skip those not registered.
[ "Serialize", "the", "history", "instance", "as", "an", "OutgoingTransaction", "." ]
3d5efd66c68e2db4b060a82b070ae490dc399ca7
https://github.com/erikvw/django-collect-offline/blob/3d5efd66c68e2db4b060a82b070ae490dc399ca7/django_collect_offline/signals.py#L55-L65
train
51,751
erikvw/django-collect-offline
django_collect_offline/signals.py
serialize_on_post_delete
def serialize_on_post_delete(sender, instance, using, **kwargs): """Creates a serialized OutgoingTransaction when a model instance is deleted. Skip those not registered. """ try: wrapped_instance = site_offline_models.get_wrapped_instance(instance) except ModelNotRegistered: pass else: wrapped_instance.to_outgoing_transaction(using, created=False, deleted=True)
python
def serialize_on_post_delete(sender, instance, using, **kwargs): """Creates a serialized OutgoingTransaction when a model instance is deleted. Skip those not registered. """ try: wrapped_instance = site_offline_models.get_wrapped_instance(instance) except ModelNotRegistered: pass else: wrapped_instance.to_outgoing_transaction(using, created=False, deleted=True)
[ "def", "serialize_on_post_delete", "(", "sender", ",", "instance", ",", "using", ",", "*", "*", "kwargs", ")", ":", "try", ":", "wrapped_instance", "=", "site_offline_models", ".", "get_wrapped_instance", "(", "instance", ")", "except", "ModelNotRegistered", ":", ...
Creates a serialized OutgoingTransaction when a model instance is deleted. Skip those not registered.
[ "Creates", "a", "serialized", "OutgoingTransaction", "when", "a", "model", "instance", "is", "deleted", "." ]
3d5efd66c68e2db4b060a82b070ae490dc399ca7
https://github.com/erikvw/django-collect-offline/blob/3d5efd66c68e2db4b060a82b070ae490dc399ca7/django_collect_offline/signals.py#L69-L80
train
51,752
gwww/elkm1
elkm1_lib/settings.py
Settings.sync
def sync(self): """Retrieve custom values from ElkM1""" self.elk.send(cp_encode()) self.get_descriptions(TextDescriptions.SETTING.value)
python
def sync(self): """Retrieve custom values from ElkM1""" self.elk.send(cp_encode()) self.get_descriptions(TextDescriptions.SETTING.value)
[ "def", "sync", "(", "self", ")", ":", "self", ".", "elk", ".", "send", "(", "cp_encode", "(", ")", ")", "self", ".", "get_descriptions", "(", "TextDescriptions", ".", "SETTING", ".", "value", ")" ]
Retrieve custom values from ElkM1
[ "Retrieve", "custom", "values", "from", "ElkM1" ]
078d0de30840c3fab46f1f8534d98df557931e91
https://github.com/gwww/elkm1/blob/078d0de30840c3fab46f1f8534d98df557931e91/elkm1_lib/settings.py#L25-L28
train
51,753
MonashBI/arcana
arcana/data/item.py
Fileset.paths
def paths(self): """Iterates through all files in the set""" if self.format is None: raise ArcanaFileFormatError( "Cannot get paths of fileset ({}) that hasn't had its format " "set".format(self)) if self.format.directory: return chain(*((op.join(root, f) for f in files) for root, _, files in os.walk(self.path))) else: return chain([self.path], self.aux_files.values())
python
def paths(self): """Iterates through all files in the set""" if self.format is None: raise ArcanaFileFormatError( "Cannot get paths of fileset ({}) that hasn't had its format " "set".format(self)) if self.format.directory: return chain(*((op.join(root, f) for f in files) for root, _, files in os.walk(self.path))) else: return chain([self.path], self.aux_files.values())
[ "def", "paths", "(", "self", ")", ":", "if", "self", ".", "format", "is", "None", ":", "raise", "ArcanaFileFormatError", "(", "\"Cannot get paths of fileset ({}) that hasn't had its format \"", "\"set\"", ".", "format", "(", "self", ")", ")", "if", "self", ".", ...
Iterates through all files in the set
[ "Iterates", "through", "all", "files", "in", "the", "set" ]
d6271a29d13733d00422d11417af8d200be62acc
https://github.com/MonashBI/arcana/blob/d6271a29d13733d00422d11417af8d200be62acc/arcana/data/item.py#L371-L381
train
51,754
MonashBI/arcana
arcana/data/item.py
Fileset.contents_equal
def contents_equal(self, other, **kwargs): """ Test the equality of the fileset contents with another fileset. If the fileset's format implements a 'contents_equal' method than that is used to determine the equality, otherwise a straight comparison of the checksums is used. Parameters ---------- other : Fileset The other fileset to compare to """ if hasattr(self.format, 'contents_equal'): equal = self.format.contents_equal(self, other, **kwargs) else: equal = (self.checksums == other.checksums) return equal
python
def contents_equal(self, other, **kwargs): """ Test the equality of the fileset contents with another fileset. If the fileset's format implements a 'contents_equal' method than that is used to determine the equality, otherwise a straight comparison of the checksums is used. Parameters ---------- other : Fileset The other fileset to compare to """ if hasattr(self.format, 'contents_equal'): equal = self.format.contents_equal(self, other, **kwargs) else: equal = (self.checksums == other.checksums) return equal
[ "def", "contents_equal", "(", "self", ",", "other", ",", "*", "*", "kwargs", ")", ":", "if", "hasattr", "(", "self", ".", "format", ",", "'contents_equal'", ")", ":", "equal", "=", "self", ".", "format", ".", "contents_equal", "(", "self", ",", "other"...
Test the equality of the fileset contents with another fileset. If the fileset's format implements a 'contents_equal' method than that is used to determine the equality, otherwise a straight comparison of the checksums is used. Parameters ---------- other : Fileset The other fileset to compare to
[ "Test", "the", "equality", "of", "the", "fileset", "contents", "with", "another", "fileset", ".", "If", "the", "fileset", "s", "format", "implements", "a", "contents_equal", "method", "than", "that", "is", "used", "to", "determine", "the", "equality", "otherwi...
d6271a29d13733d00422d11417af8d200be62acc
https://github.com/MonashBI/arcana/blob/d6271a29d13733d00422d11417af8d200be62acc/arcana/data/item.py#L542-L558
train
51,755
MonashBI/arcana
arcana/data/spec.py
BaseInputSpec.bind
def bind(self, study, **kwargs): # @UnusedVariable """ Returns a copy of the AcquiredSpec bound to the given study Parameters ---------- study : Study A study to bind the fileset spec to (should happen in the study __init__) """ if self.default is None: raise ArcanaError( "Attempted to bind '{}' to {} but only acquired specs with " "a default value should be bound to studies{})".format( self.name, study)) if self._study is not None: # This avoids rebinding specs to sub-studies that have already # been bound to the multi-study bound = self else: bound = copy(self) bound._study = study bound._default = bound.default.bind(study) return bound
python
def bind(self, study, **kwargs): # @UnusedVariable """ Returns a copy of the AcquiredSpec bound to the given study Parameters ---------- study : Study A study to bind the fileset spec to (should happen in the study __init__) """ if self.default is None: raise ArcanaError( "Attempted to bind '{}' to {} but only acquired specs with " "a default value should be bound to studies{})".format( self.name, study)) if self._study is not None: # This avoids rebinding specs to sub-studies that have already # been bound to the multi-study bound = self else: bound = copy(self) bound._study = study bound._default = bound.default.bind(study) return bound
[ "def", "bind", "(", "self", ",", "study", ",", "*", "*", "kwargs", ")", ":", "# @UnusedVariable", "if", "self", ".", "default", "is", "None", ":", "raise", "ArcanaError", "(", "\"Attempted to bind '{}' to {} but only acquired specs with \"", "\"a default value should ...
Returns a copy of the AcquiredSpec bound to the given study Parameters ---------- study : Study A study to bind the fileset spec to (should happen in the study __init__)
[ "Returns", "a", "copy", "of", "the", "AcquiredSpec", "bound", "to", "the", "given", "study" ]
d6271a29d13733d00422d11417af8d200be62acc
https://github.com/MonashBI/arcana/blob/d6271a29d13733d00422d11417af8d200be62acc/arcana/data/spec.py#L73-L96
train
51,756
MonashBI/arcana
arcana/data/spec.py
BaseSpec.bind
def bind(self, study, **kwargs): # @UnusedVariable """ Returns a copy of the Spec bound to the given study Parameters ---------- study : Study A study to bind the fileset spec to (should happen in the study __init__) """ if self._study is not None: # Avoid rebinding specs in sub-studies that have already # been bound to MultiStudy bound = self else: bound = copy(self) bound._study = study if not hasattr(study, self.pipeline_getter): raise ArcanaError( "{} does not have a method named '{}' required to " "derive {}".format(study, self.pipeline_getter, self)) bound._bind_tree(study.tree) return bound
python
def bind(self, study, **kwargs): # @UnusedVariable """ Returns a copy of the Spec bound to the given study Parameters ---------- study : Study A study to bind the fileset spec to (should happen in the study __init__) """ if self._study is not None: # Avoid rebinding specs in sub-studies that have already # been bound to MultiStudy bound = self else: bound = copy(self) bound._study = study if not hasattr(study, self.pipeline_getter): raise ArcanaError( "{} does not have a method named '{}' required to " "derive {}".format(study, self.pipeline_getter, self)) bound._bind_tree(study.tree) return bound
[ "def", "bind", "(", "self", ",", "study", ",", "*", "*", "kwargs", ")", ":", "# @UnusedVariable", "if", "self", ".", "_study", "is", "not", "None", ":", "# Avoid rebinding specs in sub-studies that have already", "# been bound to MultiStudy", "bound", "=", "self", ...
Returns a copy of the Spec bound to the given study Parameters ---------- study : Study A study to bind the fileset spec to (should happen in the study __init__)
[ "Returns", "a", "copy", "of", "the", "Spec", "bound", "to", "the", "given", "study" ]
d6271a29d13733d00422d11417af8d200be62acc
https://github.com/MonashBI/arcana/blob/d6271a29d13733d00422d11417af8d200be62acc/arcana/data/spec.py#L179-L202
train
51,757
MonashBI/arcana
arcana/data/spec.py
BaseSpec.nodes
def nodes(self, tree): """ Returns the relevant nodes for the spec's frequency """ # Run the match against the tree if self.frequency == 'per_session': nodes = [] for subject in tree.subjects: for sess in subject.sessions: nodes.append(sess) elif self.frequency == 'per_subject': nodes = tree.subjects elif self.frequency == 'per_visit': nodes = tree.visits elif self.frequency == 'per_study': nodes = [tree] else: assert False, "Unrecognised frequency '{}'".format( self.frequency) return nodes
python
def nodes(self, tree): """ Returns the relevant nodes for the spec's frequency """ # Run the match against the tree if self.frequency == 'per_session': nodes = [] for subject in tree.subjects: for sess in subject.sessions: nodes.append(sess) elif self.frequency == 'per_subject': nodes = tree.subjects elif self.frequency == 'per_visit': nodes = tree.visits elif self.frequency == 'per_study': nodes = [tree] else: assert False, "Unrecognised frequency '{}'".format( self.frequency) return nodes
[ "def", "nodes", "(", "self", ",", "tree", ")", ":", "# Run the match against the tree", "if", "self", ".", "frequency", "==", "'per_session'", ":", "nodes", "=", "[", "]", "for", "subject", "in", "tree", ".", "subjects", ":", "for", "sess", "in", "subject"...
Returns the relevant nodes for the spec's frequency
[ "Returns", "the", "relevant", "nodes", "for", "the", "spec", "s", "frequency" ]
d6271a29d13733d00422d11417af8d200be62acc
https://github.com/MonashBI/arcana/blob/d6271a29d13733d00422d11417af8d200be62acc/arcana/data/spec.py#L212-L231
train
51,758
RedHatQE/python-stitches
stitches/structure.py
Structure.reconnect_all
def reconnect_all(self): """ Re-establish connection to all instances """ for role in self.Instances.keys(): for connection in self.Instances[role]: connection.reconnect()
python
def reconnect_all(self): """ Re-establish connection to all instances """ for role in self.Instances.keys(): for connection in self.Instances[role]: connection.reconnect()
[ "def", "reconnect_all", "(", "self", ")", ":", "for", "role", "in", "self", ".", "Instances", ".", "keys", "(", ")", ":", "for", "connection", "in", "self", ".", "Instances", "[", "role", "]", ":", "connection", ".", "reconnect", "(", ")" ]
Re-establish connection to all instances
[ "Re", "-", "establish", "connection", "to", "all", "instances" ]
957e9895e64ffd3b8157b38b9cce414969509288
https://github.com/RedHatQE/python-stitches/blob/957e9895e64ffd3b8157b38b9cce414969509288/stitches/structure.py#L30-L36
train
51,759
RedHatQE/python-stitches
stitches/structure.py
Structure.add_instance
def add_instance(self, role, instance, username='root', key_filename=None, output_shell=False): """ Add instance to the setup @param role: instance's role @type role: str @param instance: host parameters we would like to establish connection to @type instance: dict @param username: user name for creating ssh connection @type username: str @param key_filename: file name with ssh private key @type key_filename: str @param output_shell: write output from this connection to standard output @type output_shell: bool """ if not role in self.Instances.keys(): self.Instances[role] = [] self.logger.debug('Adding ' + role + ' with private_hostname ' + instance['private_hostname'] + ', public_hostname ' + instance['public_hostname']) self.Instances[role].append(Connection(instance, username, key_filename, output_shell=output_shell))
python
def add_instance(self, role, instance, username='root', key_filename=None, output_shell=False): """ Add instance to the setup @param role: instance's role @type role: str @param instance: host parameters we would like to establish connection to @type instance: dict @param username: user name for creating ssh connection @type username: str @param key_filename: file name with ssh private key @type key_filename: str @param output_shell: write output from this connection to standard output @type output_shell: bool """ if not role in self.Instances.keys(): self.Instances[role] = [] self.logger.debug('Adding ' + role + ' with private_hostname ' + instance['private_hostname'] + ', public_hostname ' + instance['public_hostname']) self.Instances[role].append(Connection(instance, username, key_filename, output_shell=output_shell))
[ "def", "add_instance", "(", "self", ",", "role", ",", "instance", ",", "username", "=", "'root'", ",", "key_filename", "=", "None", ",", "output_shell", "=", "False", ")", ":", "if", "not", "role", "in", "self", ".", "Instances", ".", "keys", "(", ")",...
Add instance to the setup @param role: instance's role @type role: str @param instance: host parameters we would like to establish connection to @type instance: dict @param username: user name for creating ssh connection @type username: str @param key_filename: file name with ssh private key @type key_filename: str @param output_shell: write output from this connection to standard output @type output_shell: bool
[ "Add", "instance", "to", "the", "setup" ]
957e9895e64ffd3b8157b38b9cce414969509288
https://github.com/RedHatQE/python-stitches/blob/957e9895e64ffd3b8157b38b9cce414969509288/stitches/structure.py#L38-L72
train
51,760
RedHatQE/python-stitches
stitches/structure.py
Structure.setup_from_yamlfile
def setup_from_yamlfile(self, yamlfile, output_shell=False): """ Setup from yaml config @param yamlfile: path to yaml config file @type yamlfile: str @param output_shell: write output from this connection to standard output @type output_shell: bool """ self.logger.debug('Loading config from ' + yamlfile) with open(yamlfile, 'r') as yamlfd: yamlconfig = yaml.load(yamlfd) for instance in yamlconfig['Instances']: self.add_instance(instance['role'].upper(), instance, output_shell=output_shell) if 'Config' in yamlconfig.keys(): self.logger.debug('Config found: ' + str(yamlconfig['Config'])) self.config = yamlconfig['Config'].copy()
python
def setup_from_yamlfile(self, yamlfile, output_shell=False): """ Setup from yaml config @param yamlfile: path to yaml config file @type yamlfile: str @param output_shell: write output from this connection to standard output @type output_shell: bool """ self.logger.debug('Loading config from ' + yamlfile) with open(yamlfile, 'r') as yamlfd: yamlconfig = yaml.load(yamlfd) for instance in yamlconfig['Instances']: self.add_instance(instance['role'].upper(), instance, output_shell=output_shell) if 'Config' in yamlconfig.keys(): self.logger.debug('Config found: ' + str(yamlconfig['Config'])) self.config = yamlconfig['Config'].copy()
[ "def", "setup_from_yamlfile", "(", "self", ",", "yamlfile", ",", "output_shell", "=", "False", ")", ":", "self", ".", "logger", ".", "debug", "(", "'Loading config from '", "+", "yamlfile", ")", "with", "open", "(", "yamlfile", ",", "'r'", ")", "as", "yaml...
Setup from yaml config @param yamlfile: path to yaml config file @type yamlfile: str @param output_shell: write output from this connection to standard output @type output_shell: bool
[ "Setup", "from", "yaml", "config" ]
957e9895e64ffd3b8157b38b9cce414969509288
https://github.com/RedHatQE/python-stitches/blob/957e9895e64ffd3b8157b38b9cce414969509288/stitches/structure.py#L74-L94
train
51,761
brentp/toolshed
toolshed/files.py
process_iter
def process_iter(proc, cmd=""): """ helper function to iterate over a process stdout and report error messages when done """ try: for l in proc.stdout: yield l finally: if proc.poll() is None: # there was an exception return else: proc.wait() if proc.returncode not in (0, None, signal.SIGPIPE, signal.SIGPIPE + 128): sys.stderr.write("cmd was:%s\n" % cmd) sys.stderr.write("return code was:%s\n" % proc.returncode) raise ProcessException(cmd)
python
def process_iter(proc, cmd=""): """ helper function to iterate over a process stdout and report error messages when done """ try: for l in proc.stdout: yield l finally: if proc.poll() is None: # there was an exception return else: proc.wait() if proc.returncode not in (0, None, signal.SIGPIPE, signal.SIGPIPE + 128): sys.stderr.write("cmd was:%s\n" % cmd) sys.stderr.write("return code was:%s\n" % proc.returncode) raise ProcessException(cmd)
[ "def", "process_iter", "(", "proc", ",", "cmd", "=", "\"\"", ")", ":", "try", ":", "for", "l", "in", "proc", ".", "stdout", ":", "yield", "l", "finally", ":", "if", "proc", ".", "poll", "(", ")", "is", "None", ":", "# there was an exception", "return...
helper function to iterate over a process stdout and report error messages when done
[ "helper", "function", "to", "iterate", "over", "a", "process", "stdout", "and", "report", "error", "messages", "when", "done" ]
c9529d6872bf28207642896c3b416f68e79b1269
https://github.com/brentp/toolshed/blob/c9529d6872bf28207642896c3b416f68e79b1269/toolshed/files.py#L44-L61
train
51,762
brentp/toolshed
toolshed/files.py
header
def header(fname, sep="\t"): """ just grab the header from a given file """ fh = iter(nopen(fname)) h = tokens(next(fh), sep) h[0] = h[0].lstrip("#") return h
python
def header(fname, sep="\t"): """ just grab the header from a given file """ fh = iter(nopen(fname)) h = tokens(next(fh), sep) h[0] = h[0].lstrip("#") return h
[ "def", "header", "(", "fname", ",", "sep", "=", "\"\\t\"", ")", ":", "fh", "=", "iter", "(", "nopen", "(", "fname", ")", ")", "h", "=", "tokens", "(", "next", "(", "fh", ")", ",", "sep", ")", "h", "[", "0", "]", "=", "h", "[", "0", "]", "...
just grab the header from a given file
[ "just", "grab", "the", "header", "from", "a", "given", "file" ]
c9529d6872bf28207642896c3b416f68e79b1269
https://github.com/brentp/toolshed/blob/c9529d6872bf28207642896c3b416f68e79b1269/toolshed/files.py#L164-L171
train
51,763
brentp/toolshed
toolshed/files.py
is_newer_b
def is_newer_b(a, bfiles): """ check that all b files have been modified more recently than a """ if isinstance(bfiles, basestring): bfiles = [bfiles] if not op.exists(a): return False if not all(op.exists(b) for b in bfiles): return False atime = os.stat(a).st_mtime # modification time for b in bfiles: # a has been modified since if atime > os.stat(b).st_mtime: return False return True
python
def is_newer_b(a, bfiles): """ check that all b files have been modified more recently than a """ if isinstance(bfiles, basestring): bfiles = [bfiles] if not op.exists(a): return False if not all(op.exists(b) for b in bfiles): return False atime = os.stat(a).st_mtime # modification time for b in bfiles: # a has been modified since if atime > os.stat(b).st_mtime: return False return True
[ "def", "is_newer_b", "(", "a", ",", "bfiles", ")", ":", "if", "isinstance", "(", "bfiles", ",", "basestring", ")", ":", "bfiles", "=", "[", "bfiles", "]", "if", "not", "op", ".", "exists", "(", "a", ")", ":", "return", "False", "if", "not", "all", ...
check that all b files have been modified more recently than a
[ "check", "that", "all", "b", "files", "have", "been", "modified", "more", "recently", "than", "a" ]
c9529d6872bf28207642896c3b416f68e79b1269
https://github.com/brentp/toolshed/blob/c9529d6872bf28207642896c3b416f68e79b1269/toolshed/files.py#L284-L299
train
51,764
RedHatQE/python-stitches
stitches/expect.py
Expect.expect_list
def expect_list(connection, regexp_list, timeout=10): ''' Expect a list of expressions @param connection: Connection to the host @type connection: L{Connection} @param regexp_list: regular expressions and associated return values @type regexp_list: list of (regexp, return value) @param timeout: timeout for performing expect operation @type timeout: int @return: propper return value from regexp_list @rtype: return value @raises ExpectFailed ''' result = "" count = 0 while count < timeout: try: recv_part = connection.channel.recv(32768).decode() logging.getLogger('stitches.expect').debug("RCV: " + recv_part) if connection.output_shell: sys.stdout.write(recv_part) result += recv_part except socket.timeout: # socket.timeout here means 'no more data' pass for (regexp, retvalue) in regexp_list: # search for the first matching regexp and return desired value if re.match(regexp, result): return retvalue time.sleep(1) count += 1 raise ExpectFailed(result)
python
def expect_list(connection, regexp_list, timeout=10): ''' Expect a list of expressions @param connection: Connection to the host @type connection: L{Connection} @param regexp_list: regular expressions and associated return values @type regexp_list: list of (regexp, return value) @param timeout: timeout for performing expect operation @type timeout: int @return: propper return value from regexp_list @rtype: return value @raises ExpectFailed ''' result = "" count = 0 while count < timeout: try: recv_part = connection.channel.recv(32768).decode() logging.getLogger('stitches.expect').debug("RCV: " + recv_part) if connection.output_shell: sys.stdout.write(recv_part) result += recv_part except socket.timeout: # socket.timeout here means 'no more data' pass for (regexp, retvalue) in regexp_list: # search for the first matching regexp and return desired value if re.match(regexp, result): return retvalue time.sleep(1) count += 1 raise ExpectFailed(result)
[ "def", "expect_list", "(", "connection", ",", "regexp_list", ",", "timeout", "=", "10", ")", ":", "result", "=", "\"\"", "count", "=", "0", "while", "count", "<", "timeout", ":", "try", ":", "recv_part", "=", "connection", ".", "channel", ".", "recv", ...
Expect a list of expressions @param connection: Connection to the host @type connection: L{Connection} @param regexp_list: regular expressions and associated return values @type regexp_list: list of (regexp, return value) @param timeout: timeout for performing expect operation @type timeout: int @return: propper return value from regexp_list @rtype: return value @raises ExpectFailed
[ "Expect", "a", "list", "of", "expressions" ]
957e9895e64ffd3b8157b38b9cce414969509288
https://github.com/RedHatQE/python-stitches/blob/957e9895e64ffd3b8157b38b9cce414969509288/stitches/expect.py#L26-L63
train
51,765
RedHatQE/python-stitches
stitches/expect.py
Expect.expect
def expect(connection, strexp, timeout=10): ''' Expect one expression @param connection: Connection to the host @type connection: L{Connection} @param strexp: string to convert to expression (.*string.*) @type strexp: str @param timeout: timeout for performing expect operation @type timeout: int @return: True if succeeded @rtype: bool @raises ExpectFailed ''' return Expect.expect_list(connection, [(re.compile(".*" + strexp + ".*", re.DOTALL), True)], timeout)
python
def expect(connection, strexp, timeout=10): ''' Expect one expression @param connection: Connection to the host @type connection: L{Connection} @param strexp: string to convert to expression (.*string.*) @type strexp: str @param timeout: timeout for performing expect operation @type timeout: int @return: True if succeeded @rtype: bool @raises ExpectFailed ''' return Expect.expect_list(connection, [(re.compile(".*" + strexp + ".*", re.DOTALL), True)], timeout)
[ "def", "expect", "(", "connection", ",", "strexp", ",", "timeout", "=", "10", ")", ":", "return", "Expect", ".", "expect_list", "(", "connection", ",", "[", "(", "re", ".", "compile", "(", "\".*\"", "+", "strexp", "+", "\".*\"", ",", "re", ".", "DOTA...
Expect one expression @param connection: Connection to the host @type connection: L{Connection} @param strexp: string to convert to expression (.*string.*) @type strexp: str @param timeout: timeout for performing expect operation @type timeout: int @return: True if succeeded @rtype: bool @raises ExpectFailed
[ "Expect", "one", "expression" ]
957e9895e64ffd3b8157b38b9cce414969509288
https://github.com/RedHatQE/python-stitches/blob/957e9895e64ffd3b8157b38b9cce414969509288/stitches/expect.py#L66-L87
train
51,766
RedHatQE/python-stitches
stitches/expect.py
Expect.match
def match(connection, regexp, grouplist=[1], timeout=10): ''' Match against an expression @param connection: Connection to the host @type connection: L{Connection} @param regexp: compiled regular expression @type regexp: L{SRE_Pattern} @param grouplist: list of groups to return @type group: list of int @param timeout: timeout for performing expect operation @type timeout: int @return: matched string @rtype: str @raises ExpectFailed ''' logging.getLogger('stitches.expect').debug("MATCHING: " + regexp.pattern) result = "" count = 0 while count < timeout: try: recv_part = connection.channel.recv(32768).decode() logging.getLogger('stitches.expect').debug("RCV: " + recv_part) if connection.output_shell: sys.stdout.write(recv_part) result += recv_part except socket.timeout: # socket.timeout here means 'no more data' pass match = regexp.match(result) if match: ret_list = [] for group in grouplist: logging.getLogger('stitches.expect').debug("matched: " + match.group(group)) ret_list.append(match.group(group)) return ret_list time.sleep(1) count += 1 raise ExpectFailed(result)
python
def match(connection, regexp, grouplist=[1], timeout=10): ''' Match against an expression @param connection: Connection to the host @type connection: L{Connection} @param regexp: compiled regular expression @type regexp: L{SRE_Pattern} @param grouplist: list of groups to return @type group: list of int @param timeout: timeout for performing expect operation @type timeout: int @return: matched string @rtype: str @raises ExpectFailed ''' logging.getLogger('stitches.expect').debug("MATCHING: " + regexp.pattern) result = "" count = 0 while count < timeout: try: recv_part = connection.channel.recv(32768).decode() logging.getLogger('stitches.expect').debug("RCV: " + recv_part) if connection.output_shell: sys.stdout.write(recv_part) result += recv_part except socket.timeout: # socket.timeout here means 'no more data' pass match = regexp.match(result) if match: ret_list = [] for group in grouplist: logging.getLogger('stitches.expect').debug("matched: " + match.group(group)) ret_list.append(match.group(group)) return ret_list time.sleep(1) count += 1 raise ExpectFailed(result)
[ "def", "match", "(", "connection", ",", "regexp", ",", "grouplist", "=", "[", "1", "]", ",", "timeout", "=", "10", ")", ":", "logging", ".", "getLogger", "(", "'stitches.expect'", ")", ".", "debug", "(", "\"MATCHING: \"", "+", "regexp", ".", "pattern", ...
Match against an expression @param connection: Connection to the host @type connection: L{Connection} @param regexp: compiled regular expression @type regexp: L{SRE_Pattern} @param grouplist: list of groups to return @type group: list of int @param timeout: timeout for performing expect operation @type timeout: int @return: matched string @rtype: str @raises ExpectFailed
[ "Match", "against", "an", "expression" ]
957e9895e64ffd3b8157b38b9cce414969509288
https://github.com/RedHatQE/python-stitches/blob/957e9895e64ffd3b8157b38b9cce414969509288/stitches/expect.py#L90-L134
train
51,767
RedHatQE/python-stitches
stitches/expect.py
Expect.expect_retval
def expect_retval(connection, command, expected_status=0, timeout=10): ''' Run command and expect specified return valud @param connection: connection to the host @type connection: L{Connection} @param command: command to execute @type command: str @param expected_status: expected return value @type expected_status: int @param timeout: timeout for performing expect operation @type timeout: int @return: return value @rtype: int @raises ExpectFailed ''' retval = connection.recv_exit_status(command, timeout) if retval is None: raise ExpectFailed("Got timeout (%i seconds) while executing '%s'" % (timeout, command)) elif retval != expected_status: raise ExpectFailed("Got %s exit status (%s expected)\ncmd: %s\nstdout: %s\nstderr: %s" % (retval, expected_status, connection.last_command, connection.last_stdout, connection.last_stderr)) if connection.output_shell: sys.stdout.write("Run '%s', got %i return value\n" % (command, retval)) return retval
python
def expect_retval(connection, command, expected_status=0, timeout=10): ''' Run command and expect specified return valud @param connection: connection to the host @type connection: L{Connection} @param command: command to execute @type command: str @param expected_status: expected return value @type expected_status: int @param timeout: timeout for performing expect operation @type timeout: int @return: return value @rtype: int @raises ExpectFailed ''' retval = connection.recv_exit_status(command, timeout) if retval is None: raise ExpectFailed("Got timeout (%i seconds) while executing '%s'" % (timeout, command)) elif retval != expected_status: raise ExpectFailed("Got %s exit status (%s expected)\ncmd: %s\nstdout: %s\nstderr: %s" % (retval, expected_status, connection.last_command, connection.last_stdout, connection.last_stderr)) if connection.output_shell: sys.stdout.write("Run '%s', got %i return value\n" % (command, retval)) return retval
[ "def", "expect_retval", "(", "connection", ",", "command", ",", "expected_status", "=", "0", ",", "timeout", "=", "10", ")", ":", "retval", "=", "connection", ".", "recv_exit_status", "(", "command", ",", "timeout", ")", "if", "retval", "is", "None", ":", ...
Run command and expect specified return valud @param connection: connection to the host @type connection: L{Connection} @param command: command to execute @type command: str @param expected_status: expected return value @type expected_status: int @param timeout: timeout for performing expect operation @type timeout: int @return: return value @rtype: int @raises ExpectFailed
[ "Run", "command", "and", "expect", "specified", "return", "valud" ]
957e9895e64ffd3b8157b38b9cce414969509288
https://github.com/RedHatQE/python-stitches/blob/957e9895e64ffd3b8157b38b9cce414969509288/stitches/expect.py#L179-L211
train
51,768
vedvyas/doxytag2zealdb
doxytag2zealdb/doxytag.py
TagProcessor.find
def find(self, soup): '''Yield tags matching the tag criterion from a soup. There is no need to override this if you are satisfied with finding tags that match match_criterion. Args: soup: A BeautifulSoup to search through. Yields: BeautifulSoup Tags that match the criterion. ''' for tag in soup.recursiveChildGenerator(): if self.match_criterion(tag): yield tag
python
def find(self, soup): '''Yield tags matching the tag criterion from a soup. There is no need to override this if you are satisfied with finding tags that match match_criterion. Args: soup: A BeautifulSoup to search through. Yields: BeautifulSoup Tags that match the criterion. ''' for tag in soup.recursiveChildGenerator(): if self.match_criterion(tag): yield tag
[ "def", "find", "(", "self", ",", "soup", ")", ":", "for", "tag", "in", "soup", ".", "recursiveChildGenerator", "(", ")", ":", "if", "self", ".", "match_criterion", "(", "tag", ")", ":", "yield", "tag" ]
Yield tags matching the tag criterion from a soup. There is no need to override this if you are satisfied with finding tags that match match_criterion. Args: soup: A BeautifulSoup to search through. Yields: BeautifulSoup Tags that match the criterion.
[ "Yield", "tags", "matching", "the", "tag", "criterion", "from", "a", "soup", "." ]
8b07a88af6794248f8cfdabb0fda9dd61c777127
https://github.com/vedvyas/doxytag2zealdb/blob/8b07a88af6794248f8cfdabb0fda9dd61c777127/doxytag2zealdb/doxytag.py#L68-L82
train
51,769
vedvyas/doxytag2zealdb
doxytag2zealdb/doxytag.py
TagProcessor.get_name
def get_name(self, tag): '''Extract and return a representative "name" from a tag. Override as necessary. get_name's output can be controlled through keyword arguments that are provided when initializing a TagProcessor. For instance, a member of a class or namespace can have its parent scope included in the name by passing include_parent_scopes=True to __init__(). Args: tag: A BeautifulSoup Tag that satisfies match_criterion. Returns: A string that would be appropriate to use as an entry name in a Zeal database. ''' name = tag.findChild('name').contents[0] if self.include_parent_scopes: # Include parent scope in returned name parent_tag = tag.findParent() if parent_tag.get('kind') in ['class', 'struct', 'namespace']: name = parent_tag.findChild('name').contents[0] + '::' + name return name
python
def get_name(self, tag): '''Extract and return a representative "name" from a tag. Override as necessary. get_name's output can be controlled through keyword arguments that are provided when initializing a TagProcessor. For instance, a member of a class or namespace can have its parent scope included in the name by passing include_parent_scopes=True to __init__(). Args: tag: A BeautifulSoup Tag that satisfies match_criterion. Returns: A string that would be appropriate to use as an entry name in a Zeal database. ''' name = tag.findChild('name').contents[0] if self.include_parent_scopes: # Include parent scope in returned name parent_tag = tag.findParent() if parent_tag.get('kind') in ['class', 'struct', 'namespace']: name = parent_tag.findChild('name').contents[0] + '::' + name return name
[ "def", "get_name", "(", "self", ",", "tag", ")", ":", "name", "=", "tag", ".", "findChild", "(", "'name'", ")", ".", "contents", "[", "0", "]", "if", "self", ".", "include_parent_scopes", ":", "# Include parent scope in returned name", "parent_tag", "=", "ta...
Extract and return a representative "name" from a tag. Override as necessary. get_name's output can be controlled through keyword arguments that are provided when initializing a TagProcessor. For instance, a member of a class or namespace can have its parent scope included in the name by passing include_parent_scopes=True to __init__(). Args: tag: A BeautifulSoup Tag that satisfies match_criterion. Returns: A string that would be appropriate to use as an entry name in a Zeal database.
[ "Extract", "and", "return", "a", "representative", "name", "from", "a", "tag", "." ]
8b07a88af6794248f8cfdabb0fda9dd61c777127
https://github.com/vedvyas/doxytag2zealdb/blob/8b07a88af6794248f8cfdabb0fda9dd61c777127/doxytag2zealdb/doxytag.py#L84-L108
train
51,770
vedvyas/doxytag2zealdb
doxytag2zealdb/doxytag.py
TagProcessor.get_filename
def get_filename(self, tag): '''Extract and return a documentation filename from a tag. Override as necessary, though this default implementation probably covers all the cases of interest. Args: tag: A BeautifulSoup Tag that satisfies match_criterion. Returns: A string that would be appropriate to use as the documentation filename for an entry in a Zeal database. ''' if tag.find('filename', recursive=False) is not None: return tag.filename.contents[0] elif tag.find('anchorfile', recursive=False) is not None: return tag.anchorfile.contents[0] + '#' + tag.anchor.contents[0]
python
def get_filename(self, tag): '''Extract and return a documentation filename from a tag. Override as necessary, though this default implementation probably covers all the cases of interest. Args: tag: A BeautifulSoup Tag that satisfies match_criterion. Returns: A string that would be appropriate to use as the documentation filename for an entry in a Zeal database. ''' if tag.find('filename', recursive=False) is not None: return tag.filename.contents[0] elif tag.find('anchorfile', recursive=False) is not None: return tag.anchorfile.contents[0] + '#' + tag.anchor.contents[0]
[ "def", "get_filename", "(", "self", ",", "tag", ")", ":", "if", "tag", ".", "find", "(", "'filename'", ",", "recursive", "=", "False", ")", "is", "not", "None", ":", "return", "tag", ".", "filename", ".", "contents", "[", "0", "]", "elif", "tag", "...
Extract and return a documentation filename from a tag. Override as necessary, though this default implementation probably covers all the cases of interest. Args: tag: A BeautifulSoup Tag that satisfies match_criterion. Returns: A string that would be appropriate to use as the documentation filename for an entry in a Zeal database.
[ "Extract", "and", "return", "a", "documentation", "filename", "from", "a", "tag", "." ]
8b07a88af6794248f8cfdabb0fda9dd61c777127
https://github.com/vedvyas/doxytag2zealdb/blob/8b07a88af6794248f8cfdabb0fda9dd61c777127/doxytag2zealdb/doxytag.py#L124-L140
train
51,771
vedvyas/doxytag2zealdb
doxytag2zealdb/doxytag.py
TagProcessorWithEntryTypeAndFindByNamePlusKind.match_criterion
def match_criterion(self, tag): '''Override. Determine if a tag has the desired name and kind attribute value. Args: tag: A BeautifulSoup Tag. Returns: True if tag has the desired name and kind, otherwise False. ''' return tag.name == self.reference_tag_name and \ tag.attrs.get('kind', '') == self.reference_tag_kind
python
def match_criterion(self, tag): '''Override. Determine if a tag has the desired name and kind attribute value. Args: tag: A BeautifulSoup Tag. Returns: True if tag has the desired name and kind, otherwise False. ''' return tag.name == self.reference_tag_name and \ tag.attrs.get('kind', '') == self.reference_tag_kind
[ "def", "match_criterion", "(", "self", ",", "tag", ")", ":", "return", "tag", ".", "name", "==", "self", ".", "reference_tag_name", "and", "tag", ".", "attrs", ".", "get", "(", "'kind'", ",", "''", ")", "==", "self", ".", "reference_tag_kind" ]
Override. Determine if a tag has the desired name and kind attribute value. Args: tag: A BeautifulSoup Tag. Returns: True if tag has the desired name and kind, otherwise False.
[ "Override", ".", "Determine", "if", "a", "tag", "has", "the", "desired", "name", "and", "kind", "attribute", "value", "." ]
8b07a88af6794248f8cfdabb0fda9dd61c777127
https://github.com/vedvyas/doxytag2zealdb/blob/8b07a88af6794248f8cfdabb0fda9dd61c777127/doxytag2zealdb/doxytag.py#L169-L180
train
51,772
vedvyas/doxytag2zealdb
doxytag2zealdb/doxytag.py
functionTagProcessor.get_name
def get_name(self, tag): '''Override. Extract a representative "name" from a function tag. get_name's output can be controlled through keyword arguments that are provided when initializing a functionTagProcessor. For instance, function arguments and return types can be included by passing include_function_signatures=True to __init__(). Args: tag: A BeautifulSoup Tag for a function. Returns: A string that would be appropriate to use as an entry name for a function in a Zeal database. ''' name = super(functionTagProcessor, self).get_name(tag) if self.include_function_signatures: # Include complete function signature in returned name func_args = tag.findChild('arglist') if func_args and len(func_args.contents): name += func_args.contents[0] ret_type = tag.findChild('type') if ret_type and len(ret_type.contents): name += ' -> ' + ret_type.contents[0] return name
python
def get_name(self, tag): '''Override. Extract a representative "name" from a function tag. get_name's output can be controlled through keyword arguments that are provided when initializing a functionTagProcessor. For instance, function arguments and return types can be included by passing include_function_signatures=True to __init__(). Args: tag: A BeautifulSoup Tag for a function. Returns: A string that would be appropriate to use as an entry name for a function in a Zeal database. ''' name = super(functionTagProcessor, self).get_name(tag) if self.include_function_signatures: # Include complete function signature in returned name func_args = tag.findChild('arglist') if func_args and len(func_args.contents): name += func_args.contents[0] ret_type = tag.findChild('type') if ret_type and len(ret_type.contents): name += ' -> ' + ret_type.contents[0] return name
[ "def", "get_name", "(", "self", ",", "tag", ")", ":", "name", "=", "super", "(", "functionTagProcessor", ",", "self", ")", ".", "get_name", "(", "tag", ")", "if", "self", ".", "include_function_signatures", ":", "# Include complete function signature in returned n...
Override. Extract a representative "name" from a function tag. get_name's output can be controlled through keyword arguments that are provided when initializing a functionTagProcessor. For instance, function arguments and return types can be included by passing include_function_signatures=True to __init__(). Args: tag: A BeautifulSoup Tag for a function. Returns: A string that would be appropriate to use as an entry name for a function in a Zeal database.
[ "Override", ".", "Extract", "a", "representative", "name", "from", "a", "function", "tag", "." ]
8b07a88af6794248f8cfdabb0fda9dd61c777127
https://github.com/vedvyas/doxytag2zealdb/blob/8b07a88af6794248f8cfdabb0fda9dd61c777127/doxytag2zealdb/doxytag.py#L298-L325
train
51,773
brentp/toolshed
toolshed/pool.py
pool
def pool(n=None, dummy=False): """ create a multiprocessing pool that responds to interrupts. """ if dummy: from multiprocessing.dummy import Pool else: from multiprocessing import Pool if n is None: import multiprocessing n = multiprocessing.cpu_count() - 1 return Pool(n)
python
def pool(n=None, dummy=False): """ create a multiprocessing pool that responds to interrupts. """ if dummy: from multiprocessing.dummy import Pool else: from multiprocessing import Pool if n is None: import multiprocessing n = multiprocessing.cpu_count() - 1 return Pool(n)
[ "def", "pool", "(", "n", "=", "None", ",", "dummy", "=", "False", ")", ":", "if", "dummy", ":", "from", "multiprocessing", ".", "dummy", "import", "Pool", "else", ":", "from", "multiprocessing", "import", "Pool", "if", "n", "is", "None", ":", "import",...
create a multiprocessing pool that responds to interrupts.
[ "create", "a", "multiprocessing", "pool", "that", "responds", "to", "interrupts", "." ]
c9529d6872bf28207642896c3b416f68e79b1269
https://github.com/brentp/toolshed/blob/c9529d6872bf28207642896c3b416f68e79b1269/toolshed/pool.py#L70-L83
train
51,774
gwww/elkm1
elkm1_lib/elements.py
Element._call_callbacks
def _call_callbacks(self): """Callbacks when attribute of element changes""" for callback in self._callbacks: callback(self, self._changeset) self._changeset = {}
python
def _call_callbacks(self): """Callbacks when attribute of element changes""" for callback in self._callbacks: callback(self, self._changeset) self._changeset = {}
[ "def", "_call_callbacks", "(", "self", ")", ":", "for", "callback", "in", "self", ".", "_callbacks", ":", "callback", "(", "self", ",", "self", ".", "_changeset", ")", "self", ".", "_changeset", "=", "{", "}" ]
Callbacks when attribute of element changes
[ "Callbacks", "when", "attribute", "of", "element", "changes" ]
078d0de30840c3fab46f1f8534d98df557931e91
https://github.com/gwww/elkm1/blob/078d0de30840c3fab46f1f8534d98df557931e91/elkm1_lib/elements.py#L31-L35
train
51,775
gwww/elkm1
elkm1_lib/elements.py
Element.setattr
def setattr(self, attr, new_value, close_the_changeset=True): """If attribute value has changed then set it and call the callbacks""" existing_value = getattr(self, attr, None) if existing_value != new_value: setattr(self, attr, new_value) self._changeset[attr] = new_value if close_the_changeset and self._changeset: self._call_callbacks()
python
def setattr(self, attr, new_value, close_the_changeset=True): """If attribute value has changed then set it and call the callbacks""" existing_value = getattr(self, attr, None) if existing_value != new_value: setattr(self, attr, new_value) self._changeset[attr] = new_value if close_the_changeset and self._changeset: self._call_callbacks()
[ "def", "setattr", "(", "self", ",", "attr", ",", "new_value", ",", "close_the_changeset", "=", "True", ")", ":", "existing_value", "=", "getattr", "(", "self", ",", "attr", ",", "None", ")", "if", "existing_value", "!=", "new_value", ":", "setattr", "(", ...
If attribute value has changed then set it and call the callbacks
[ "If", "attribute", "value", "has", "changed", "then", "set", "it", "and", "call", "the", "callbacks" ]
078d0de30840c3fab46f1f8534d98df557931e91
https://github.com/gwww/elkm1/blob/078d0de30840c3fab46f1f8534d98df557931e91/elkm1_lib/elements.py#L37-L45
train
51,776
gwww/elkm1
elkm1_lib/elements.py
Element.default_name
def default_name(self, separator='-'): """Return a default name for based on class and index of element""" return self.__class__.__name__ + '{}{:03d}'.format( separator, self._index+1)
python
def default_name(self, separator='-'): """Return a default name for based on class and index of element""" return self.__class__.__name__ + '{}{:03d}'.format( separator, self._index+1)
[ "def", "default_name", "(", "self", ",", "separator", "=", "'-'", ")", ":", "return", "self", ".", "__class__", ".", "__name__", "+", "'{}{:03d}'", ".", "format", "(", "separator", ",", "self", ".", "_index", "+", "1", ")" ]
Return a default name for based on class and index of element
[ "Return", "a", "default", "name", "for", "based", "on", "class", "and", "index", "of", "element" ]
078d0de30840c3fab46f1f8534d98df557931e91
https://github.com/gwww/elkm1/blob/078d0de30840c3fab46f1f8534d98df557931e91/elkm1_lib/elements.py#L47-L50
train
51,777
gwww/elkm1
elkm1_lib/elements.py
Element.as_dict
def as_dict(self): """Package up the public attributes as a dict.""" attrs = vars(self) return {key: attrs[key] for key in attrs if not key.startswith('_')}
python
def as_dict(self): """Package up the public attributes as a dict.""" attrs = vars(self) return {key: attrs[key] for key in attrs if not key.startswith('_')}
[ "def", "as_dict", "(", "self", ")", ":", "attrs", "=", "vars", "(", "self", ")", "return", "{", "key", ":", "attrs", "[", "key", "]", "for", "key", "in", "attrs", "if", "not", "key", ".", "startswith", "(", "'_'", ")", "}" ]
Package up the public attributes as a dict.
[ "Package", "up", "the", "public", "attributes", "as", "a", "dict", "." ]
078d0de30840c3fab46f1f8534d98df557931e91
https://github.com/gwww/elkm1/blob/078d0de30840c3fab46f1f8534d98df557931e91/elkm1_lib/elements.py#L62-L65
train
51,778
gwww/elkm1
elkm1_lib/elements.py
Elements.get_descriptions
def get_descriptions(self, description_type): """ Gets the descriptions for specified type. When complete the callback is called with a list of descriptions """ (desc_type, max_units) = description_type results = [None] * max_units self.elk._descriptions_in_progress[desc_type] = (max_units, results, self._got_desc) self.elk.send(sd_encode(desc_type=desc_type, unit=0))
python
def get_descriptions(self, description_type): """ Gets the descriptions for specified type. When complete the callback is called with a list of descriptions """ (desc_type, max_units) = description_type results = [None] * max_units self.elk._descriptions_in_progress[desc_type] = (max_units, results, self._got_desc) self.elk.send(sd_encode(desc_type=desc_type, unit=0))
[ "def", "get_descriptions", "(", "self", ",", "description_type", ")", ":", "(", "desc_type", ",", "max_units", ")", "=", "description_type", "results", "=", "[", "None", "]", "*", "max_units", "self", ".", "elk", ".", "_descriptions_in_progress", "[", "desc_ty...
Gets the descriptions for specified type. When complete the callback is called with a list of descriptions
[ "Gets", "the", "descriptions", "for", "specified", "type", ".", "When", "complete", "the", "callback", "is", "called", "with", "a", "list", "of", "descriptions" ]
078d0de30840c3fab46f1f8534d98df557931e91
https://github.com/gwww/elkm1/blob/078d0de30840c3fab46f1f8534d98df557931e91/elkm1_lib/elements.py#L90-L100
train
51,779
dahlia/wikidata
wikidata/multilingual.py
normalize_locale_code
def normalize_locale_code(locale: Union[Locale, str]) -> str: """Determine the normalized locale code string. >>> normalize_locale_code('ko-kr') 'ko_KR' >>> normalize_locale_code('zh_TW') 'zh_Hant_TW' >>> normalize_locale_code(Locale.parse('en_US')) 'en_US' """ if not isinstance(locale, Locale): locale = Locale.parse(locale.replace('-', '_')) return str(locale)
python
def normalize_locale_code(locale: Union[Locale, str]) -> str: """Determine the normalized locale code string. >>> normalize_locale_code('ko-kr') 'ko_KR' >>> normalize_locale_code('zh_TW') 'zh_Hant_TW' >>> normalize_locale_code(Locale.parse('en_US')) 'en_US' """ if not isinstance(locale, Locale): locale = Locale.parse(locale.replace('-', '_')) return str(locale)
[ "def", "normalize_locale_code", "(", "locale", ":", "Union", "[", "Locale", ",", "str", "]", ")", "->", "str", ":", "if", "not", "isinstance", "(", "locale", ",", "Locale", ")", ":", "locale", "=", "Locale", ".", "parse", "(", "locale", ".", "replace",...
Determine the normalized locale code string. >>> normalize_locale_code('ko-kr') 'ko_KR' >>> normalize_locale_code('zh_TW') 'zh_Hant_TW' >>> normalize_locale_code(Locale.parse('en_US')) 'en_US'
[ "Determine", "the", "normalized", "locale", "code", "string", "." ]
b07c9f8fffc59b088ec9dd428d0ec4d989c82db4
https://github.com/dahlia/wikidata/blob/b07c9f8fffc59b088ec9dd428d0ec4d989c82db4/wikidata/multilingual.py#L83-L96
train
51,780
dahlia/wikidata
wikidata/cache.py
CachePolicy.set
def set(self, key: CacheKey, value: Optional[CacheValue]) -> None: r"""Create or update a cache. :param key: A key string to create or update. :type key: :const:`CacheKey` :param value: A value to cache. :const:`None` to remove cache. :type value: :class:`~typing.Optional`\ [:const:`CacheValue`] """ raise NotImplementedError( 'Concreate subclasses of {0.__module__}.{0.__qualname__} have to ' 'override .set() method'.format(CachePolicy) )
python
def set(self, key: CacheKey, value: Optional[CacheValue]) -> None: r"""Create or update a cache. :param key: A key string to create or update. :type key: :const:`CacheKey` :param value: A value to cache. :const:`None` to remove cache. :type value: :class:`~typing.Optional`\ [:const:`CacheValue`] """ raise NotImplementedError( 'Concreate subclasses of {0.__module__}.{0.__qualname__} have to ' 'override .set() method'.format(CachePolicy) )
[ "def", "set", "(", "self", ",", "key", ":", "CacheKey", ",", "value", ":", "Optional", "[", "CacheValue", "]", ")", "->", "None", ":", "raise", "NotImplementedError", "(", "'Concreate subclasses of {0.__module__}.{0.__qualname__} have to '", "'override .set() method'", ...
r"""Create or update a cache. :param key: A key string to create or update. :type key: :const:`CacheKey` :param value: A value to cache. :const:`None` to remove cache. :type value: :class:`~typing.Optional`\ [:const:`CacheValue`]
[ "r", "Create", "or", "update", "a", "cache", "." ]
b07c9f8fffc59b088ec9dd428d0ec4d989c82db4
https://github.com/dahlia/wikidata/blob/b07c9f8fffc59b088ec9dd428d0ec4d989c82db4/wikidata/cache.py#L43-L55
train
51,781
dahlia/wikidata
wikidata/entity.py
Entity.getlist
def getlist(self, key: 'Entity') -> Sequence[object]: r"""Return all values associated to the given ``key`` property in sequence. :param key: The property entity. :type key: :class:`Entity` :return: A sequence of all values associated to the given ``key`` property. It can be empty if nothing is associated to the property. :rtype: :class:`~typing.Sequence`\ [:class:`object`] """ if not (isinstance(key, type(self)) and key.type is EntityType.property): return [] claims_map = self.attributes.get('claims') or {} assert isinstance(claims_map, collections.abc.Mapping) claims = claims_map.get(key.id, []) claims.sort(key=lambda claim: claim['rank'], # FIXME reverse=True) logger = logging.getLogger(__name__ + '.Entity.getitem') if logger.isEnabledFor(logging.DEBUG): logger.debug('claim data: %s', __import__('pprint').pformat(claims)) decode = self.client.decode_datavalue return [decode(snak['datatype'], snak['datavalue']) for snak in (claim['mainsnak'] for claim in claims)]
python
def getlist(self, key: 'Entity') -> Sequence[object]: r"""Return all values associated to the given ``key`` property in sequence. :param key: The property entity. :type key: :class:`Entity` :return: A sequence of all values associated to the given ``key`` property. It can be empty if nothing is associated to the property. :rtype: :class:`~typing.Sequence`\ [:class:`object`] """ if not (isinstance(key, type(self)) and key.type is EntityType.property): return [] claims_map = self.attributes.get('claims') or {} assert isinstance(claims_map, collections.abc.Mapping) claims = claims_map.get(key.id, []) claims.sort(key=lambda claim: claim['rank'], # FIXME reverse=True) logger = logging.getLogger(__name__ + '.Entity.getitem') if logger.isEnabledFor(logging.DEBUG): logger.debug('claim data: %s', __import__('pprint').pformat(claims)) decode = self.client.decode_datavalue return [decode(snak['datatype'], snak['datavalue']) for snak in (claim['mainsnak'] for claim in claims)]
[ "def", "getlist", "(", "self", ",", "key", ":", "'Entity'", ")", "->", "Sequence", "[", "object", "]", ":", "if", "not", "(", "isinstance", "(", "key", ",", "type", "(", "self", ")", ")", "and", "key", ".", "type", "is", "EntityType", ".", "propert...
r"""Return all values associated to the given ``key`` property in sequence. :param key: The property entity. :type key: :class:`Entity` :return: A sequence of all values associated to the given ``key`` property. It can be empty if nothing is associated to the property. :rtype: :class:`~typing.Sequence`\ [:class:`object`]
[ "r", "Return", "all", "values", "associated", "to", "the", "given", "key", "property", "in", "sequence", "." ]
b07c9f8fffc59b088ec9dd428d0ec4d989c82db4
https://github.com/dahlia/wikidata/blob/b07c9f8fffc59b088ec9dd428d0ec4d989c82db4/wikidata/entity.py#L165-L191
train
51,782
raddevon/flask-permissions
flask_permissions/models.py
make_user_role_table
def make_user_role_table(table_name='user', id_column_name='id'): """ Create the user-role association table so that it correctly references your own UserMixin subclass. """ return db.Table('fp_user_role', db.Column( 'user_id', db.Integer, db.ForeignKey('{}.{}'.format( table_name, id_column_name))), db.Column( 'role_id', db.Integer, db.ForeignKey('fp_role.id')), extend_existing=True)
python
def make_user_role_table(table_name='user', id_column_name='id'): """ Create the user-role association table so that it correctly references your own UserMixin subclass. """ return db.Table('fp_user_role', db.Column( 'user_id', db.Integer, db.ForeignKey('{}.{}'.format( table_name, id_column_name))), db.Column( 'role_id', db.Integer, db.ForeignKey('fp_role.id')), extend_existing=True)
[ "def", "make_user_role_table", "(", "table_name", "=", "'user'", ",", "id_column_name", "=", "'id'", ")", ":", "return", "db", ".", "Table", "(", "'fp_user_role'", ",", "db", ".", "Column", "(", "'user_id'", ",", "db", ".", "Integer", ",", "db", ".", "Fo...
Create the user-role association table so that it correctly references your own UserMixin subclass.
[ "Create", "the", "user", "-", "role", "association", "table", "so", "that", "it", "correctly", "references", "your", "own", "UserMixin", "subclass", "." ]
a2f64c8e26b6b4807019794a68bad21b12ceeb71
https://github.com/raddevon/flask-permissions/blob/a2f64c8e26b6b4807019794a68bad21b12ceeb71/flask_permissions/models.py#L23-L36
train
51,783
sunlightlabs/django-mediasync
mediasync/views.py
combo_serve
def combo_serve(request, path, client): """ Handles generating a 'combo' file for the given path. This is similar to what happens when we upload to S3. Processors are applied, and we get the value that we would if we were serving from S3. This is a good way to make sure combo files work as intended before rolling out to production. """ joinfile = path sourcefiles = msettings['JOINED'][path] # Generate the combo file as a string. combo_data, dirname = combine_files(joinfile, sourcefiles, client) if path.endswith('.css'): mime_type = 'text/css' elif joinfile.endswith('.js'): mime_type = 'application/javascript' return HttpResponse(combo_data, mimetype=mime_type)
python
def combo_serve(request, path, client): """ Handles generating a 'combo' file for the given path. This is similar to what happens when we upload to S3. Processors are applied, and we get the value that we would if we were serving from S3. This is a good way to make sure combo files work as intended before rolling out to production. """ joinfile = path sourcefiles = msettings['JOINED'][path] # Generate the combo file as a string. combo_data, dirname = combine_files(joinfile, sourcefiles, client) if path.endswith('.css'): mime_type = 'text/css' elif joinfile.endswith('.js'): mime_type = 'application/javascript' return HttpResponse(combo_data, mimetype=mime_type)
[ "def", "combo_serve", "(", "request", ",", "path", ",", "client", ")", ":", "joinfile", "=", "path", "sourcefiles", "=", "msettings", "[", "'JOINED'", "]", "[", "path", "]", "# Generate the combo file as a string.", "combo_data", ",", "dirname", "=", "combine_fi...
Handles generating a 'combo' file for the given path. This is similar to what happens when we upload to S3. Processors are applied, and we get the value that we would if we were serving from S3. This is a good way to make sure combo files work as intended before rolling out to production.
[ "Handles", "generating", "a", "combo", "file", "for", "the", "given", "path", ".", "This", "is", "similar", "to", "what", "happens", "when", "we", "upload", "to", "S3", ".", "Processors", "are", "applied", "and", "we", "get", "the", "value", "that", "we"...
aa8ce4cfff757bbdb488463c64c0863cca6a1932
https://github.com/sunlightlabs/django-mediasync/blob/aa8ce4cfff757bbdb488463c64c0863cca6a1932/mediasync/views.py#L14-L32
train
51,784
sunlightlabs/django-mediasync
mediasync/views.py
static_serve
def static_serve(request, path, client): """ Given a request for a media asset, this view does the necessary wrangling to get the correct thing delivered to the user. This can also emulate the combo behavior seen when SERVE_REMOTE == False and EMULATE_COMBO == True. """ if msettings['SERVE_REMOTE']: # We're serving from S3, redirect there. url = client.remote_media_url().strip('/') + '/%(path)s' return redirect(url, permanent=True) if not msettings['SERVE_REMOTE'] and msettings['EMULATE_COMBO']: # Combo emulation is on and we're serving media locally. Try to see if # the given path matches a combo file defined in the JOINED dict in # the MEDIASYNC settings dict. combo_match = _find_combo_match(path) if combo_match: # We found a combo file match. Combine it and serve the result. return combo_serve(request, combo_match, client) # No combo file, but we're serving locally. Use the standard (inefficient) # Django static serve view. resp = serve(request, path, document_root=client.media_root, show_indexes=True) try: resp.content = client.process(resp.content, resp['Content-Type'], path) except KeyError: # HTTPNotModifiedResponse lacks the "Content-Type" key. pass return resp
python
def static_serve(request, path, client): """ Given a request for a media asset, this view does the necessary wrangling to get the correct thing delivered to the user. This can also emulate the combo behavior seen when SERVE_REMOTE == False and EMULATE_COMBO == True. """ if msettings['SERVE_REMOTE']: # We're serving from S3, redirect there. url = client.remote_media_url().strip('/') + '/%(path)s' return redirect(url, permanent=True) if not msettings['SERVE_REMOTE'] and msettings['EMULATE_COMBO']: # Combo emulation is on and we're serving media locally. Try to see if # the given path matches a combo file defined in the JOINED dict in # the MEDIASYNC settings dict. combo_match = _find_combo_match(path) if combo_match: # We found a combo file match. Combine it and serve the result. return combo_serve(request, combo_match, client) # No combo file, but we're serving locally. Use the standard (inefficient) # Django static serve view. resp = serve(request, path, document_root=client.media_root, show_indexes=True) try: resp.content = client.process(resp.content, resp['Content-Type'], path) except KeyError: # HTTPNotModifiedResponse lacks the "Content-Type" key. pass return resp
[ "def", "static_serve", "(", "request", ",", "path", ",", "client", ")", ":", "if", "msettings", "[", "'SERVE_REMOTE'", "]", ":", "# We're serving from S3, redirect there.", "url", "=", "client", ".", "remote_media_url", "(", ")", ".", "strip", "(", "'/'", ")",...
Given a request for a media asset, this view does the necessary wrangling to get the correct thing delivered to the user. This can also emulate the combo behavior seen when SERVE_REMOTE == False and EMULATE_COMBO == True.
[ "Given", "a", "request", "for", "a", "media", "asset", "this", "view", "does", "the", "necessary", "wrangling", "to", "get", "the", "correct", "thing", "delivered", "to", "the", "user", ".", "This", "can", "also", "emulate", "the", "combo", "behavior", "se...
aa8ce4cfff757bbdb488463c64c0863cca6a1932
https://github.com/sunlightlabs/django-mediasync/blob/aa8ce4cfff757bbdb488463c64c0863cca6a1932/mediasync/views.py#L86-L116
train
51,785
sprockets/sprockets.http
sprockets/http/runner.py
Runner.start_server
def start_server(self, port_number, number_of_procs=0): """ Create a HTTP server and start it. :param int port_number: the port number to bind the server to :param int number_of_procs: number of processes to pass to Tornado's ``httpserver.HTTPServer.start``. If the application's ``debug`` setting is ``True``, then we are going to run in a single-process mode; otherwise, we'll let tornado decide how many sub-processes to spawn. The following additional configuration parameters can be set on the ``httpserver.HTTPServer`` instance by setting them in the application settings: ``xheaders``, ``max_body_size``, ``max_buffer_size``. """ signal.signal(signal.SIGTERM, self._on_signal) signal.signal(signal.SIGINT, self._on_signal) xheaders = self.application.settings.get('xheaders', False) max_body_size = self.application.settings.get('max_body_size', None) max_buffer_size = self.application.settings.get('max_buffer_size', None) self.server = httpserver.HTTPServer( self.application.tornado_application, xheaders=xheaders, max_body_size=max_body_size, max_buffer_size=max_buffer_size) if self.application.settings.get('debug', False): self.logger.info('starting 1 process on port %d', port_number) self.server.listen(port_number) else: self.logger.info('starting processes on port %d', port_number) self.server.bind(port_number, reuse_port=True) self.server.start(number_of_procs)
python
def start_server(self, port_number, number_of_procs=0): """ Create a HTTP server and start it. :param int port_number: the port number to bind the server to :param int number_of_procs: number of processes to pass to Tornado's ``httpserver.HTTPServer.start``. If the application's ``debug`` setting is ``True``, then we are going to run in a single-process mode; otherwise, we'll let tornado decide how many sub-processes to spawn. The following additional configuration parameters can be set on the ``httpserver.HTTPServer`` instance by setting them in the application settings: ``xheaders``, ``max_body_size``, ``max_buffer_size``. """ signal.signal(signal.SIGTERM, self._on_signal) signal.signal(signal.SIGINT, self._on_signal) xheaders = self.application.settings.get('xheaders', False) max_body_size = self.application.settings.get('max_body_size', None) max_buffer_size = self.application.settings.get('max_buffer_size', None) self.server = httpserver.HTTPServer( self.application.tornado_application, xheaders=xheaders, max_body_size=max_body_size, max_buffer_size=max_buffer_size) if self.application.settings.get('debug', False): self.logger.info('starting 1 process on port %d', port_number) self.server.listen(port_number) else: self.logger.info('starting processes on port %d', port_number) self.server.bind(port_number, reuse_port=True) self.server.start(number_of_procs)
[ "def", "start_server", "(", "self", ",", "port_number", ",", "number_of_procs", "=", "0", ")", ":", "signal", ".", "signal", "(", "signal", ".", "SIGTERM", ",", "self", ".", "_on_signal", ")", "signal", ".", "signal", "(", "signal", ".", "SIGINT", ",", ...
Create a HTTP server and start it. :param int port_number: the port number to bind the server to :param int number_of_procs: number of processes to pass to Tornado's ``httpserver.HTTPServer.start``. If the application's ``debug`` setting is ``True``, then we are going to run in a single-process mode; otherwise, we'll let tornado decide how many sub-processes to spawn. The following additional configuration parameters can be set on the ``httpserver.HTTPServer`` instance by setting them in the application settings: ``xheaders``, ``max_body_size``, ``max_buffer_size``.
[ "Create", "a", "HTTP", "server", "and", "start", "it", "." ]
8baa4cdc1fa35a162ee226fd6cc4170a0ca0ecd3
https://github.com/sprockets/sprockets.http/blob/8baa4cdc1fa35a162ee226fd6cc4170a0ca0ecd3/sprockets/http/runner.py#L59-L94
train
51,786
sprockets/sprockets.http
sprockets/http/runner.py
Runner.run
def run(self, port_number, number_of_procs=0): """ Create the server and run the IOLoop. :param int port_number: the port number to bind the server to :param int number_of_procs: number of processes to pass to Tornado's ``httpserver.HTTPServer.start``. If the application's ``debug`` setting is ``True``, then we are going to run in a single-process mode; otherwise, we'll let tornado decide how many sub-processes based on the value of the ``number_of_procs`` argument. In any case, the application's *before_run* callbacks are invoked. If a callback raises an exception, then the application is terminated by calling :func:`sys.exit`. If any ``on_start`` callbacks are registered, they will be added to the Tornado IOLoop for execution after the IOLoop is started. The following additional configuration parameters can be set on the ``httpserver.HTTPServer`` instance by setting them in the application settings: ``xheaders``, ``max_body_size``, ``max_buffer_size``. """ self.start_server(port_number, number_of_procs) iol = ioloop.IOLoop.instance() try: self.application.start(iol) except Exception: self.logger.exception('application terminated during start, ' 'exiting') sys.exit(70) iol.start()
python
def run(self, port_number, number_of_procs=0): """ Create the server and run the IOLoop. :param int port_number: the port number to bind the server to :param int number_of_procs: number of processes to pass to Tornado's ``httpserver.HTTPServer.start``. If the application's ``debug`` setting is ``True``, then we are going to run in a single-process mode; otherwise, we'll let tornado decide how many sub-processes based on the value of the ``number_of_procs`` argument. In any case, the application's *before_run* callbacks are invoked. If a callback raises an exception, then the application is terminated by calling :func:`sys.exit`. If any ``on_start`` callbacks are registered, they will be added to the Tornado IOLoop for execution after the IOLoop is started. The following additional configuration parameters can be set on the ``httpserver.HTTPServer`` instance by setting them in the application settings: ``xheaders``, ``max_body_size``, ``max_buffer_size``. """ self.start_server(port_number, number_of_procs) iol = ioloop.IOLoop.instance() try: self.application.start(iol) except Exception: self.logger.exception('application terminated during start, ' 'exiting') sys.exit(70) iol.start()
[ "def", "run", "(", "self", ",", "port_number", ",", "number_of_procs", "=", "0", ")", ":", "self", ".", "start_server", "(", "port_number", ",", "number_of_procs", ")", "iol", "=", "ioloop", ".", "IOLoop", ".", "instance", "(", ")", "try", ":", "self", ...
Create the server and run the IOLoop. :param int port_number: the port number to bind the server to :param int number_of_procs: number of processes to pass to Tornado's ``httpserver.HTTPServer.start``. If the application's ``debug`` setting is ``True``, then we are going to run in a single-process mode; otherwise, we'll let tornado decide how many sub-processes based on the value of the ``number_of_procs`` argument. In any case, the application's *before_run* callbacks are invoked. If a callback raises an exception, then the application is terminated by calling :func:`sys.exit`. If any ``on_start`` callbacks are registered, they will be added to the Tornado IOLoop for execution after the IOLoop is started. The following additional configuration parameters can be set on the ``httpserver.HTTPServer`` instance by setting them in the application settings: ``xheaders``, ``max_body_size``, ``max_buffer_size``.
[ "Create", "the", "server", "and", "run", "the", "IOLoop", "." ]
8baa4cdc1fa35a162ee226fd6cc4170a0ca0ecd3
https://github.com/sprockets/sprockets.http/blob/8baa4cdc1fa35a162ee226fd6cc4170a0ca0ecd3/sprockets/http/runner.py#L100-L133
train
51,787
confirm/ansibleci
ansibleci/config.py
Config.add_module
def add_module(self, module): ''' Adds configuration parameters from a Python module. ''' for key, value in module.__dict__.iteritems(): if key[0:2] != '__': self.__setattr__(attr=key, value=value)
python
def add_module(self, module): ''' Adds configuration parameters from a Python module. ''' for key, value in module.__dict__.iteritems(): if key[0:2] != '__': self.__setattr__(attr=key, value=value)
[ "def", "add_module", "(", "self", ",", "module", ")", ":", "for", "key", ",", "value", "in", "module", ".", "__dict__", ".", "iteritems", "(", ")", ":", "if", "key", "[", "0", ":", "2", "]", "!=", "'__'", ":", "self", ".", "__setattr__", "(", "at...
Adds configuration parameters from a Python module.
[ "Adds", "configuration", "parameters", "from", "a", "Python", "module", "." ]
6a53ae8c4a4653624977e146092422857f661b8f
https://github.com/confirm/ansibleci/blob/6a53ae8c4a4653624977e146092422857f661b8f/ansibleci/config.py#L61-L67
train
51,788
matllubos/django-is-core
is_core/generic_views/__init__.py
PermissionsViewMixin._check_permission
def _check_permission(self, name, obj=None): """ If customer is not authorized he should not get information that object is exists. Therefore 403 is returned if object was not found or is redirected to the login page. If custmer is authorized and object was not found is returned 404. If object was found and user is not authorized is returned 403 or redirect to login page. If object was found and user is authorized is returned 403 or 200 according of result of _has_permission method. """ def redirect_or_exception(ex): if not self.request.user or not self.request.user.is_authenticated: if self.auto_login_redirect: redirect_to_login(self.request.get_full_path()) else: raise HTTPUnauthorizedResponseException else: raise ex try: if not self._has_permission(name, obj): redirect_or_exception(HTTPForbiddenResponseException) except Http404 as ex: redirect_or_exception(ex)
python
def _check_permission(self, name, obj=None): """ If customer is not authorized he should not get information that object is exists. Therefore 403 is returned if object was not found or is redirected to the login page. If custmer is authorized and object was not found is returned 404. If object was found and user is not authorized is returned 403 or redirect to login page. If object was found and user is authorized is returned 403 or 200 according of result of _has_permission method. """ def redirect_or_exception(ex): if not self.request.user or not self.request.user.is_authenticated: if self.auto_login_redirect: redirect_to_login(self.request.get_full_path()) else: raise HTTPUnauthorizedResponseException else: raise ex try: if not self._has_permission(name, obj): redirect_or_exception(HTTPForbiddenResponseException) except Http404 as ex: redirect_or_exception(ex)
[ "def", "_check_permission", "(", "self", ",", "name", ",", "obj", "=", "None", ")", ":", "def", "redirect_or_exception", "(", "ex", ")", ":", "if", "not", "self", ".", "request", ".", "user", "or", "not", "self", ".", "request", ".", "user", ".", "is...
If customer is not authorized he should not get information that object is exists. Therefore 403 is returned if object was not found or is redirected to the login page. If custmer is authorized and object was not found is returned 404. If object was found and user is not authorized is returned 403 or redirect to login page. If object was found and user is authorized is returned 403 or 200 according of result of _has_permission method.
[ "If", "customer", "is", "not", "authorized", "he", "should", "not", "get", "information", "that", "object", "is", "exists", ".", "Therefore", "403", "is", "returned", "if", "object", "was", "not", "found", "or", "is", "redirected", "to", "the", "login", "p...
3f87ec56a814738683c732dce5f07e0328c2300d
https://github.com/matllubos/django-is-core/blob/3f87ec56a814738683c732dce5f07e0328c2300d/is_core/generic_views/__init__.py#L67-L88
train
51,789
xapple/plumbing
plumbing/graphs.py
Graph.plot_and_save
def plot_and_save(self, **kwargs): """Used when the plot method defined does not create a figure nor calls save_plot Then the plot method has to use self.fig""" self.fig = pyplot.figure() self.plot() self.axes = pyplot.gca() self.save_plot(self.fig, self.axes, **kwargs) pyplot.close(self.fig)
python
def plot_and_save(self, **kwargs): """Used when the plot method defined does not create a figure nor calls save_plot Then the plot method has to use self.fig""" self.fig = pyplot.figure() self.plot() self.axes = pyplot.gca() self.save_plot(self.fig, self.axes, **kwargs) pyplot.close(self.fig)
[ "def", "plot_and_save", "(", "self", ",", "*", "*", "kwargs", ")", ":", "self", ".", "fig", "=", "pyplot", ".", "figure", "(", ")", "self", ".", "plot", "(", ")", "self", ".", "axes", "=", "pyplot", ".", "gca", "(", ")", "self", ".", "save_plot",...
Used when the plot method defined does not create a figure nor calls save_plot Then the plot method has to use self.fig
[ "Used", "when", "the", "plot", "method", "defined", "does", "not", "create", "a", "figure", "nor", "calls", "save_plot", "Then", "the", "plot", "method", "has", "to", "use", "self", ".", "fig" ]
4a7706c7722f5996d0ca366f191aff9ac145880a
https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/graphs.py#L162-L169
train
51,790
xapple/plumbing
plumbing/graphs.py
Graph.plot
def plot(self, bins=250, **kwargs): """An example plot function. You have to subclass this method.""" # Data # counts = [sum(map(len, b.contigs)) for b in self.parent.bins] # Linear bins in logarithmic space # if 'log' in kwargs.get('x_scale', ''): start, stop = numpy.log10(1), numpy.log10(max(counts)) bins = list(numpy.logspace(start=start, stop=stop, num=bins)) bins.insert(0, 0) # Plot # fig = pyplot.figure() pyplot.hist(counts, bins=bins, color='gray') axes = pyplot.gca() # Information # title = 'Distribution of the total nucleotide count in the bins' axes.set_title(title) axes.set_xlabel('Number of nucleotides in a bin') axes.set_ylabel('Number of bins with that many nucleotides in them') # Save it # self.save_plot(fig, axes, **kwargs) pyplot.close(fig) # For convenience # return self
python
def plot(self, bins=250, **kwargs): """An example plot function. You have to subclass this method.""" # Data # counts = [sum(map(len, b.contigs)) for b in self.parent.bins] # Linear bins in logarithmic space # if 'log' in kwargs.get('x_scale', ''): start, stop = numpy.log10(1), numpy.log10(max(counts)) bins = list(numpy.logspace(start=start, stop=stop, num=bins)) bins.insert(0, 0) # Plot # fig = pyplot.figure() pyplot.hist(counts, bins=bins, color='gray') axes = pyplot.gca() # Information # title = 'Distribution of the total nucleotide count in the bins' axes.set_title(title) axes.set_xlabel('Number of nucleotides in a bin') axes.set_ylabel('Number of bins with that many nucleotides in them') # Save it # self.save_plot(fig, axes, **kwargs) pyplot.close(fig) # For convenience # return self
[ "def", "plot", "(", "self", ",", "bins", "=", "250", ",", "*", "*", "kwargs", ")", ":", "# Data #", "counts", "=", "[", "sum", "(", "map", "(", "len", ",", "b", ".", "contigs", ")", ")", "for", "b", "in", "self", ".", "parent", ".", "bins", "...
An example plot function. You have to subclass this method.
[ "An", "example", "plot", "function", ".", "You", "have", "to", "subclass", "this", "method", "." ]
4a7706c7722f5996d0ca366f191aff9ac145880a
https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/graphs.py#L171-L193
train
51,791
xapple/plumbing
plumbing/slurm/__init__.py
count_processors
def count_processors(): """How many cores does the current computer have ?""" if 'SLURM_NTASKS' in os.environ: return int(os.environ['SLURM_NTASKS']) elif 'SLURM_JOB_CPUS_PER_NODE' in os.environ: text = os.environ['SLURM_JOB_CPUS_PER_NODE'] if is_integer(text): return int(text) else: n, N = re.findall("([1-9]+)\(x([1-9]+)\)", text)[0] return int(n) * int(N) else: return multiprocessing.cpu_count()
python
def count_processors(): """How many cores does the current computer have ?""" if 'SLURM_NTASKS' in os.environ: return int(os.environ['SLURM_NTASKS']) elif 'SLURM_JOB_CPUS_PER_NODE' in os.environ: text = os.environ['SLURM_JOB_CPUS_PER_NODE'] if is_integer(text): return int(text) else: n, N = re.findall("([1-9]+)\(x([1-9]+)\)", text)[0] return int(n) * int(N) else: return multiprocessing.cpu_count()
[ "def", "count_processors", "(", ")", ":", "if", "'SLURM_NTASKS'", "in", "os", ".", "environ", ":", "return", "int", "(", "os", ".", "environ", "[", "'SLURM_NTASKS'", "]", ")", "elif", "'SLURM_JOB_CPUS_PER_NODE'", "in", "os", ".", "environ", ":", "text", "=...
How many cores does the current computer have ?
[ "How", "many", "cores", "does", "the", "current", "computer", "have", "?" ]
4a7706c7722f5996d0ca366f191aff9ac145880a
https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/slurm/__init__.py#L10-L19
train
51,792
xapple/plumbing
plumbing/slurm/__init__.py
guess_server_name
def guess_server_name(): """We often use the same servers, which one are we running on now ?""" if os.environ.get('CSCSERVICE') == 'sisu': return "sisu" elif os.environ.get('SLURM_JOB_PARTITION') == 'halvan': return "halvan" elif os.environ.get('SNIC_RESOURCE') == 'milou': return "milou" elif os.environ.get('LAPTOP') == 'macbook_air': return "macbook_air" else: return "unknown"
python
def guess_server_name(): """We often use the same servers, which one are we running on now ?""" if os.environ.get('CSCSERVICE') == 'sisu': return "sisu" elif os.environ.get('SLURM_JOB_PARTITION') == 'halvan': return "halvan" elif os.environ.get('SNIC_RESOURCE') == 'milou': return "milou" elif os.environ.get('LAPTOP') == 'macbook_air': return "macbook_air" else: return "unknown"
[ "def", "guess_server_name", "(", ")", ":", "if", "os", ".", "environ", ".", "get", "(", "'CSCSERVICE'", ")", "==", "'sisu'", ":", "return", "\"sisu\"", "elif", "os", ".", "environ", ".", "get", "(", "'SLURM_JOB_PARTITION'", ")", "==", "'halvan'", ":", "r...
We often use the same servers, which one are we running on now ?
[ "We", "often", "use", "the", "same", "servers", "which", "one", "are", "we", "running", "on", "now", "?" ]
4a7706c7722f5996d0ca366f191aff9ac145880a
https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/slurm/__init__.py#L22-L28
train
51,793
epandurski/flask_signalbus
flask_signalbus/atomic.py
_ModelUtilitiesMixin.get_instance
def get_instance(cls, instance_or_pk): """Return a model instance in ``db.session``. :param instance_or_pk: An instance of this model class, or a primary key. A composite primary key can be passed as a tuple. Example:: @db.atomic def increase_account_balance(account, amount): # Here `Account` is a subclass of `db.Model`. account = Account.get_instance(account) account.balance += amount # Now `increase_account_balance` can be # called with an account instance: increase_account_balance(my_account, 100.00) # or with an account primary key (1234): increase_account_balance(1234, 100.00) """ if isinstance(instance_or_pk, cls): if instance_or_pk in cls._flask_signalbus_sa.session: return instance_or_pk instance_or_pk = inspect(cls).primary_key_from_instance(instance_or_pk) return cls.query.get(instance_or_pk)
python
def get_instance(cls, instance_or_pk): """Return a model instance in ``db.session``. :param instance_or_pk: An instance of this model class, or a primary key. A composite primary key can be passed as a tuple. Example:: @db.atomic def increase_account_balance(account, amount): # Here `Account` is a subclass of `db.Model`. account = Account.get_instance(account) account.balance += amount # Now `increase_account_balance` can be # called with an account instance: increase_account_balance(my_account, 100.00) # or with an account primary key (1234): increase_account_balance(1234, 100.00) """ if isinstance(instance_or_pk, cls): if instance_or_pk in cls._flask_signalbus_sa.session: return instance_or_pk instance_or_pk = inspect(cls).primary_key_from_instance(instance_or_pk) return cls.query.get(instance_or_pk)
[ "def", "get_instance", "(", "cls", ",", "instance_or_pk", ")", ":", "if", "isinstance", "(", "instance_or_pk", ",", "cls", ")", ":", "if", "instance_or_pk", "in", "cls", ".", "_flask_signalbus_sa", ".", "session", ":", "return", "instance_or_pk", "instance_or_pk...
Return a model instance in ``db.session``. :param instance_or_pk: An instance of this model class, or a primary key. A composite primary key can be passed as a tuple. Example:: @db.atomic def increase_account_balance(account, amount): # Here `Account` is a subclass of `db.Model`. account = Account.get_instance(account) account.balance += amount # Now `increase_account_balance` can be # called with an account instance: increase_account_balance(my_account, 100.00) # or with an account primary key (1234): increase_account_balance(1234, 100.00)
[ "Return", "a", "model", "instance", "in", "db", ".", "session", "." ]
253800118443821a40404f04416422b076d62b6e
https://github.com/epandurski/flask_signalbus/blob/253800118443821a40404f04416422b076d62b6e/flask_signalbus/atomic.py#L21-L49
train
51,794
epandurski/flask_signalbus
flask_signalbus/atomic.py
_ModelUtilitiesMixin.lock_instance
def lock_instance(cls, instance_or_pk, read=False): """Return a locked model instance in ``db.session``. :param instance_or_pk: An instance of this model class, or a primary key. A composite primary key can be passed as a tuple. :param read: If `True`, a reading lock is obtained instead of a writing lock. """ mapper = inspect(cls) pk_attrs = [mapper.get_property_by_column(c).class_attribute for c in mapper.primary_key] pk_values = cls.get_pk_values(instance_or_pk) clause = and_(*[attr == value for attr, value in zip(pk_attrs, pk_values)]) return cls.query.filter(clause).with_for_update(read=read).one_or_none()
python
def lock_instance(cls, instance_or_pk, read=False): """Return a locked model instance in ``db.session``. :param instance_or_pk: An instance of this model class, or a primary key. A composite primary key can be passed as a tuple. :param read: If `True`, a reading lock is obtained instead of a writing lock. """ mapper = inspect(cls) pk_attrs = [mapper.get_property_by_column(c).class_attribute for c in mapper.primary_key] pk_values = cls.get_pk_values(instance_or_pk) clause = and_(*[attr == value for attr, value in zip(pk_attrs, pk_values)]) return cls.query.filter(clause).with_for_update(read=read).one_or_none()
[ "def", "lock_instance", "(", "cls", ",", "instance_or_pk", ",", "read", "=", "False", ")", ":", "mapper", "=", "inspect", "(", "cls", ")", "pk_attrs", "=", "[", "mapper", ".", "get_property_by_column", "(", "c", ")", ".", "class_attribute", "for", "c", "...
Return a locked model instance in ``db.session``. :param instance_or_pk: An instance of this model class, or a primary key. A composite primary key can be passed as a tuple. :param read: If `True`, a reading lock is obtained instead of a writing lock.
[ "Return", "a", "locked", "model", "instance", "in", "db", ".", "session", "." ]
253800118443821a40404f04416422b076d62b6e
https://github.com/epandurski/flask_signalbus/blob/253800118443821a40404f04416422b076d62b6e/flask_signalbus/atomic.py#L52-L68
train
51,795
epandurski/flask_signalbus
flask_signalbus/atomic.py
_ModelUtilitiesMixin.get_pk_values
def get_pk_values(cls, instance_or_pk): """Return a primary key as a tuple. :param instance_or_pk: An instance of this model class, or a primary key. A composite primary key can be passed as a tuple. """ if isinstance(instance_or_pk, cls): cls._flask_signalbus_sa.session.flush() instance_or_pk = inspect(cls).primary_key_from_instance(instance_or_pk) return instance_or_pk if isinstance(instance_or_pk, tuple) else (instance_or_pk,)
python
def get_pk_values(cls, instance_or_pk): """Return a primary key as a tuple. :param instance_or_pk: An instance of this model class, or a primary key. A composite primary key can be passed as a tuple. """ if isinstance(instance_or_pk, cls): cls._flask_signalbus_sa.session.flush() instance_or_pk = inspect(cls).primary_key_from_instance(instance_or_pk) return instance_or_pk if isinstance(instance_or_pk, tuple) else (instance_or_pk,)
[ "def", "get_pk_values", "(", "cls", ",", "instance_or_pk", ")", ":", "if", "isinstance", "(", "instance_or_pk", ",", "cls", ")", ":", "cls", ".", "_flask_signalbus_sa", ".", "session", ".", "flush", "(", ")", "instance_or_pk", "=", "inspect", "(", "cls", "...
Return a primary key as a tuple. :param instance_or_pk: An instance of this model class, or a primary key. A composite primary key can be passed as a tuple.
[ "Return", "a", "primary", "key", "as", "a", "tuple", "." ]
253800118443821a40404f04416422b076d62b6e
https://github.com/epandurski/flask_signalbus/blob/253800118443821a40404f04416422b076d62b6e/flask_signalbus/atomic.py#L71-L83
train
51,796
epandurski/flask_signalbus
flask_signalbus/atomic.py
AtomicProceduresMixin.atomic
def atomic(self, func): """A decorator that wraps a function in an atomic block. Example:: db = CustomSQLAlchemy() @db.atomic def f(): write_to_db('a message') return 'OK' assert f() == 'OK' This code defines the function ``f``, which is wrapped in an atomic block. Wrapping a function in an atomic block gives several guarantees: 1. The database transaction will be automatically committed if the function returns normally, and automatically rolled back if the function raises unhandled exception. 2. When the transaction is committed, all objects in ``db.session`` will be expunged. This means that no lazy loading will be performed on them. 3. If a transaction serialization error occurs during the execution of the function, the function will be re-executed. (It might be re-executed several times.) Atomic blocks can be nested, but in this case the outermost block takes full control of transaction's life-cycle, and inner blocks do nothing. """ @wraps(func) def wrapper(*args, **kwargs): session = self.session session_info = session.info if session_info.get(_ATOMIC_FLAG_SESSION_INFO_KEY): return func(*args, **kwargs) f = retry_on_deadlock(session)(func) session_info[_ATOMIC_FLAG_SESSION_INFO_KEY] = True try: result = f(*args, **kwargs) session.flush() session.expunge_all() session.commit() return result except Exception: session.rollback() raise finally: session_info[_ATOMIC_FLAG_SESSION_INFO_KEY] = False return wrapper
python
def atomic(self, func): """A decorator that wraps a function in an atomic block. Example:: db = CustomSQLAlchemy() @db.atomic def f(): write_to_db('a message') return 'OK' assert f() == 'OK' This code defines the function ``f``, which is wrapped in an atomic block. Wrapping a function in an atomic block gives several guarantees: 1. The database transaction will be automatically committed if the function returns normally, and automatically rolled back if the function raises unhandled exception. 2. When the transaction is committed, all objects in ``db.session`` will be expunged. This means that no lazy loading will be performed on them. 3. If a transaction serialization error occurs during the execution of the function, the function will be re-executed. (It might be re-executed several times.) Atomic blocks can be nested, but in this case the outermost block takes full control of transaction's life-cycle, and inner blocks do nothing. """ @wraps(func) def wrapper(*args, **kwargs): session = self.session session_info = session.info if session_info.get(_ATOMIC_FLAG_SESSION_INFO_KEY): return func(*args, **kwargs) f = retry_on_deadlock(session)(func) session_info[_ATOMIC_FLAG_SESSION_INFO_KEY] = True try: result = f(*args, **kwargs) session.flush() session.expunge_all() session.commit() return result except Exception: session.rollback() raise finally: session_info[_ATOMIC_FLAG_SESSION_INFO_KEY] = False return wrapper
[ "def", "atomic", "(", "self", ",", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "session", "=", "self", ".", "session", "session_info", "=", "session", ".", "info", "if", ...
A decorator that wraps a function in an atomic block. Example:: db = CustomSQLAlchemy() @db.atomic def f(): write_to_db('a message') return 'OK' assert f() == 'OK' This code defines the function ``f``, which is wrapped in an atomic block. Wrapping a function in an atomic block gives several guarantees: 1. The database transaction will be automatically committed if the function returns normally, and automatically rolled back if the function raises unhandled exception. 2. When the transaction is committed, all objects in ``db.session`` will be expunged. This means that no lazy loading will be performed on them. 3. If a transaction serialization error occurs during the execution of the function, the function will be re-executed. (It might be re-executed several times.) Atomic blocks can be nested, but in this case the outermost block takes full control of transaction's life-cycle, and inner blocks do nothing.
[ "A", "decorator", "that", "wraps", "a", "function", "in", "an", "atomic", "block", "." ]
253800118443821a40404f04416422b076d62b6e
https://github.com/epandurski/flask_signalbus/blob/253800118443821a40404f04416422b076d62b6e/flask_signalbus/atomic.py#L129-L185
train
51,797
intelligenia/modeltranslation
modeltranslation/translation.py
_save_translations
def _save_translations(sender, instance, *args, **kwargs): """ This signal saves model translations. """ # If we are in a site with one language there is no need of saving translations if site_is_monolingual(): return False cls = sender # If its class has no "translatable_fields" then there are no translations if not hasattr(cls._meta, "translatable_fields"): return False # For each translatable field, get its value, computes its md5 and for each language creates its # empty translation. for field in cls._meta.translatable_fields: value = getattr(instance,field) if not value is None: md5_value = checksum(value) setattr( instance, u"md5"+field, md5_value ) for lang in settings.LANGUAGES: lang = lang[0] # print "({0}!={1}) = {2}".format(lang, settings.LANGUAGE_CODE,lang!=settings.LANGUAGE_CODE) if lang != settings.LANGUAGE_CODE: context = u"Updating from object" if hasattr(instance, "trans_context"): context = getattr(instance, "trans_context") trans = FieldTranslation.update(instance, field, lang, context)
python
def _save_translations(sender, instance, *args, **kwargs): """ This signal saves model translations. """ # If we are in a site with one language there is no need of saving translations if site_is_monolingual(): return False cls = sender # If its class has no "translatable_fields" then there are no translations if not hasattr(cls._meta, "translatable_fields"): return False # For each translatable field, get its value, computes its md5 and for each language creates its # empty translation. for field in cls._meta.translatable_fields: value = getattr(instance,field) if not value is None: md5_value = checksum(value) setattr( instance, u"md5"+field, md5_value ) for lang in settings.LANGUAGES: lang = lang[0] # print "({0}!={1}) = {2}".format(lang, settings.LANGUAGE_CODE,lang!=settings.LANGUAGE_CODE) if lang != settings.LANGUAGE_CODE: context = u"Updating from object" if hasattr(instance, "trans_context"): context = getattr(instance, "trans_context") trans = FieldTranslation.update(instance, field, lang, context)
[ "def", "_save_translations", "(", "sender", ",", "instance", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# If we are in a site with one language there is no need of saving translations", "if", "site_is_monolingual", "(", ")", ":", "return", "False", "cls", "...
This signal saves model translations.
[ "This", "signal", "saves", "model", "translations", "." ]
64d6adeb537747321d5020efedf5d7e0d135862d
https://github.com/intelligenia/modeltranslation/blob/64d6adeb537747321d5020efedf5d7e0d135862d/modeltranslation/translation.py#L53-L82
train
51,798
intelligenia/modeltranslation
modeltranslation/translation.py
_get_fieldtranslations
def _get_fieldtranslations(instance, field=None, lang=None): """ Get all the translations for this object. """ # Basic filtering: filter translations by module, model an object_id _filter = {"module": instance.__module__, "model": instance.__class__.__name__, "object_id": instance.id} if lang: _filter["lang"] = lang # If we specify a field we get ONE translation (this field translation) if field: _filter["field"] = field try: return FieldTranslation.objects.get(**_filter) except FieldTranslation.DoesNotExist: return False # Otherwise, we get all translations return FieldTranslation.objects.filter(**_filter)
python
def _get_fieldtranslations(instance, field=None, lang=None): """ Get all the translations for this object. """ # Basic filtering: filter translations by module, model an object_id _filter = {"module": instance.__module__, "model": instance.__class__.__name__, "object_id": instance.id} if lang: _filter["lang"] = lang # If we specify a field we get ONE translation (this field translation) if field: _filter["field"] = field try: return FieldTranslation.objects.get(**_filter) except FieldTranslation.DoesNotExist: return False # Otherwise, we get all translations return FieldTranslation.objects.filter(**_filter)
[ "def", "_get_fieldtranslations", "(", "instance", ",", "field", "=", "None", ",", "lang", "=", "None", ")", ":", "# Basic filtering: filter translations by module, model an object_id", "_filter", "=", "{", "\"module\"", ":", "instance", ".", "__module__", ",", "\"mode...
Get all the translations for this object.
[ "Get", "all", "the", "translations", "for", "this", "object", "." ]
64d6adeb537747321d5020efedf5d7e0d135862d
https://github.com/intelligenia/modeltranslation/blob/64d6adeb537747321d5020efedf5d7e0d135862d/modeltranslation/translation.py#L93-L113
train
51,799