repo
stringlengths
7
54
path
stringlengths
4
192
url
stringlengths
87
284
code
stringlengths
78
104k
code_tokens
list
docstring
stringlengths
1
46.9k
docstring_tokens
list
language
stringclasses
1 value
partition
stringclasses
3 values
DLR-RM/RAFCON
source/rafcon/gui/clipboard.py
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/clipboard.py#L375-L450
def do_smart_selection_adaption(selection, parent_m): """ Reduce and extend transition and data flow element selection if already enclosed by selection The smart selection adaptation checks and ignores directly data flows and transitions which are selected without selected related origin or targets elements. Additional the linkage (data flows and transitions) if those origins and targets are covered by the selected elements is added to the selection. Thereby the selection it self is manipulated to provide direct feedback to the user. :param selection: :param parent_m: :return: """ def get_ports_related_to_data_flow(data_flow): from_port = data_flow.parent.get_data_port(data_flow.from_state, data_flow.from_key) to_port = data_flow.parent.get_data_port(data_flow.to_state, data_flow.to_key) return from_port, to_port def get_states_related_to_transition(transition): if transition.from_state == transition.parent.state_id or transition.from_state is None: from_state = transition.parent else: from_state = transition.parent.states[transition.from_state] if transition.to_state == transition.parent.state_id: to_state = transition.parent else: to_state = transition.parent.states[transition.to_state] if transition.to_outcome in transition.parent.outcomes: to_outcome = transition.parent.outcomes[transition.to_outcome] else: to_outcome = transition.to_outcome return from_state, to_state, to_outcome # reduce linkage selection by not fully by selection covered linkage possible_states = [state_m.state for state_m in selection.states] possible_outcomes = [outcome_m.outcome for outcome_m in selection.outcomes] for data_flow_m in selection.data_flows: from_port, to_port = get_ports_related_to_data_flow(data_flow_m.data_flow) if from_port.parent not in possible_states or to_port not in possible_states: selection.remove(data_flow_m) for transition_m in selection.transitions: from_state, to_state, to_oc = get_states_related_to_transition(transition_m.transition) if from_state not in possible_states or (to_state not in possible_states and to_oc not in possible_outcomes): selection.remove(transition_m) # extend linkage selection by fully by selected element enclosed linkage if parent_m and isinstance(parent_m.state, ContainerState): state_ids = [state.state_id for state in possible_states] port_ids = [sv_m.scoped_variable.data_port_id for sv_m in selection.scoped_variables] + \ [ip_m.data_port.data_port_id for ip_m in selection.input_data_ports] + \ [op_m.data_port.data_port_id for op_m in selection.output_data_ports] ports = [sv_m.scoped_variable for sv_m in selection.scoped_variables] + \ [ip_m.data_port for ip_m in selection.input_data_ports] + \ [op_m.data_port for op_m in selection.output_data_ports] related_transitions, related_data_flows = \ parent_m.state.related_linkage_states_and_scoped_variables(state_ids, port_ids) # extend by selected states or a port and a state enclosed data flows for data_flow in related_data_flows['enclosed']: data_flow_m = parent_m.get_data_flow_m(data_flow.data_flow_id) if data_flow_m not in selection.data_flows: selection.add(data_flow_m) # extend by selected ports enclosed data flows for data_flow_id, data_flow in parent_m.state.data_flows.items(): from_port, to_port = get_ports_related_to_data_flow(data_flow) if from_port in ports and to_port in ports: selection.add(parent_m.get_data_flow_m(data_flow_id)) # extend by selected states enclosed transitions for transition in related_transitions['enclosed']: transition_m = parent_m.get_transition_m(transition.transition_id) if transition_m not in selection.transitions: selection.add(transition_m) # extend by selected state and outcome enclosed transitions for transition_id, transition in parent_m.state.transitions.items(): from_state, to_state, to_oc = get_states_related_to_transition(transition) if from_state in possible_states and to_oc in possible_outcomes: selection.add(parent_m.get_transition_m(transition_id))
[ "def", "do_smart_selection_adaption", "(", "selection", ",", "parent_m", ")", ":", "def", "get_ports_related_to_data_flow", "(", "data_flow", ")", ":", "from_port", "=", "data_flow", ".", "parent", ".", "get_data_port", "(", "data_flow", ".", "from_state", ",", "d...
Reduce and extend transition and data flow element selection if already enclosed by selection The smart selection adaptation checks and ignores directly data flows and transitions which are selected without selected related origin or targets elements. Additional the linkage (data flows and transitions) if those origins and targets are covered by the selected elements is added to the selection. Thereby the selection it self is manipulated to provide direct feedback to the user. :param selection: :param parent_m: :return:
[ "Reduce", "and", "extend", "transition", "and", "data", "flow", "element", "selection", "if", "already", "enclosed", "by", "selection" ]
python
train
Naresh1318/crystal
crystal/app.py
https://github.com/Naresh1318/crystal/blob/6bb43fd1128296cc59b8ed3bc03064cc61c6bd88/crystal/app.py#L213-L226
def delete_project(): """ Delete the selected run from the database. :return: """ assert request.method == "POST", "POST request expected received {}".format(request.method) if request.method == "POST": try: selections = json.loads(request.form["selections"]) utils.drop_project(selections["project"]) return jsonify({"response": "deleted {}".format(selections["project"])}) except Exception as e: logging.error(e) return jsonify({"0": "__EMPTY"})
[ "def", "delete_project", "(", ")", ":", "assert", "request", ".", "method", "==", "\"POST\"", ",", "\"POST request expected received {}\"", ".", "format", "(", "request", ".", "method", ")", "if", "request", ".", "method", "==", "\"POST\"", ":", "try", ":", ...
Delete the selected run from the database. :return:
[ "Delete", "the", "selected", "run", "from", "the", "database", ".", ":", "return", ":" ]
python
train
brechtm/rinohtype
src/rinoh/backend/pdf/xobject/purepng.py
https://github.com/brechtm/rinohtype/blob/40a63c4e5ad7550f62b6860f1812cb67cafb9dc7/src/rinoh/backend/pdf/xobject/purepng.py#L443-L453
def popdict(src, keys): """ Extract all keys (with values) from `src` dictionary as new dictionary values are removed from source dictionary. """ new = {} for key in keys: if key in src: new[key] = src.pop(key) return new
[ "def", "popdict", "(", "src", ",", "keys", ")", ":", "new", "=", "{", "}", "for", "key", "in", "keys", ":", "if", "key", "in", "src", ":", "new", "[", "key", "]", "=", "src", ".", "pop", "(", "key", ")", "return", "new" ]
Extract all keys (with values) from `src` dictionary as new dictionary values are removed from source dictionary.
[ "Extract", "all", "keys", "(", "with", "values", ")", "from", "src", "dictionary", "as", "new", "dictionary" ]
python
train
Chilipp/docrep
docrep/__init__.py
https://github.com/Chilipp/docrep/blob/637971f76e1a6e1c70e36dcd1b02bbc37ba02487/docrep/__init__.py#L439-L465
def with_indents(self, s, indent=0, stacklevel=3): """ Substitute a string with the indented :attr:`params` Parameters ---------- s: str The string in which to substitute indent: int The number of spaces that the substitution should be indented stacklevel: int The stacklevel for the warning raised in :func:`safe_module` when encountering an invalid key in the string Returns ------- str The substituted string See Also -------- with_indent, dedents""" # we make a new dictionary with objects that indent the original # strings if necessary. Note that the first line is not indented d = {key: _StrWithIndentation(val, indent) for key, val in six.iteritems(self.params)} return safe_modulo(s, d, stacklevel=stacklevel)
[ "def", "with_indents", "(", "self", ",", "s", ",", "indent", "=", "0", ",", "stacklevel", "=", "3", ")", ":", "# we make a new dictionary with objects that indent the original", "# strings if necessary. Note that the first line is not indented", "d", "=", "{", "key", ":",...
Substitute a string with the indented :attr:`params` Parameters ---------- s: str The string in which to substitute indent: int The number of spaces that the substitution should be indented stacklevel: int The stacklevel for the warning raised in :func:`safe_module` when encountering an invalid key in the string Returns ------- str The substituted string See Also -------- with_indent, dedents
[ "Substitute", "a", "string", "with", "the", "indented", ":", "attr", ":", "params" ]
python
train
tjcsl/ion
intranet/apps/dashboard/views.py
https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/dashboard/views.py#L340-L374
def paginate_announcements_list(request, context, items): """ ***TODO*** Migrate to django Paginator (see lostitems) """ # pagination if "start" in request.GET: try: start_num = int(request.GET.get("start")) except ValueError: start_num = 0 else: start_num = 0 display_num = 10 end_num = start_num + display_num prev_page = start_num - display_num more_items = ((len(items) - start_num) > display_num) try: items_sorted = items[start_num:end_num] except (ValueError, AssertionError): items_sorted = items[:display_num] else: items = items_sorted context.update({ "items": items, "start_num": start_num, "end_num": end_num, "prev_page": prev_page, "more_items": more_items, }) return context, items
[ "def", "paginate_announcements_list", "(", "request", ",", "context", ",", "items", ")", ":", "# pagination", "if", "\"start\"", "in", "request", ".", "GET", ":", "try", ":", "start_num", "=", "int", "(", "request", ".", "GET", ".", "get", "(", "\"start\""...
***TODO*** Migrate to django Paginator (see lostitems)
[ "***", "TODO", "***", "Migrate", "to", "django", "Paginator", "(", "see", "lostitems", ")" ]
python
train
bapakode/OmMongo
ommongo/fields/fields.py
https://github.com/bapakode/OmMongo/blob/52b5a5420516dc709f2d2eb065818c7973991ce3/ommongo/fields/fields.py#L285-L294
def unwrap(self, value, session=None): ''' Validate and then unwrap ``value`` for object creation. :param value: list returned from the database. ''' self.validate_unwrap(value) ret = [] for field, value in izip(self.types, value): ret.append(field.unwrap(value, session=session)) return tuple(ret)
[ "def", "unwrap", "(", "self", ",", "value", ",", "session", "=", "None", ")", ":", "self", ".", "validate_unwrap", "(", "value", ")", "ret", "=", "[", "]", "for", "field", ",", "value", "in", "izip", "(", "self", ".", "types", ",", "value", ")", ...
Validate and then unwrap ``value`` for object creation. :param value: list returned from the database.
[ "Validate", "and", "then", "unwrap", "value", "for", "object", "creation", "." ]
python
train
ibis-project/ibis
ibis/client.py
https://github.com/ibis-project/ibis/blob/1e39a5fd9ef088b45c155e8a5f541767ee8ef2e7/ibis/client.py#L226-L252
def explain(self, expr, params=None): """ Query for and return the query plan associated with the indicated expression or SQL query. Returns ------- plan : string """ if isinstance(expr, ir.Expr): context = self.dialect.make_context(params=params) query_ast = self._build_ast(expr, context) if len(query_ast.queries) > 1: raise Exception('Multi-query expression') query = query_ast.queries[0].compile() else: query = expr statement = 'EXPLAIN {0}'.format(query) with self._execute(statement, results=True) as cur: result = self._get_list(cur) return 'Query:\n{0}\n\n{1}'.format( util.indent(query, 2), '\n'.join(result) )
[ "def", "explain", "(", "self", ",", "expr", ",", "params", "=", "None", ")", ":", "if", "isinstance", "(", "expr", ",", "ir", ".", "Expr", ")", ":", "context", "=", "self", ".", "dialect", ".", "make_context", "(", "params", "=", "params", ")", "qu...
Query for and return the query plan associated with the indicated expression or SQL query. Returns ------- plan : string
[ "Query", "for", "and", "return", "the", "query", "plan", "associated", "with", "the", "indicated", "expression", "or", "SQL", "query", "." ]
python
train
inasafe/inasafe
safe/gis/tools.py
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gis/tools.py#L90-L130
def reclassify_value(one_value, ranges): """This function will return the classified value according to ranges. The algorithm will return None if the continuous value has not any class. :param one_value: The continuous value to classify. :type one_value: float :param ranges: Classes, following the hazard classification definitions. :type ranges: OrderedDict :return: The classified value or None. :rtype: float or None """ if (one_value is None or (hasattr(one_value, 'isNull') and one_value.isNull())): return None for threshold_id, threshold in list(ranges.items()): value_min = threshold[0] value_max = threshold[1] # If, eg [0, 0], the one_value must be equal to 0. if value_min == value_max and value_max == one_value: return threshold_id # If, eg [None, 0], the one_value must be less or equal than 0. if value_min is None and one_value <= value_max: return threshold_id # If, eg [0, None], the one_value must be greater than 0. if value_max is None and one_value > value_min: return threshold_id # If, eg [0, 1], the one_value must be # between 0 excluded and 1 included. if value_min is not None and (value_min < one_value <= value_max): return threshold_id return None
[ "def", "reclassify_value", "(", "one_value", ",", "ranges", ")", ":", "if", "(", "one_value", "is", "None", "or", "(", "hasattr", "(", "one_value", ",", "'isNull'", ")", "and", "one_value", ".", "isNull", "(", ")", ")", ")", ":", "return", "None", "for...
This function will return the classified value according to ranges. The algorithm will return None if the continuous value has not any class. :param one_value: The continuous value to classify. :type one_value: float :param ranges: Classes, following the hazard classification definitions. :type ranges: OrderedDict :return: The classified value or None. :rtype: float or None
[ "This", "function", "will", "return", "the", "classified", "value", "according", "to", "ranges", "." ]
python
train
knipknap/SpiffWorkflow
SpiffWorkflow/serializer/xml.py
https://github.com/knipknap/SpiffWorkflow/blob/f0af7f59a332e0619e4f3c00a7d4a3d230760e00/SpiffWorkflow/serializer/xml.py#L193-L206
def serialize_operator_equal(self, op): """ Serializer for :meth:`SpiffWorkflow.operators.Equal`. Example:: <equals> <value>text</value> <value><attribute>foobar</attribute></value> <value><path>foobar</path></value> </equals> """ elem = etree.Element('equals') return self.serialize_value_list(elem, op.args)
[ "def", "serialize_operator_equal", "(", "self", ",", "op", ")", ":", "elem", "=", "etree", ".", "Element", "(", "'equals'", ")", "return", "self", ".", "serialize_value_list", "(", "elem", ",", "op", ".", "args", ")" ]
Serializer for :meth:`SpiffWorkflow.operators.Equal`. Example:: <equals> <value>text</value> <value><attribute>foobar</attribute></value> <value><path>foobar</path></value> </equals>
[ "Serializer", "for", ":", "meth", ":", "SpiffWorkflow", ".", "operators", ".", "Equal", "." ]
python
valid
klis87/django-cloudinary-storage
cloudinary_storage/management/commands/deleteorphanedmedia.py
https://github.com/klis87/django-cloudinary-storage/blob/b8cabd2ebbf67b9cfbbf4defee1a750fea5950a9/cloudinary_storage/management/commands/deleteorphanedmedia.py#L71-L82
def get_files_to_remove(self): """ Returns orphaned media files to be removed grouped by resource type. All files which paths start with any of exclude paths are ignored. """ files_to_remove = {} needful_files = self.get_needful_files() for resources_type, resources in self.get_uploaded_resources(): exclude_paths = self.get_exclude_paths() resources = {resource for resource in resources if not resource.startswith(exclude_paths)} files_to_remove[resources_type] = resources - needful_files return files_to_remove
[ "def", "get_files_to_remove", "(", "self", ")", ":", "files_to_remove", "=", "{", "}", "needful_files", "=", "self", ".", "get_needful_files", "(", ")", "for", "resources_type", ",", "resources", "in", "self", ".", "get_uploaded_resources", "(", ")", ":", "exc...
Returns orphaned media files to be removed grouped by resource type. All files which paths start with any of exclude paths are ignored.
[ "Returns", "orphaned", "media", "files", "to", "be", "removed", "grouped", "by", "resource", "type", ".", "All", "files", "which", "paths", "start", "with", "any", "of", "exclude", "paths", "are", "ignored", "." ]
python
train
xolox/python-vcs-repo-mgr
vcs_repo_mgr/__init__.py
https://github.com/xolox/python-vcs-repo-mgr/blob/fdad2441a3e7ba5deeeddfa1c2f5ebc00c393aed/vcs_repo_mgr/__init__.py#L1532-L1568
def interactive_merge_conflict_handler(self, exception): """ Give the operator a chance to interactively resolve merge conflicts. :param exception: An :exc:`~executor.ExternalCommandFailed` object. :returns: :data:`True` if the operator has interactively resolved any merge conflicts (and as such the merge error doesn't need to be propagated), :data:`False` otherwise. This method checks whether :data:`sys.stdin` is connected to a terminal to decide whether interaction with an operator is possible. If it is then an interactive terminal prompt is used to ask the operator to resolve the merge conflict(s). If the operator confirms the prompt, the merge error is swallowed instead of propagated. When :data:`sys.stdin` is not connected to a terminal or the operator denies the prompt the merge error is propagated. """ if connected_to_terminal(sys.stdin): logger.info(compact(""" It seems that I'm connected to a terminal so I'll give you a chance to interactively fix the merge conflict(s) in order to avoid propagating the merge error. Please mark or stage your changes but don't commit the result just yet (it will be done for you). """)) while True: if prompt_for_confirmation("Ignore merge error because you've resolved all conflicts?"): if self.merge_conflicts: logger.warning("I'm still seeing merge conflicts, please double check! (%s)", concatenate(self.merge_conflicts)) else: # The operator resolved all conflicts. return True else: # The operator wants us to propagate the error. break return False
[ "def", "interactive_merge_conflict_handler", "(", "self", ",", "exception", ")", ":", "if", "connected_to_terminal", "(", "sys", ".", "stdin", ")", ":", "logger", ".", "info", "(", "compact", "(", "\"\"\"\n It seems that I'm connected to a terminal so I'll ...
Give the operator a chance to interactively resolve merge conflicts. :param exception: An :exc:`~executor.ExternalCommandFailed` object. :returns: :data:`True` if the operator has interactively resolved any merge conflicts (and as such the merge error doesn't need to be propagated), :data:`False` otherwise. This method checks whether :data:`sys.stdin` is connected to a terminal to decide whether interaction with an operator is possible. If it is then an interactive terminal prompt is used to ask the operator to resolve the merge conflict(s). If the operator confirms the prompt, the merge error is swallowed instead of propagated. When :data:`sys.stdin` is not connected to a terminal or the operator denies the prompt the merge error is propagated.
[ "Give", "the", "operator", "a", "chance", "to", "interactively", "resolve", "merge", "conflicts", "." ]
python
train
mattja/distob
distob/arrays.py
https://github.com/mattja/distob/blob/b0fc49e157189932c70231077ed35e1aa5717da9/distob/arrays.py#L917-L923
def _valid_distaxis(shapes, ax): """`ax` is a valid candidate for a distributed axis if the given subarray shapes are all the same when ignoring axis `ax`""" compare_shapes = np.vstack(shapes) if ax < compare_shapes.shape[1]: compare_shapes[:, ax] = -1 return np.count_nonzero(compare_shapes - compare_shapes[0]) == 0
[ "def", "_valid_distaxis", "(", "shapes", ",", "ax", ")", ":", "compare_shapes", "=", "np", ".", "vstack", "(", "shapes", ")", "if", "ax", "<", "compare_shapes", ".", "shape", "[", "1", "]", ":", "compare_shapes", "[", ":", ",", "ax", "]", "=", "-", ...
`ax` is a valid candidate for a distributed axis if the given subarray shapes are all the same when ignoring axis `ax`
[ "ax", "is", "a", "valid", "candidate", "for", "a", "distributed", "axis", "if", "the", "given", "subarray", "shapes", "are", "all", "the", "same", "when", "ignoring", "axis", "ax" ]
python
valid
saltstack/salt
salt/modules/cp.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/cp.py#L63-L89
def recv(files, dest): ''' Used with salt-cp, pass the files dict, and the destination. This function receives small fast copy files from the master via salt-cp. It does not work via the CLI. ''' ret = {} for path, data in six.iteritems(files): if os.path.basename(path) == os.path.basename(dest) \ and not os.path.isdir(dest): final = dest elif os.path.isdir(dest): final = os.path.join(dest, os.path.basename(path)) elif os.path.isdir(os.path.dirname(dest)): final = dest else: return 'Destination unavailable' try: with salt.utils.files.fopen(final, 'w+') as fp_: fp_.write(data) ret[final] = True except IOError: ret[final] = False return ret
[ "def", "recv", "(", "files", ",", "dest", ")", ":", "ret", "=", "{", "}", "for", "path", ",", "data", "in", "six", ".", "iteritems", "(", "files", ")", ":", "if", "os", ".", "path", ".", "basename", "(", "path", ")", "==", "os", ".", "path", ...
Used with salt-cp, pass the files dict, and the destination. This function receives small fast copy files from the master via salt-cp. It does not work via the CLI.
[ "Used", "with", "salt", "-", "cp", "pass", "the", "files", "dict", "and", "the", "destination", "." ]
python
train
KelSolaar/Manager
manager/components_manager.py
https://github.com/KelSolaar/Manager/blob/39c8153fc021fc8a76e345a6e336ec2644f089d1/manager/components_manager.py#L1217-L1238
def list_components(self, dependency_order=True): """ Lists the Components by dependency resolving. Usage:: >>> manager = Manager(("./manager/tests/tests_manager/resources/components/core",)) >>> manager.register_components() True >>> manager.list_components() [u'core.tests_component_a', u'core.tests_component_b'] :param dependency_order: Components are returned by dependency order. :type dependency_order: bool """ if dependency_order: return list(itertools.chain.from_iterable([sorted(list(batch)) for batch in foundations.common.dependency_resolver( dict((key, value.require) for (key, value) in self))])) else: return [key for (key, value) in self]
[ "def", "list_components", "(", "self", ",", "dependency_order", "=", "True", ")", ":", "if", "dependency_order", ":", "return", "list", "(", "itertools", ".", "chain", ".", "from_iterable", "(", "[", "sorted", "(", "list", "(", "batch", ")", ")", "for", ...
Lists the Components by dependency resolving. Usage:: >>> manager = Manager(("./manager/tests/tests_manager/resources/components/core",)) >>> manager.register_components() True >>> manager.list_components() [u'core.tests_component_a', u'core.tests_component_b'] :param dependency_order: Components are returned by dependency order. :type dependency_order: bool
[ "Lists", "the", "Components", "by", "dependency", "resolving", "." ]
python
train
SuperCowPowers/workbench
workbench/server/workbench_server.py
https://github.com/SuperCowPowers/workbench/blob/710232756dd717f734253315e3d0b33c9628dafb/workbench/server/workbench_server.py#L659-L666
def _help_workers(self): """ Help on all the available workers """ help = 'Workbench Workers:' for worker in self.list_all_workers(): full_help = self.work_request('help_formatter', worker)['help_formatter']['help'] compact_help = full_help.split('\n')[:4] help += '\n\n%s' % '\n'.join(compact_help) return help
[ "def", "_help_workers", "(", "self", ")", ":", "help", "=", "'Workbench Workers:'", "for", "worker", "in", "self", ".", "list_all_workers", "(", ")", ":", "full_help", "=", "self", ".", "work_request", "(", "'help_formatter'", ",", "worker", ")", "[", "'help...
Help on all the available workers
[ "Help", "on", "all", "the", "available", "workers" ]
python
train
xflr6/concepts
concepts/tools.py
https://github.com/xflr6/concepts/blob/2801b27b05fa02cccee7d549451810ffcbf5c942/concepts/tools.py#L101-L107
def issuperset(self, items): """Return whether this collection contains all items. >>> Unique(['spam', 'eggs']).issuperset(['spam', 'spam', 'spam']) True """ return all(_compat.map(self._seen.__contains__, items))
[ "def", "issuperset", "(", "self", ",", "items", ")", ":", "return", "all", "(", "_compat", ".", "map", "(", "self", ".", "_seen", ".", "__contains__", ",", "items", ")", ")" ]
Return whether this collection contains all items. >>> Unique(['spam', 'eggs']).issuperset(['spam', 'spam', 'spam']) True
[ "Return", "whether", "this", "collection", "contains", "all", "items", "." ]
python
train
SeattleTestbed/seash
seash_modules.py
https://github.com/SeattleTestbed/seash/blob/40f9d2285662ff8b61e0468b4196acee089b273b/seash_modules.py#L103-L162
def ensure_no_conflicts_in_commanddicts(originaldict, comparedict): """ <Purpose> Recursively compares two commanddicts to see if they have conflicting commands. <Arguments> originaldict: A commanddict to compare. comparedict: A commanddict to compare. <Side Effects> None <Exceptions> ModuleConflictError - A command was conflicting. The error detail is the problematic command. <Returns> None """ """ Child nodes are identical if they all of the following are identical: helptext/callback/summary. There are 3 cases we have to worry about. > Shared child node. > Child nodes are identical. Check grandchildren. > Only one is defined. Check grandchildren. > Both child nodes are defined and are not identical. Reject. > Node is not shared. Accept. """ for child in comparedict.keys(): # Node not shared. if child not in originaldict: continue # Shared node comparechild_defined = is_commanddictnode_defined(comparedict[child]) originalchild_defined = is_commanddictnode_defined(originaldict[child]) # Only one is defined, or; # both are defined and they are identical if ((comparechild_defined ^ originalchild_defined) or (comparechild_defined and originalchild_defined and _are_cmd_nodes_same(originaldict[child], comparedict[child]))): try: ensure_no_conflicts_in_commanddicts(comparedict[child]['children'], originaldict[child]['children']) except seash_exceptions.ModuleConflictError, e: # Reconstruct the full command recursively raise seash_exceptions.ModuleConflictError(child + " " + str(e) + " ("+module_name+")") continue # Not identical. Conflict found. # Also include which module the conflicting module was found from. if 'module' in originaldict[child]: module_name = originaldict['module'][child] else: module_name = "default" raise seash_exceptions.ModuleConflictError(child + ' ('+module_name+')')
[ "def", "ensure_no_conflicts_in_commanddicts", "(", "originaldict", ",", "comparedict", ")", ":", "\"\"\"\n Child nodes are identical if they all of the following are identical: \n helptext/callback/summary.\n \n There are 3 cases we have to worry about.\n > Shared child node.\n > Child ...
<Purpose> Recursively compares two commanddicts to see if they have conflicting commands. <Arguments> originaldict: A commanddict to compare. comparedict: A commanddict to compare. <Side Effects> None <Exceptions> ModuleConflictError - A command was conflicting. The error detail is the problematic command. <Returns> None
[ "<Purpose", ">", "Recursively", "compares", "two", "commanddicts", "to", "see", "if", "they", "have", "conflicting", "commands", ".", "<Arguments", ">", "originaldict", ":", "A", "commanddict", "to", "compare", ".", "comparedict", ":", "A", "commanddict", "to", ...
python
train
OnroerendErfgoed/language-tags
language_tags/tags.py
https://github.com/OnroerendErfgoed/language-tags/blob/acb91e5458d22617f344e2eefaba9a9865373fdd/language_tags/tags.py#L134-L154
def languages(macrolanguage): """ Get a list of :class:`language_tags.Subtag.Subtag` objects given the string macrolanguage. :param string macrolanguage: subtag macrolanguage. :return: a list of the macrolanguage :class:`language_tags.Subtag.Subtag` objects. :raise Exception: if the macrolanguage does not exists. """ results = [] macrolanguage = macrolanguage.lower() macrolanguage_data = data.get('macrolanguage') if macrolanguage not in macrolanguage_data: raise Exception('\'' + macrolanguage + '\' is not a macrolanguage.') for registry_item in registry: record = registry_item if 'Macrolanguage' in record: if record['Macrolanguage'] == macrolanguage: results.append(Subtag(record['Subtag'], record['Type'])) return results
[ "def", "languages", "(", "macrolanguage", ")", ":", "results", "=", "[", "]", "macrolanguage", "=", "macrolanguage", ".", "lower", "(", ")", "macrolanguage_data", "=", "data", ".", "get", "(", "'macrolanguage'", ")", "if", "macrolanguage", "not", "in", "macr...
Get a list of :class:`language_tags.Subtag.Subtag` objects given the string macrolanguage. :param string macrolanguage: subtag macrolanguage. :return: a list of the macrolanguage :class:`language_tags.Subtag.Subtag` objects. :raise Exception: if the macrolanguage does not exists.
[ "Get", "a", "list", "of", ":", "class", ":", "language_tags", ".", "Subtag", ".", "Subtag", "objects", "given", "the", "string", "macrolanguage", "." ]
python
train
gabstopper/smc-python
smc/routing/route_map.py
https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/routing/route_map.py#L447-L456
def search_rule(self, search): """ Search the RouteMap policy using a search string :param str search: search string for a contains match against the rule name and comments field :rtype: list(RouteMapRule) """ return [RouteMapRule(**rule) for rule in self.make_request( resource='search_rule', params={'filter': search})]
[ "def", "search_rule", "(", "self", ",", "search", ")", ":", "return", "[", "RouteMapRule", "(", "*", "*", "rule", ")", "for", "rule", "in", "self", ".", "make_request", "(", "resource", "=", "'search_rule'", ",", "params", "=", "{", "'filter'", ":", "s...
Search the RouteMap policy using a search string :param str search: search string for a contains match against the rule name and comments field :rtype: list(RouteMapRule)
[ "Search", "the", "RouteMap", "policy", "using", "a", "search", "string", ":", "param", "str", "search", ":", "search", "string", "for", "a", "contains", "match", "against", "the", "rule", "name", "and", "comments", "field", ":", "rtype", ":", "list", "(", ...
python
train
Clinical-Genomics/scout
scout/adapter/mongo/query.py
https://github.com/Clinical-Genomics/scout/blob/90a551e2e1653a319e654c2405c2866f93d0ebb9/scout/adapter/mongo/query.py#L11-L50
def build_variant_query(self, query=None, category='snv', variant_type=['clinical']): """Build a mongo query across multiple cases. Translate query options from a form into a complete mongo query dictionary. Beware that unindexed queries against a large variant collection will be extremely slow. Currently indexed query options: hgnc_symbols rank_score variant_type category Args: query(dict): A query dictionary for the database, from a query form. category(str): 'snv', 'sv', 'str' or 'cancer' variant_type(str): 'clinical' or 'research' Returns: mongo_query : A dictionary in the mongo query format. """ query = query or {} mongo_variant_query = {} LOG.debug("Building a mongo query for %s" % query) if query.get('hgnc_symbols'): mongo_variant_query['hgnc_symbols'] = {'$in': query['hgnc_symbols']} mongo_variant_query['variant_type'] = {'$in': variant_type} mongo_variant_query['category'] = category rank_score = query.get('rank_score') or 15 mongo_variant_query['rank_score'] = {'$gte': rank_score} LOG.debug("Querying %s" % mongo_variant_query) return mongo_variant_query
[ "def", "build_variant_query", "(", "self", ",", "query", "=", "None", ",", "category", "=", "'snv'", ",", "variant_type", "=", "[", "'clinical'", "]", ")", ":", "query", "=", "query", "or", "{", "}", "mongo_variant_query", "=", "{", "}", "LOG", ".", "d...
Build a mongo query across multiple cases. Translate query options from a form into a complete mongo query dictionary. Beware that unindexed queries against a large variant collection will be extremely slow. Currently indexed query options: hgnc_symbols rank_score variant_type category Args: query(dict): A query dictionary for the database, from a query form. category(str): 'snv', 'sv', 'str' or 'cancer' variant_type(str): 'clinical' or 'research' Returns: mongo_query : A dictionary in the mongo query format.
[ "Build", "a", "mongo", "query", "across", "multiple", "cases", ".", "Translate", "query", "options", "from", "a", "form", "into", "a", "complete", "mongo", "query", "dictionary", "." ]
python
test
ethereum/eth-account
eth_account/_utils/signing.py
https://github.com/ethereum/eth-account/blob/335199b815ae34fea87f1523e2f29777fd52946e/eth_account/_utils/signing.py#L96-L117
def hash_of_signed_transaction(txn_obj): ''' Regenerate the hash of the signed transaction object. 1. Infer the chain ID from the signature 2. Strip out signature from transaction 3. Annotate the transaction with that ID, if available 4. Take the hash of the serialized, unsigned, chain-aware transaction Chain ID inference and annotation is according to EIP-155 See details at https://github.com/ethereum/EIPs/blob/master/EIPS/eip-155.md :return: the hash of the provided transaction, to be signed ''' (chain_id, _v) = extract_chain_id(txn_obj.v) unsigned_parts = strip_signature(txn_obj) if chain_id is None: signable_transaction = UnsignedTransaction(*unsigned_parts) else: extended_transaction = unsigned_parts + [chain_id, 0, 0] signable_transaction = ChainAwareUnsignedTransaction(*extended_transaction) return signable_transaction.hash()
[ "def", "hash_of_signed_transaction", "(", "txn_obj", ")", ":", "(", "chain_id", ",", "_v", ")", "=", "extract_chain_id", "(", "txn_obj", ".", "v", ")", "unsigned_parts", "=", "strip_signature", "(", "txn_obj", ")", "if", "chain_id", "is", "None", ":", "signa...
Regenerate the hash of the signed transaction object. 1. Infer the chain ID from the signature 2. Strip out signature from transaction 3. Annotate the transaction with that ID, if available 4. Take the hash of the serialized, unsigned, chain-aware transaction Chain ID inference and annotation is according to EIP-155 See details at https://github.com/ethereum/EIPs/blob/master/EIPS/eip-155.md :return: the hash of the provided transaction, to be signed
[ "Regenerate", "the", "hash", "of", "the", "signed", "transaction", "object", "." ]
python
train
HPENetworking/topology_lib_ip
lib/topology_lib_ip/library.py
https://github.com/HPENetworking/topology_lib_ip/blob/c69cc3db80d96575d787fdc903a9370d2df1c5ae/lib/topology_lib_ip/library.py#L99-L146
def _parse_ip_stats_link_show(raw_result): """ Parse the 'ip -s link show dev <dev>' command raw output. :param str raw_result: vtysh raw result string. :rtype: dict :return: The parsed result of the show interface command in a \ dictionary of the form: :: { 'rx_bytes': 0, 'rx_packets': 0, 'rx_errors': 0, 'rx_dropped': 0, 'rx_overrun': 0, 'rx_mcast': 0, 'tx_bytes': 0, 'tx_packets': 0, 'tx_errors': 0, 'tx_dropped': 0, 'tx_carrier': 0, 'tx_collisions': 0, } """ show_re = ( r'.+?RX:.*?\n' r'\s*(?P<rx_bytes>\d+)\s+(?P<rx_packets>\d+)\s+(?P<rx_errors>\d+)\s+' r'(?P<rx_dropped>\d+)\s+(?P<rx_overrun>\d+)\s+(?P<rx_mcast>\d+)' r'.+?TX:.*?\n' r'\s*(?P<tx_bytes>\d+)\s+(?P<tx_packets>\d+)\s+(?P<tx_errors>\d+)\s+' r'(?P<tx_dropped>\d+)\s+(?P<tx_carrier>\d+)\s+(?P<tx_collisions>\d+)' ) re_result = match(show_re, raw_result, DOTALL) result = None if (re_result): result = re_result.groupdict() for key, value in result.items(): if value is not None: if value.isdigit(): result[key] = int(value) return result
[ "def", "_parse_ip_stats_link_show", "(", "raw_result", ")", ":", "show_re", "=", "(", "r'.+?RX:.*?\\n'", "r'\\s*(?P<rx_bytes>\\d+)\\s+(?P<rx_packets>\\d+)\\s+(?P<rx_errors>\\d+)\\s+'", "r'(?P<rx_dropped>\\d+)\\s+(?P<rx_overrun>\\d+)\\s+(?P<rx_mcast>\\d+)'", "r'.+?TX:.*?\\n'", "r'\\s*(?P<tx...
Parse the 'ip -s link show dev <dev>' command raw output. :param str raw_result: vtysh raw result string. :rtype: dict :return: The parsed result of the show interface command in a \ dictionary of the form: :: { 'rx_bytes': 0, 'rx_packets': 0, 'rx_errors': 0, 'rx_dropped': 0, 'rx_overrun': 0, 'rx_mcast': 0, 'tx_bytes': 0, 'tx_packets': 0, 'tx_errors': 0, 'tx_dropped': 0, 'tx_carrier': 0, 'tx_collisions': 0, }
[ "Parse", "the", "ip", "-", "s", "link", "show", "dev", "<dev", ">", "command", "raw", "output", "." ]
python
train
zarr-developers/zarr
zarr/hierarchy.py
https://github.com/zarr-developers/zarr/blob/fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5/zarr/hierarchy.py#L667-L669
def create_groups(self, *names, **kwargs): """Convenience method to create multiple groups in a single call.""" return tuple(self.create_group(name, **kwargs) for name in names)
[ "def", "create_groups", "(", "self", ",", "*", "names", ",", "*", "*", "kwargs", ")", ":", "return", "tuple", "(", "self", ".", "create_group", "(", "name", ",", "*", "*", "kwargs", ")", "for", "name", "in", "names", ")" ]
Convenience method to create multiple groups in a single call.
[ "Convenience", "method", "to", "create", "multiple", "groups", "in", "a", "single", "call", "." ]
python
train
JdeRobot/base
src/drivers/MAVLinkServer/MAVProxy/pymavlink/dialects/v10/matrixpilot.py
https://github.com/JdeRobot/base/blob/303b18992785b2fe802212f2d758a60873007f1f/src/drivers/MAVLinkServer/MAVProxy/pymavlink/dialects/v10/matrixpilot.py#L9055-L9073
def raw_imu_send(self, time_usec, xacc, yacc, zacc, xgyro, ygyro, zgyro, xmag, ymag, zmag, force_mavlink1=False): ''' The RAW IMU readings for the usual 9DOF sensor setup. This message should always contain the true raw values without any scaling to allow data capture and system debugging. time_usec : Timestamp (microseconds since UNIX epoch or microseconds since system boot) (uint64_t) xacc : X acceleration (raw) (int16_t) yacc : Y acceleration (raw) (int16_t) zacc : Z acceleration (raw) (int16_t) xgyro : Angular speed around X axis (raw) (int16_t) ygyro : Angular speed around Y axis (raw) (int16_t) zgyro : Angular speed around Z axis (raw) (int16_t) xmag : X Magnetic field (raw) (int16_t) ymag : Y Magnetic field (raw) (int16_t) zmag : Z Magnetic field (raw) (int16_t) ''' return self.send(self.raw_imu_encode(time_usec, xacc, yacc, zacc, xgyro, ygyro, zgyro, xmag, ymag, zmag), force_mavlink1=force_mavlink1)
[ "def", "raw_imu_send", "(", "self", ",", "time_usec", ",", "xacc", ",", "yacc", ",", "zacc", ",", "xgyro", ",", "ygyro", ",", "zgyro", ",", "xmag", ",", "ymag", ",", "zmag", ",", "force_mavlink1", "=", "False", ")", ":", "return", "self", ".", "send"...
The RAW IMU readings for the usual 9DOF sensor setup. This message should always contain the true raw values without any scaling to allow data capture and system debugging. time_usec : Timestamp (microseconds since UNIX epoch or microseconds since system boot) (uint64_t) xacc : X acceleration (raw) (int16_t) yacc : Y acceleration (raw) (int16_t) zacc : Z acceleration (raw) (int16_t) xgyro : Angular speed around X axis (raw) (int16_t) ygyro : Angular speed around Y axis (raw) (int16_t) zgyro : Angular speed around Z axis (raw) (int16_t) xmag : X Magnetic field (raw) (int16_t) ymag : Y Magnetic field (raw) (int16_t) zmag : Z Magnetic field (raw) (int16_t)
[ "The", "RAW", "IMU", "readings", "for", "the", "usual", "9DOF", "sensor", "setup", ".", "This", "message", "should", "always", "contain", "the", "true", "raw", "values", "without", "any", "scaling", "to", "allow", "data", "capture", "and", "system", "debuggi...
python
train
rwl/godot
godot/ui/graph_editor.py
https://github.com/rwl/godot/blob/013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f/godot/ui/graph_editor.py#L187-L193
def init ( self, parent ): """ Finishes initialising the editor by creating the underlying toolkit widget. """ self._graph = graph = Graph() ui = graph.edit_traits(parent=parent, kind="panel") self.control = ui.control
[ "def", "init", "(", "self", ",", "parent", ")", ":", "self", ".", "_graph", "=", "graph", "=", "Graph", "(", ")", "ui", "=", "graph", ".", "edit_traits", "(", "parent", "=", "parent", ",", "kind", "=", "\"panel\"", ")", "self", ".", "control", "=",...
Finishes initialising the editor by creating the underlying toolkit widget.
[ "Finishes", "initialising", "the", "editor", "by", "creating", "the", "underlying", "toolkit", "widget", "." ]
python
test
cimm-kzn/CGRtools
CGRtools/algorithms/morgan.py
https://github.com/cimm-kzn/CGRtools/blob/15a19b04f6e4e1d0dab8e0d32a0877c7f7d70f34/CGRtools/algorithms/morgan.py#L88-L105
def _eratosthenes(): """Yields the sequence of prime numbers via the Sieve of Eratosthenes.""" d = {} # map each composite integer to its first-found prime factor for q in count(2): # q gets 2, 3, 4, 5, ... ad infinitum p = d.pop(q, None) if p is None: # q not a key in D, so q is prime, therefore, yield it yield q # mark q squared as not-prime (with q as first-found prime factor) d[q * q] = q else: # let x <- smallest (N*p)+q which wasn't yet known to be composite # we just learned x is composite, with p first-found prime factor, # since p is the first-found prime factor of q -- find and mark it x = p + q while x in d: x += p d[x] = p
[ "def", "_eratosthenes", "(", ")", ":", "d", "=", "{", "}", "# map each composite integer to its first-found prime factor", "for", "q", "in", "count", "(", "2", ")", ":", "# q gets 2, 3, 4, 5, ... ad infinitum", "p", "=", "d", ".", "pop", "(", "q", ",", "None", ...
Yields the sequence of prime numbers via the Sieve of Eratosthenes.
[ "Yields", "the", "sequence", "of", "prime", "numbers", "via", "the", "Sieve", "of", "Eratosthenes", "." ]
python
train
dronekit/dronekit-python
dronekit/__init__.py
https://github.com/dronekit/dronekit-python/blob/91c147fa61f521f5fff5d0cee06d07ed93614af8/dronekit/__init__.py#L542-L590
def add_attribute_listener(self, attr_name, observer): """ Add an attribute listener callback. The callback function (``observer``) is invoked differently depending on the *type of attribute*. Attributes that represent sensor values or which are used to monitor connection status are updated whenever a message is received from the vehicle. Attributes which reflect vehicle "state" are only updated when their values change (for example :py:attr:`Vehicle.system_status`, :py:attr:`Vehicle.armed`, and :py:attr:`Vehicle.mode`). The callback can be removed using :py:func:`remove_attribute_listener`. .. note:: The :py:func:`on_attribute` decorator performs the same operation as this method, but with a more elegant syntax. Use ``add_attribute_listener`` by preference if you will need to remove the observer. The argument list for the callback is ``observer(object, attr_name, attribute_value)``: * ``self`` - the associated :py:class:`Vehicle`. This may be compared to a global vehicle handle to implement vehicle-specific callback handling (if needed). * ``attr_name`` - the attribute name. This can be used to infer which attribute has triggered if the same callback is used for watching several attributes. * ``value`` - the attribute value (so you don't need to re-query the vehicle object). The example below shows how to get callbacks for (global) location changes: .. code:: python #Callback to print the location in global frame def location_callback(self, attr_name, msg): print "Location (Global): ", msg #Add observer for the vehicle's current location vehicle.add_attribute_listener('global_frame', location_callback) See :ref:`vehicle_state_observe_attributes` for more information. :param String attr_name: The name of the attribute to watch (or '*' to watch all attributes). :param observer: The callback to invoke when a change in the attribute is detected. """ listeners_for_attr = self._attribute_listeners.get(attr_name) if listeners_for_attr is None: listeners_for_attr = [] self._attribute_listeners[attr_name] = listeners_for_attr if observer not in listeners_for_attr: listeners_for_attr.append(observer)
[ "def", "add_attribute_listener", "(", "self", ",", "attr_name", ",", "observer", ")", ":", "listeners_for_attr", "=", "self", ".", "_attribute_listeners", ".", "get", "(", "attr_name", ")", "if", "listeners_for_attr", "is", "None", ":", "listeners_for_attr", "=", ...
Add an attribute listener callback. The callback function (``observer``) is invoked differently depending on the *type of attribute*. Attributes that represent sensor values or which are used to monitor connection status are updated whenever a message is received from the vehicle. Attributes which reflect vehicle "state" are only updated when their values change (for example :py:attr:`Vehicle.system_status`, :py:attr:`Vehicle.armed`, and :py:attr:`Vehicle.mode`). The callback can be removed using :py:func:`remove_attribute_listener`. .. note:: The :py:func:`on_attribute` decorator performs the same operation as this method, but with a more elegant syntax. Use ``add_attribute_listener`` by preference if you will need to remove the observer. The argument list for the callback is ``observer(object, attr_name, attribute_value)``: * ``self`` - the associated :py:class:`Vehicle`. This may be compared to a global vehicle handle to implement vehicle-specific callback handling (if needed). * ``attr_name`` - the attribute name. This can be used to infer which attribute has triggered if the same callback is used for watching several attributes. * ``value`` - the attribute value (so you don't need to re-query the vehicle object). The example below shows how to get callbacks for (global) location changes: .. code:: python #Callback to print the location in global frame def location_callback(self, attr_name, msg): print "Location (Global): ", msg #Add observer for the vehicle's current location vehicle.add_attribute_listener('global_frame', location_callback) See :ref:`vehicle_state_observe_attributes` for more information. :param String attr_name: The name of the attribute to watch (or '*' to watch all attributes). :param observer: The callback to invoke when a change in the attribute is detected.
[ "Add", "an", "attribute", "listener", "callback", "." ]
python
train
Jammy2211/PyAutoLens
autolens/data/array/grids.py
https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/data/array/grids.py#L668-L679
def scaled_array_2d_with_sub_dimensions_from_sub_array_1d(self, sub_array_1d): """ Map a 1D sub-array the same dimension as the sub-grid to its original masked 2D sub-array and return it as a scaled array. Parameters ----------- sub_array_1d : ndarray The 1D sub-array of which is mapped to a 2D scaled sub-array the dimensions. """ return scaled_array.ScaledSquarePixelArray(array=self.sub_array_2d_from_sub_array_1d(sub_array_1d=sub_array_1d), pixel_scale=self.mask.pixel_scale / self.sub_grid_size, origin=self.mask.origin)
[ "def", "scaled_array_2d_with_sub_dimensions_from_sub_array_1d", "(", "self", ",", "sub_array_1d", ")", ":", "return", "scaled_array", ".", "ScaledSquarePixelArray", "(", "array", "=", "self", ".", "sub_array_2d_from_sub_array_1d", "(", "sub_array_1d", "=", "sub_array_1d", ...
Map a 1D sub-array the same dimension as the sub-grid to its original masked 2D sub-array and return it as a scaled array. Parameters ----------- sub_array_1d : ndarray The 1D sub-array of which is mapped to a 2D scaled sub-array the dimensions.
[ "Map", "a", "1D", "sub", "-", "array", "the", "same", "dimension", "as", "the", "sub", "-", "grid", "to", "its", "original", "masked", "2D", "sub", "-", "array", "and", "return", "it", "as", "a", "scaled", "array", "." ]
python
valid
numenta/htmresearch
htmresearch/frameworks/location/location_network_creation.py
https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/frameworks/location/location_network_creation.py#L645-L649
def getL2Representations(self): """ Returns the active representation in L2. """ return [set(L2.getSelf()._pooler.getActiveCells()) for L2 in self.L2Regions]
[ "def", "getL2Representations", "(", "self", ")", ":", "return", "[", "set", "(", "L2", ".", "getSelf", "(", ")", ".", "_pooler", ".", "getActiveCells", "(", ")", ")", "for", "L2", "in", "self", ".", "L2Regions", "]" ]
Returns the active representation in L2.
[ "Returns", "the", "active", "representation", "in", "L2", "." ]
python
train
ksbg/sparklanes
sparklanes/_framework/task.py
https://github.com/ksbg/sparklanes/blob/62e70892e6ae025be2f4c419f4afc34714d6884c/sparklanes/_framework/task.py#L121-L140
def cache(self, name, val, overwrite=True): """Assigns an attribute reference to all subsequent tasks. For example, if a task caches a DataFrame `df` using `self.cache('some_df', df)`, all tasks that follow can access the DataFrame using `self.some_df`. Note that manually assigned attributes that share the same name have precedence over cached attributes. Parameters ---------- name : str Name of the attribute val Attribute value overwrite : bool Indicates if the attribute shall be overwritten, or not (if `False`, and a cached attribute with the given name already exists, `sparklanes.errors.CacheError` will be thrown). """ if name in TaskCache.cached and not overwrite: raise CacheError('Object with name `%s` already in cache.' % name) TaskCache.cached[name] = val
[ "def", "cache", "(", "self", ",", "name", ",", "val", ",", "overwrite", "=", "True", ")", ":", "if", "name", "in", "TaskCache", ".", "cached", "and", "not", "overwrite", ":", "raise", "CacheError", "(", "'Object with name `%s` already in cache.'", "%", "name...
Assigns an attribute reference to all subsequent tasks. For example, if a task caches a DataFrame `df` using `self.cache('some_df', df)`, all tasks that follow can access the DataFrame using `self.some_df`. Note that manually assigned attributes that share the same name have precedence over cached attributes. Parameters ---------- name : str Name of the attribute val Attribute value overwrite : bool Indicates if the attribute shall be overwritten, or not (if `False`, and a cached attribute with the given name already exists, `sparklanes.errors.CacheError` will be thrown).
[ "Assigns", "an", "attribute", "reference", "to", "all", "subsequent", "tasks", ".", "For", "example", "if", "a", "task", "caches", "a", "DataFrame", "df", "using", "self", ".", "cache", "(", "some_df", "df", ")", "all", "tasks", "that", "follow", "can", ...
python
train
rocky/python3-trepan
trepan/processor/parse/scanner.py
https://github.com/rocky/python3-trepan/blob/14e91bc0acce090d67be145b1ac040cab92ac5f3/trepan/processor/parse/scanner.py#L81-L86
def t_single_quote_file(self, s): r"'[^'].+'" # Pick out text inside of singe-quoted string base = s[1:-1] self.add_token('FILENAME', base) self.pos += len(s)
[ "def", "t_single_quote_file", "(", "self", ",", "s", ")", ":", "# Pick out text inside of singe-quoted string", "base", "=", "s", "[", "1", ":", "-", "1", "]", "self", ".", "add_token", "(", "'FILENAME'", ",", "base", ")", "self", ".", "pos", "+=", "len", ...
r"'[^'].+
[ "r", "[", "^", "]", ".", "+" ]
python
test
nugget/python-insteonplm
insteonplm/tools.py
https://github.com/nugget/python-insteonplm/blob/65548041f1b0729ae1ae904443dd81b0c6cbf1bf/insteonplm/tools.py#L905-L927
def do_help(self, arg): """Help command. Usage: help [command] Parameters: command: Optional - command name to display detailed help """ cmds = arg.split() if cmds: func = getattr(self, 'do_{}'.format(cmds[0])) if func: _LOGGING.info(func.__doc__) else: _LOGGING.error('Command %s not found', cmds[0]) else: _LOGGING.info("Available command list: ") for curr_cmd in dir(self.__class__): if curr_cmd.startswith("do_") and not curr_cmd == 'do_test': print(" - ", curr_cmd[3:]) _LOGGING.info("For help with a command type `help command`")
[ "def", "do_help", "(", "self", ",", "arg", ")", ":", "cmds", "=", "arg", ".", "split", "(", ")", "if", "cmds", ":", "func", "=", "getattr", "(", "self", ",", "'do_{}'", ".", "format", "(", "cmds", "[", "0", "]", ")", ")", "if", "func", ":", "...
Help command. Usage: help [command] Parameters: command: Optional - command name to display detailed help
[ "Help", "command", "." ]
python
train
AtteqCom/zsl
src/zsl/router/task.py
https://github.com/AtteqCom/zsl/blob/ab51a96da1780ff642912396d4b85bdcb72560c1/src/zsl/router/task.py#L238-L247
def _create_result(self, cls): # type:(Callable)->Tuple[Any, Callable] """ Create the task using the injector initialization. :param cls: :return: """ task = instantiate(cls) logging.getLogger(__name__).debug("Task object {0} created [{1}].".format(cls.__name__, task)) return task, get_callable(task)
[ "def", "_create_result", "(", "self", ",", "cls", ")", ":", "# type:(Callable)->Tuple[Any, Callable]", "task", "=", "instantiate", "(", "cls", ")", "logging", ".", "getLogger", "(", "__name__", ")", ".", "debug", "(", "\"Task object {0} created [{1}].\"", ".", "fo...
Create the task using the injector initialization. :param cls: :return:
[ "Create", "the", "task", "using", "the", "injector", "initialization", ".", ":", "param", "cls", ":", ":", "return", ":" ]
python
train
reingart/pyafipws
wsremcarne.py
https://github.com/reingart/pyafipws/blob/ee87cfe4ac12285ab431df5fec257f103042d1ab/wsremcarne.py#L143-L148
def __analizar_evento(self, ret): "Comprueba y extrae el wvento informativo si existen en la respuesta XML" evt = ret.get('evento') if evt: self.Eventos = [evt] self.Evento = "%(codigo)s: %(descripcion)s" % evt
[ "def", "__analizar_evento", "(", "self", ",", "ret", ")", ":", "evt", "=", "ret", ".", "get", "(", "'evento'", ")", "if", "evt", ":", "self", ".", "Eventos", "=", "[", "evt", "]", "self", ".", "Evento", "=", "\"%(codigo)s: %(descripcion)s\"", "%", "evt...
Comprueba y extrae el wvento informativo si existen en la respuesta XML
[ "Comprueba", "y", "extrae", "el", "wvento", "informativo", "si", "existen", "en", "la", "respuesta", "XML" ]
python
train
NuGrid/NuGridPy
nugridpy/utils.py
https://github.com/NuGrid/NuGridPy/blob/eee8047446e398be77362d82c1d8b3310054fab0/nugridpy/utils.py#L1512-L1919
def stable_specie(): ''' provide the list of stable species, and decay path feeding stables ''' #import numpy as np stable_raw=[] stable_raw = ['H 1', 'H 2',\ 'HE 3', 'HE 4',\ 'LI 6', 'LI 7',\ 'BE 9',\ 'B 10', 'B 11',\ 'C 12', 'C 13',\ 'N 14', 'N 15',\ 'O 16', 'O 17', 'O 18',\ 'F 19',\ 'NE 20', 'NE 21', 'NE 22',\ 'NA 23',\ 'MG 24', 'MG 25', 'MG 26',\ 'AL 27',\ 'SI 28', 'SI 29', 'SI 30',\ 'P 31',\ 'S 32', 'S 33', 'S 34', 'S 36',\ 'CL 35', 'CL 37',\ 'AR 36', 'AR 38', 'AR 40',\ 'K 39', 'K 40', 'K 41',\ 'CA 40', 'CA 42', 'CA 43', 'CA 44', 'CA 46', 'CA 48',\ 'SC 45',\ 'TI 46', 'TI 47', 'TI 48', 'TI 49', 'TI 50',\ 'V 50', 'V 51',\ 'CR 50', 'CR 52', 'CR 53', 'CR 54',\ 'MN 55',\ 'FE 54', 'FE 56', 'FE 57', 'FE 58',\ 'CO 59',\ 'NI 58', 'NI 60', 'NI 61', 'NI 62', 'NI 64',\ 'CU 63', 'CU 65',\ 'ZN 64', 'ZN 66', 'ZN 67', 'ZN 68', 'ZN 70',\ 'GA 69', 'GA 71',\ 'GE 70', 'GE 72', 'GE 73', 'GE 74', 'GE 76',\ 'AS 75',\ 'SE 74', 'SE 76', 'SE 77', 'SE 78', 'SE 80', 'SE 82',\ 'BR 79', 'BR 81',\ 'KR 78', 'KR 80', 'KR 82', 'KR 83', 'KR 84', 'KR 86',\ 'RB 85', 'RB 87',\ 'SR 84', 'SR 86', 'SR 87', 'SR 88',\ 'Y 89',\ 'ZR 90', 'ZR 91', 'ZR 92', 'ZR 94', 'ZR 96',\ 'NB 93',\ 'MO 92', 'MO 94', 'MO 95', 'MO 96', 'MO 97', 'MO 98', 'MO100',\ 'RU 96', 'RU 98', 'RU 99', 'RU100', 'RU101', 'RU102', 'RU104',\ 'RH103',\ 'PD102', 'PD104', 'PD105', 'PD106', 'PD108', 'PD110',\ 'AG107', 'AG109',\ 'CD106', 'CD108', 'CD110', 'CD111', 'CD112', 'CD113', 'CD114', 'CD116',\ 'IN113', 'IN115',\ 'SN112', 'SN114', 'SN115', 'SN116', 'SN117', 'SN118', 'SN119', 'SN120', 'SN122', 'SN124',\ 'SB121', 'SB123',\ 'TE120', 'TE122', 'TE123', 'TE124', 'TE125', 'TE126', 'TE128', 'TE130',\ 'I 127',\ 'XE124', 'XE126', 'XE128', 'XE129', 'XE130', 'XE131', 'XE132', 'XE134', 'XE136',\ 'CS133',\ 'BA130', 'BA132', 'BA134', 'BA135', 'BA136', 'BA137', 'BA138',\ 'LA138', 'LA139',\ 'CE136', 'CE138', 'CE140', 'CE142',\ 'PR141',\ 'ND142', 'ND143', 'ND144', 'ND145', 'ND146', 'ND148', 'ND150',\ 'SM144', 'SM147', 'SM148', 'SM149', 'SM150', 'SM152', 'SM154',\ 'EU151', 'EU153',\ 'GD152', 'GD154', 'GD155', 'GD156', 'GD157', 'GD158', 'GD160',\ 'TB159',\ 'DY156', 'DY158', 'DY160', 'DY161', 'DY162', 'DY163', 'DY164',\ 'HO165',\ 'ER162', 'ER164', 'ER166', 'ER167', 'ER168', 'ER170',\ 'TM169',\ 'YB168', 'YB170', 'YB171', 'YB172', 'YB173', 'YB174', 'YB176',\ 'LU175', 'LU176',\ 'HF174', 'HF176', 'HF177', 'HF178', 'HF179', 'HF180',\ 'TA180', 'TA181',\ 'W 180', 'W 182', 'W 183', 'W 184', 'W 186',\ 'RE185', 'RE187',\ 'OS184', 'OS186', 'OS187', 'OS188', 'OS189', 'OS190', 'OS192',\ 'IR191', 'IR193',\ 'PT190', 'PT192', 'PT194', 'PT195', 'PT196', 'PT198',\ 'AU197',\ 'HG196', 'HG198', 'HG199', 'HG200', 'HG201', 'HG202', 'HG204',\ 'TL203', 'TL205',\ 'PB204', 'PB206', 'PB207', 'PB208',\ 'BI209',\ 'TH232',\ 'U 235','U 238'] jj=-1 global count_size_stable count_size_stable=[] global stable stable=[] global jdum jdum=np.zeros(len(stable_raw)) global jjdum jjdum=np.zeros(len(spe)) for i in range(len(stable_raw)): dum_str = stable_raw[i] for j in range(len(spe)): if stable_raw[i].capitalize() == spe[j]: stable.append(stable_raw[i]) jdum[i]=1 jjdum[j]=1 jj=jj+1 count_size_stable.append(int(jj)) #print stable # back_ind is an index to go back, to use the order of stable # useful for example for decayed yields. global back_ind back_ind={} for a,b in zip(stable,count_size_stable): back_ind[a]=b #print 'in stable:',back_ind['SE 74'] # definition of decay paths global decay_raw decay_raw=[] decay_raw=[['H 1'],\ ['H 2'],\ ['HE 3'],\ ['HE 4','B 8'],\ ['LI 6'],\ ['LI 7','BE 7'],\ ['BE 9'],\ ['B 10','BE 10'],\ ['B 11','C 11','BE 11'],\ ['C 12'],\ ['C 13','N 13','O 13'],\ ['N 14','C 14','O 14'],\ ['N 15','C 15','O 15','F 15'],\ ['O 16'],\ ['O 17','F 17'],\ ['O 18','F 18','NE 18'],\ ['F 19','O 19','NE 19'],\ ['NE 20','F 20','NA 20'],\ ['NE 21','F 21','NA 21'],\ ['NE 22','NA 22','MG 22','F 22'],\ ['NA 23','MG 23','NE 23'],\ ['MG 24','AL 24','NA 24','NE 24',],\ ['MG 25','NA 25','AL 25'],\ ['MG 26','SI 26','AL 26','NA 26','AL*26'],\ ['AL 27','SI 27','MG 27'],\ ['SI 28','AL 28','MG 28'],\ ['SI 29','P 29','AL 29','MG 29'],\ ['SI 30','S 30','P 30','AL 30','MG 30'],\ ['P 31','S 31','SI 31'],\ ['S 32','P 32','SI 32'],\ ['S 33','CL 33','P 33','SI 33'],\ ['S 34','CL 34','P 34'],\ ['S 36','P 36'],\ ['CL 35','S 35','AR 35'],\ ['CL 37','S 37','P 37','AR 37','K 37'],\ ['AR 36','CL 36'],\ ['AR 38','CL 38','S 38','P 38','K 38'],\ ['AR 40','CL 40','S 40'],\ ['K 39','AR 39','CL 39','S 39','CA 39'],\ ['K 40'],\ ['K 41','AR 41','CL 41','S 41','CA 41','SC 41'],\ ['CA 40','SC 40'],\ ['CA 42','K 42','AR 42','CL 42','S 42','SC 42','TI 42'],\ ['CA 43','K 43','AR 43','CL 43','SC 43','TI 43','V 43'],\ ['CA 44','K 44','AR 44','CL 44','SC 44','TI 44'],\ ['CA 46','K 46','AR 46'],\ ['CA 48','K 48','AR 48'],\ ['SC 45','CA 45','K 45','AR 45','CL 45','TI 45','V 45'],\ ['TI 46','SC 46','V 46','CR 46'],\ ['TI 47','SC 47','CA 47','K 47','AR 47','V 47','CR 47'],\ ['TI 48','SC 48','V 48','CR 48'],\ ['TI 49','SC 49','CA 49','K 49','V 49','CR 49','MN 49'],\ ['TI 50','SC 50','CA 50','K 50'],\ ['V 50'],\ ['V 51','CR 51','TI 51','SC 51','CA 51','MN 51'],\ ['CR 50','MN 50'],\ ['CR 52','MN 52','FE 52','V 52','TI 52','SC 52','CA 52'],\ ['CR 53','MN 53','FE 53','V 53','TI 53','SC 53'],\ ['CR 54','MN 54','V 54','TI 54','SC 54'],\ ['MN 55','FE 55','CR 55','V 55','TI 55','CO 55'],\ ['FE 54','CO 54'],\ ['FE 56','NI 56','CO 56','MN 56','CR 56'],\ ['FE 57','NI 57','CO 57','MN 57','CR 57'],\ ['FE 58','CO 58','MN 58','CR 58'],\ ['CO 59','FE 59','MN 59','CR 59','NI 59','CU 59'],\ ['NI 58','CU 58'],\ ['NI 60','CO 60','FE 60','MN 60','CR 60','CU 60','ZN 60'],\ ['NI 61','CO 61','FE 61','MN 61','CU 61','ZN 61'],\ ['NI 62','CO 62','FE 62','CU 62','ZN 62'],\ ['NI 64','CO 64','FE 64','CU 64'],\ ['CU 63','NI 63','CO 63','FE 63','MN 63','ZN 63','GA 63'],\ ['CU 65','NI 65','CO 65','FE 65','ZN 65','GA 65','GE 65'],\ ['ZN 64','CU 64','GA 64','GE 64'],\ ['ZN 66','CU 66','NI 66','CO 66','FE 66','GA 66','GE 66'],\ ['ZN 67','CU 67','NI 67','CO 67','FE 67','GA 67','GE 67','AS 77'],\ ['ZN 68','NI 68','CO 68','GA 68','GE 68','CU 68','AS 68','SE 68'],\ ['ZN 70','CU 70','NI 70','CO 70'],\ ['GA 69','ZN 69','CU 69','NI 69','GE 69','AS 69','SE 69'],\ ['GA 71','ZN 71','CU 71','NI 71','GE 71','AS 71','SE 71','BR 71'],\ ['GE 70','GA 70','AS 70','SE 70','BR 70'],\ ['GE 72','GA 72','ZN 72','CU 72','NI 72','AS 72','SE 72','BR 72','KR 72'],\ ['GE 73','GA 73','ZN 73','CU 73','NI 73','AS 73','SE 73','BR 73','KR 73'],\ ['GE 74','GA 74','ZN 74','CU 74','NI 74','AS 74'],\ ['GE 76','GA 76','ZN 76','CU 76'],\ ['AS 75','GE 75','GA 75','ZN 75','CU 75','SE 75','BR 75','KR 75','RB 75'],\ ['SE 74','AS 74','BR 74','KR 74'],\ ['SE 76','AS 76','BR 76','KR 76','RB 76','SR 76'],\ ['SE 77','AS 77','GE 77','BR 77','GA 77','ZN 77','KR 77','RB 77','SR 77'],\ ['SE 78','AS 78','GE 78','GA 78','ZN 78','BR 78'],\ ['SE 80','AS 80','GE 80','GA 80','ZN 80'],\ ['SE 82','AS 82','GE 82','GA 82'],\ ['BR 79','SE 79','AS 79','GE 79','GA 79','ZN 79','KR 79','RB 79','SR 79','Y 79'],\ ['BR 81','SE 81','KR 81','AS 81','GE 81','GA 81','RB 81','SR 81','Y 81','ZR 81'],\ ['KR 78','RB 78','SR 78','Y 78'],\ ['KR 80','BR 80','RB 80','SR 80','ZR 80'],\ ['KR 82','BR 82','RB 82','SR 82','Y 82','ZR 82'],\ ['KR 83','BR 83','SE 83','AS 83','GE 83','RB 83','SR 83','Y 83','ZR 83','NB 83'],\ ['KR 84','BR 84','SE 84','AS 84','GE 84','RB 84'],\ ['KR 86','BR 86','SE 86','AS 86'],\ ['RB 85','KR 85','SR 85','KR*85','BR 85','SE 85','AS 85','Y 85','ZR 85','NB 85','MO 85'],\ ['RB 87','KR 87','BR 87','SE 87','AS 87'],\ ['SR 84','Y 84','ZR 84','NB 84','MO 84'],\ ['SR 86','RB 86','Y 86','ZR 86','NB 86','MO 86'],\ ['SR 87','Y 87','ZR 87','NB 87','MO 87','TC 87'],\ ['SR 88','RB 88','KR 88','BR 88','SE 88','Y 88','ZR 88','NB 88','MO 88','TC 88'],\ ['Y 89','SR 89','RB 89','KR 89','BR 89','ZR 89','NB 89','MO 89','TC 89','RU 89'],\ ['ZR 90','Y 90','SR 90','RB 90','KR 90','BR 90','NB 90','MO 90','TC 90','RU 90'],\ ['ZR 91','Y 91','SR 91','RB 91','KR 91','BR 91','SE 91','NB 91','MO 91','TC 91','RU 91','RH 91'],\ ['ZR 92','Y 92','SR 92','RB 92','KR 92','BR 92','NB 92'],\ ['ZR 94','Y 94','SR 94','RB 94','KR 94'],\ ['ZR 96','Y 96','SR 96'],\ ['NB 93','ZR 93','Y 93','SR 93','RB 93','KR 93','MO 93','TC 93','RU 93','RH 93','PD 93'],\ ['MO 92','TC 92','RU 92','RH 92','PD 92'],\ ['MO 94','NB 94','TC 94','RU 94','RH 94','PD 94'],\ ['MO 95','NB 95','ZR 95','Y 95','SR 95','TC 95','RU 95','RH 95','PD 95','AG 95'],\ ['MO 96','NB 96','TC 96'],\ ['MO 97','NB 97','ZR 97','Y 97','SR 97','TC 97','RU 97','RH 97','PD 97','AG 97','CD 97'],\ ['MO 98','NB 98','ZR 98','Y 98','SR 98'],\ ['MO100','NB100','ZR100','Y 100'],\ ['RU 96','RH 96','PD 96','AG 96'],\ ['RU 98','TC 98','RH 98','PD 98','AG 98','CD 98'],\ ['RU 99','TC 99','MO 99','NB 99','ZR 99','Y 99','RH 99','PD 99','AG 99','CD 99','IN 99'],\ ['RU100','TC100','RH100','PD100','AG100','CD100','IN100','SN100'],\ ['RU101','TC101','MO101','NB101','ZR101','Y 101','RH101','PD101','AG101','CD101','IN101','SN101'],\ ['RU102','MO102','TC102','NB102','ZR102','Y 102','RH102'],\ ['RU104','TC104','MO104','NB104'],\ ['RH103','RU103','TC103','MO103','NB103','ZR103','Y 103','PD103','AG103','CD103','IN103','SN103'],\ ['PD102','AG102','CD102','IN102','SN102'],\ ['PD104','RH104','AG104','CD104','IN104','SN104','SB104'],\ ['PD105','RH105','RU105','TC105','MO105','NB105','ZR105','AG105','CD105','IN105','SN105','SB105'],\ ['PD106','RH106','RU106','TC106','MO106','NB106','AG106'],\ ['PD108','RH108','RU108','TC108','MO108','NB108'],\ ['PD110','RH110','RU110','TC110','MO110','NB110'],\ ['AG107','PD107','RH107','RU107','TC107','MO107','CD107','IN107','SN107','SB107'],\ ['AG109','PD109','RH109','RU109','TC109','MO109','NB109','CD109','IN109','SN109','SB109','TE109'],\ ['CD106','IN106','SN106','SB106'],\ ['CD108','AG108','IN108','SN108','SB108'],\ ['CD110','AG110','IN110','SN110','SB110','TE110'],\ ['CD111','AG111','PD111','RH111','RU111','TC111','IN111','SN111','SB111','TE111','I 111'],\ ['CD112','AG112','PD112','RH112','RU112','TC112'],\ ['CD113','AG113','PD113','RH113','RU113'],\ ['CD114','AG114','PD114','RH114','RU114'],\ ['CD116','AG116','PD116','RH116'],\ ['IN113','SN113','SB113','TE113','I 113','XE113'],\ ['IN115','CD115','AG115','PD115','RH115','RU115'],\ ['SN112','IN112','SB112','TE112','I 112','XE112'],\ ['SN114','IN114','SB114','TE114','I 114','XE114','CS114'],\ ['SN115','SB115','TE115','I 115','XE115','CS115','BA115'],\ ['SN116','IN116','SB116','TE116','I 116','XE116','CS116','BA116'],\ ['SN117','IN117','AG117','PD117','RH117','SB117','CD117','TE117','I 117','XE117','CS117','BA117'],\ ['SN118','IN118','CD118','AG118','PD118','SB118','TE118','XE118','CS118','BA118'],\ ['SN119','IN119','CD119','AG119','PD119','SB119','TE119','XE119','CS119','BA119'],\ ['SN120','SB120','IN120','CD120','AG120','PD120'],\ ['SN122','IN122','CD122','AG122'],\ ['SN124','IN124','CD124'],\ ['SB121','SN121','IN121','CD121','AG121','TE121','I 121','XE121','CS121','XE121','CS121','BA121','LA121','CE121'], ['SB123','SN123','IN123','CD123','AG123'],\ ['TE120','I 120','XE120','CS120','BA120','LA120'],\ ['TE122','SB122','I 122','XE122','CS122','BA122','LA122'],\ ['TE123','I 123','XE123','CS123','BA123','LA123','CE123'],\ ['TE124','SB124','I 124'],\ ['TE125','SB125','SN125','IN125','CD125','I 125','XE125','CS125','BA125','LA125','CE125','PR125'],\ ['TE126','SB126','SN126','IN126','CD126'],\ ['TE128','SB128','SN128','IN128','CD128'],\ ['TE130','SB130','SN130','IN130'],\ ['I 127','TE127','SB127','SN127','IN127','CD127','XE127','CS127','BA127','LA127','CE127','PR127','ND127'],\ ['XE124','CS124','BA124','LA124','CE124','PR124'],\ ['XE126','I 126','CS126','BA126','LA126','CE126','PR126'],\ ['XE128','I 128','CS128','BA128','LA128','CE128','PR128'],\ ['XE129','I 129','TE129','SB129','SN129','IN129','CD129','CS129','BA129','LA129','CE129','PR129','ND129'],\ ['XE130','I 130','CS130'],\ ['XE131','I 131','TE131','SB131','SN131','IN131','CS131','BA131','LA131','CE131','PR131','ND131','PM131','SM131'],\ ['XE132','I 132','TE132','SB132','SN132','IN132','CS132'], ['XE134','I 134','TE134','SB134','SN134'],\ ['XE136','I 136','TE136','SB136'],\ ['CS133','XE133','I 133','TE133','SB133','SN133','BA133','LA133','CE133','PR133','ND133','PM133','SM133'],\ ['BA130','LA130','CE130','PR130','ND130','PM130'],\ ['BA132','LA132','CE132','PR132','ND132','PM132','SM132'],\ ['BA134','CS134','LA134','CE134','PR134','ND134','PM134','SM134','EU134'],\ ['BA135','CS135','XE135','I 135','TE135','SB135','SN135','LA135','CE135','PR135','ND135','PM135','SM135','EU135','GD135'],\ ['BA136','CS136','LA136'],\ ['BA137','CS137','XE137','I 137','TE137','SB137','LA137','CE137','PR137','ND137','PM137','SM137','EU137','GD137'],\ ['BA138','CS138','XE138','I 138','TE138'],\ ['LA138'],\ ['LA139','BA139','CS139','XE139','I 139','CE139','PR139','ND139','PM139','SM139','EU139','GD139','TB139','DY139'],\ ['CE136','PR136','ND136','PM136','SM136','EU136'],\ ['CE138','PR138','ND138','PM138','SM138','EU138','GD138'],\ ['CE140','LA140','BA140','CS140','XE140','I 140','PR140','ND140','PM140','SM140','EU140','GD140','TB140'],\ ['CE142','LA142','BA142','CS142','XE142','I 142'],\ ['PR141','CE141','LA141','BA141','CS141','XE141','I 141','ND141','PM141','SM141','EU141','GD141','TB141','DY141'],\ ['ND142','PR142','PM142','SM142','EU142','GD142','TB142','DY142','HO142','SM146','EU146','GD146','TB146','DY146','HO146','ER146',\ 'GD150','TB150','DY150','HO150','ER150','DY154','HO154','ER154'],\ ['ND143','PR143','CE143','LA143','BA143','CS143','XE143','PM143','SM143','EU143','GD143','TB143','DY143'],\ ['ND144','PR144','CE144','LA144','BA144','CS144','XE144','PM144'],\ ['ND145','PR145','CE145','LA145','BA145','CS145','PM145','SM145','EU145','GD145','TB145','DY145','HO145','ER145'],\ ['ND146','PR146','CE146','LA146','BA146','CS146','PM146'],\ ['ND148','PR148','CE148','LA148','BA148'],\ ['ND150','PR150','CE150','LA150','BA150'],\ ['SM144','EU144','GD144','TB144','DY144','HO144','GD148','TB148','DY148','HO148','ER148','TM148'],\ ['SM147','PM147','ND147','PR147','CE147','LA147','BA147','EU147','GD147','TB147','DY147','HO147','ER147'],\ ['SM148','PM148','EU148'],\ ['SM149','PM149','ND149','PR149','CE149','LA149','EU149','GD149','TB149','DY149','HO149','ER149','TM149','YB149'],\ ['SM150','PM150','EU150'],\ ['SM152','PM152','ND152','PR152','CE152','EU152'],\ ['SM154','PM154','ND154','PR154'],\ ['EU151','SM151','PM151','ND151','PR151','CE151','GD151','TB151'],\ ['EU153','SM153','PM153','GD153','PR153','GD153','TB153','DY153','HO153'],\ ['GD152','TB152','DY152','HO152'],\ ['GD154','EU154','TB154'],\ ['GD155','EU155','SM155','PM155','ND155','TB155','DY155','HO155','ER155','TM155'],\ ['GD156','EU156','SM156','PM156','ND156','TB156'],\ ['GD157','EU157','SM157','PM157','TB157','DY157','HO157','ER157','TM157','YB157'],\ ['GD158','EU158','SM158','PM158','TB158'],\ ['GD160','EU160','SM160'],\ ['TB159','GD159','EU159','SM159','PM159','DY159','HO159','ER159','TM159','YB159','LU159'],\ ['DY156','HO156','ER156','TM156','YB156','HO156','ER156','TM156','YB156'],\ ['DY158','HO158','ER158','TM158','YB158','LU158'],\ ['DY160','TB160','HO160','ER160','TM160','YB160','LU160','HF160'],\ ['DY161','TB161','GD161','EU161','SM161','PM161','ND161','HO161','ER161','TM161','YB161','LU161','HF161','TA161'],\ ['DY162','TB162','GD162','EU162','SM162','PM162','HO162'],\ ['DY163','TB163','HO163','GD163','EU163','SM163','PM163','ND163','ER163','TM163','YB163','LU163','HF163','TA163'],\ ['DY164','TB164','HO164','GD164','EU164','SM164','PM164','ND164','HO164'],\ ['HO165','DY165','ER165','TB165','GD165','EU165','SM165','PM165','HO165','TM165','YB165','LU165','HF165','TA165','W 165'],\ ['ER162','TM162','YB162','LU162','HF162','TA162'],\ ['ER164','TM164','YB164','LU164','HF164','TA164','W 164'],\ ['ER166','HO166','DY166','TB166','GD166','EU166','SM166','PM166','ND166','TM166','YB166','LU166','HF166','TA166','W 166','RE166'],\ ['ER167','HO167','DY167','TB167','GD167','EU167','SM167','PM167','ND167','TM167','YB167','LU167','HF167','TA167','W 167','RE167'],\ ['ER168','HO168','DY168','TB168','GD168','EU168','SM168','PM168','ND168','TM168'],\ ['ER170','HO170','DY170','TB170','GD170','EU170','SM170','PM170','ND170'],\ ['TM169','ER169','HO169','DY169','TB169','GD169','EU169','SM169','PM169','ND169','YB169','LU169','HF169','TA169','W 169','RE169'],\ ['YB168','LU168','HF168','TA168','W 168','RE168'],\ ['YB170','TM170','LU170','HF170','TA170','W 170','RE170','OS170'],\ ['YB171','TM171','ER171','HO171','DY171','TB171','GD171','EU171','SM171','PM171','ND171','LU171','HF171','TA171','W 171','RE171','OS171'],\ ['YB172','TM172','ER172','HO172','DY172','TB172','GD172','EU172','SM172','PM172','ND172','LU172','HF172','TA172','W 172','RE172','OS172','IR172'],\ ['YB173','TM173','ER173','HO173','DY173','TB173','GD173','EU173','SM173','PM173','ND173','LU173','HF173','TA173','W 173','RE173','OS173','IR173'],\ ['YB174','TM174','ER174','HO174','DY174','TB174','GD174','EU174','SM174','PM174','ND174','LU174'],\ ['YB176','TM176','ER176','HO176','DY176','TB176','GD176','EU176','SM176','PM176','ND176'],\ ['LU175','YB175','TM175','ER175','HO175','DY175','TB175','GD175','EU175','SM175','PM175','ND175','HF175','TA175','W 175','RE175','OS175','IR175'],\ ['LU176','HF176','TA176','W 176','RE176','OS176','IR176'],\ ['HF174','TA174','W 174','RE174','OS174','IR174'],\ ['HF176','TA176','W 176','RE176','OS176','IR176'],\ ['HF177','LU177','YB177','LU177','YB177','TM177','ER177','HO177','DY177','TB177','GD177','TA177','W 177','RE177','OS177','IR177'],\ ['HF178','LU178','YB178','LU178','YB178','TM178','ER178','HO178','DY178','TB178','GD178','TA178','W 178','RE178','OS178','IR178'],\ ['HF179','LU179','YB179','LU179','YB179','TM179','ER179','HO179','DY179','TB179','GD179','TA179','W 179','RE179','OS179','IR179','PT179'],\ ['HF180','LU180','YB180','LU180','YB180','TM180','ER180','HO180','DY180','TB180','GD180','TA180','W 180','RE180','OS180','IR180','PT180','AU180'],\ ['TA180'],\ ['TA181','HF181','LU181','YB181','LU181','YB181','TM181','ER181','HO181','DY181','TB181','GD181','W 181','RE181','OS181','IR181','PT181','AU181'],\ ['W 180','RE180','OS180','IR180','PT180','AU180'],\ ['W 182','TA182','HF182','LU182','YB182','LU182','YB182','TM182','ER182','HO182','DY182','TB182','GD182','RE182','OS182','IR182','PT182','AU182'],\ ['W 183','TA183','HF183','LU183','YB183','LU183','YB183','TM183','ER183','HO183','DY183','TB183','GD183','RE183','OS183','IR183','PT183','AU183'],\ ['W 184','TA184','HF184','LU184','YB184','LU184','YB184','TM184','ER184','HO184','DY184','TB184','GD184','RE184'],\ ['W 186','TA186','HF186','LU186','YB186','LU186','YB186','TM186','ER186','HO186','DY186','TB186','GD186'],\ ['RE185','W 185','TA185','HF185','LU185','YB185','LU185','YB185','TM185','ER185','HO185','DY185','TB185','GD185','OS185','IR185','PT185','AU185','HG185','TL185'],\ ['RE187','W 187','TA187','HF187','LU187','YB187','LU187','YB187','TM187','ER187','HO187','DY187','TB187','GD187'],\ ['OS184','IR184','PT184','AU184','HG184','TL184'],\ ['OS186','RE186','IR186','PT186','AU186','HG186','TL186'],\ ['OS187','IR187','PT187','AU187','HG187','TL187','PB187'],\ ['OS188','RE188','W 188','TA188','HF188','LU188','YB188','LU188','YB188','TM188','ER188','HO188','DY188','TB188','GD188','IR188','PT188','AU188','HG188','TL188','PB188'],\ ['OS189','RE189','W 189','TA189','HF189','LU189','YB189','LU189','YB189','TM189','ER189','HO189','DY189','TB189','GD189','IR189','PT189','AU189','HG189','TL189','PB189'],\ ['OS190','RE190','W 190','TA190','HF190','LU190','YB190','LU190','YB190','TM190','ER190','HO190','DY190','TB190','GD190','IR190'],\ ['OS192','RE190','W 192','TA192','HF192','LU192','YB192','LU192','YB192','TM192','ER192','HO192','DY192','TB192','GD192'],\ ['IR191','OS191','RE191','W 191','TA191','HF191','LU191','YB191','LU191','YB191','TM191','ER191','HO191','DY191','TB191','GD191','PT191','AU191','HG191','TL191','PB191'],\ ['IR193','OS193','RE193','W 193','TA193','HF193','LU193','YB193','LU193','YB193','TM193','ER193','HO193','DY193','TB193','GD193','PT193','AU193','HG193','TL193','PB193'],\ ['PT190','AU190','HG190','TL190','PB190'],\ ['PT192','IR192','AU192','HG192','TL192','PB192'],\ ['PT194','IR194','OS194','RE194','W 194','TA194','HF194','AU194','HG194','TL194','PB194','BI194'], ['PT195','IR195','OS195','RE195','W 195','TA195','HF195','AU195','HG195','TL195','PB195','BI195'],\ ['PT196','IR196','OS196','RE196','W 196','TA196','HF196','AU196'],\ ['PT198','IR198','OS198','RE198','W 198','TA198','HF198'],\ ['AU197','PT197','IR197','OS197','RE197','W 197','TA197','HF197','HG197','TL197','PB197','BI197'],\ ['HG196','TL196','PB196','BI196'],\ ['HG198','AU198','TL198','PB198','BI198'],\ ['HG199','AU199','PT199','IR199','OS199','RE199','W 199','TA199','HF199','TL199','PB199','BI199'],\ ['HG200','AU200','PT200','IR200','OS200','RE200','W 200','TA200','HF200','TL200','PB200','BI200'],\ ['HG201','AU201','PT201','IR201','OS201','RE201','W 201','TA201','HF201','TL201','PB201','BI201','PO201'],\ ['HG202','AU202','PT202','IR202','OS202','RE202','W 202','TA202','HF202','TL202','PB202','BI202','PO202'],\ ['HG204','AU204','PT204','IR204','OS204','RE204','W 204','TA204','HF204'],\ ['TL203','HG203','AU203','PT203','IR203','OS203','RE203','W 203','TA203','HF203','PB203','BI203','PO203'],\ ['TL205','HG205','AU205','PT205','IR205','OS205','RE205','W 205','TA205','HF205','PB205','BI205','PO205'],\ ['PB204','TL204','BI204','PO204'],\ ['PB206','TL206','HG206','AU206','PT206','IR206','OS206','RE206','W 206','TA206','HF206','BI206','PO210'],\ ['PB207','TL207','HG207','AU207','PT207','IR207','OS207','RE207','W 207','TA207','HF207','BI207','PO211','BI211'],\ ['PB208','TL208','HG208','AU208','PT208','IR208','OS208','RE208','W 208','TA208','HF208','BI208','PO212','BI212'],\ ['BI209','PB209','TL209','HG209','AU209','PT209','IR209','OS209','RE209','W 209','TA209','HF209'],\ ['TH232','AC232','RA232','FR232','RN232'],\ ['U 235','PA235','TH235','AC235','RA235','FR235','RN235'],\ ['U 238','PA238','TH238','AC238','RA238','FR238','RN238']]
[ "def", "stable_specie", "(", ")", ":", "#import numpy as np", "stable_raw", "=", "[", "]", "stable_raw", "=", "[", "'H 1'", ",", "'H 2'", ",", "'HE 3'", ",", "'HE 4'", ",", "'LI 6'", ",", "'LI 7'", ",", "'BE 9'", ",", "'B 10'", ",", "'B 11'", ",...
provide the list of stable species, and decay path feeding stables
[ "provide", "the", "list", "of", "stable", "species", "and", "decay", "path", "feeding", "stables" ]
python
train
DataDog/integrations-core
tokumx/datadog_checks/tokumx/vendor/pymongo/pool.py
https://github.com/DataDog/integrations-core/blob/ebd41c873cf9f97a8c51bf9459bc6a7536af8acd/tokumx/datadog_checks/tokumx/vendor/pymongo/pool.py#L431-L482
def command(self, dbname, spec, slave_ok=False, read_preference=ReadPreference.PRIMARY, codec_options=DEFAULT_CODEC_OPTIONS, check=True, allowable_errors=None, check_keys=False, read_concern=DEFAULT_READ_CONCERN, write_concern=None, parse_write_concern_error=False, collation=None): """Execute a command or raise ConnectionFailure or OperationFailure. :Parameters: - `dbname`: name of the database on which to run the command - `spec`: a command document as a dict, SON, or mapping object - `slave_ok`: whether to set the SlaveOkay wire protocol bit - `read_preference`: a read preference - `codec_options`: a CodecOptions instance - `check`: raise OperationFailure if there are errors - `allowable_errors`: errors to ignore if `check` is True - `check_keys`: if True, check `spec` for invalid keys - `read_concern`: The read concern for this command. - `write_concern`: The write concern for this command. - `parse_write_concern_error`: Whether to parse the ``writeConcernError`` field in the command response. - `collation`: The collation for this command. """ if self.max_wire_version < 4 and not read_concern.ok_for_legacy: raise ConfigurationError( 'read concern level of %s is not valid ' 'with a max wire version of %d.' % (read_concern.level, self.max_wire_version)) if not (write_concern is None or write_concern.acknowledged or collation is None): raise ConfigurationError( 'Collation is unsupported for unacknowledged writes.') if self.max_wire_version >= 5 and write_concern: spec['writeConcern'] = write_concern.document elif self.max_wire_version < 5 and collation is not None: raise ConfigurationError( 'Must be connected to MongoDB 3.4+ to use a collation.') try: return command(self.sock, dbname, spec, slave_ok, self.is_mongos, read_preference, codec_options, check, allowable_errors, self.address, check_keys, self.listeners, self.max_bson_size, read_concern, parse_write_concern_error=parse_write_concern_error, collation=collation) except OperationFailure: raise # Catch socket.error, KeyboardInterrupt, etc. and close ourselves. except BaseException as error: self._raise_connection_failure(error)
[ "def", "command", "(", "self", ",", "dbname", ",", "spec", ",", "slave_ok", "=", "False", ",", "read_preference", "=", "ReadPreference", ".", "PRIMARY", ",", "codec_options", "=", "DEFAULT_CODEC_OPTIONS", ",", "check", "=", "True", ",", "allowable_errors", "="...
Execute a command or raise ConnectionFailure or OperationFailure. :Parameters: - `dbname`: name of the database on which to run the command - `spec`: a command document as a dict, SON, or mapping object - `slave_ok`: whether to set the SlaveOkay wire protocol bit - `read_preference`: a read preference - `codec_options`: a CodecOptions instance - `check`: raise OperationFailure if there are errors - `allowable_errors`: errors to ignore if `check` is True - `check_keys`: if True, check `spec` for invalid keys - `read_concern`: The read concern for this command. - `write_concern`: The write concern for this command. - `parse_write_concern_error`: Whether to parse the ``writeConcernError`` field in the command response. - `collation`: The collation for this command.
[ "Execute", "a", "command", "or", "raise", "ConnectionFailure", "or", "OperationFailure", "." ]
python
train
erikrose/nose-progressive
noseprogressive/utils.py
https://github.com/erikrose/nose-progressive/blob/42853f11290cfaac8aa3d204714b71e27cc4ec07/noseprogressive/utils.py#L121-L132
def human_path(path, cwd): """Return the most human-readable representation of the given path. If an absolute path is given that's within the current directory, convert it to a relative path to shorten it. Otherwise, return the absolute path. """ # TODO: Canonicalize the path to remove /kitsune/../kitsune nonsense. path = abspath(path) if cwd and path.startswith(cwd): path = path[len(cwd) + 1:] # Make path relative. Remove leading slash. return path
[ "def", "human_path", "(", "path", ",", "cwd", ")", ":", "# TODO: Canonicalize the path to remove /kitsune/../kitsune nonsense.", "path", "=", "abspath", "(", "path", ")", "if", "cwd", "and", "path", ".", "startswith", "(", "cwd", ")", ":", "path", "=", "path", ...
Return the most human-readable representation of the given path. If an absolute path is given that's within the current directory, convert it to a relative path to shorten it. Otherwise, return the absolute path.
[ "Return", "the", "most", "human", "-", "readable", "representation", "of", "the", "given", "path", "." ]
python
train
log2timeline/dfvfs
dfvfs/lib/gzipfile.py
https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/lib/gzipfile.py#L270-L278
def GetCacheSize(self): """Determines the size of the uncompressed cached data. Returns: int: number of cached bytes. """ if not self._cache_start_offset or not self._cache_end_offset: return 0 return self._cache_end_offset - self._cache_start_offset
[ "def", "GetCacheSize", "(", "self", ")", ":", "if", "not", "self", ".", "_cache_start_offset", "or", "not", "self", ".", "_cache_end_offset", ":", "return", "0", "return", "self", ".", "_cache_end_offset", "-", "self", ".", "_cache_start_offset" ]
Determines the size of the uncompressed cached data. Returns: int: number of cached bytes.
[ "Determines", "the", "size", "of", "the", "uncompressed", "cached", "data", "." ]
python
train
AmesCornish/buttersink
buttersink/SSHStore.py
https://github.com/AmesCornish/buttersink/blob/5cc37e30d9f8071fcf3497dca8b8a91b910321ea/buttersink/SSHStore.py#L586-L589
def send(self, diffTo, diffFrom): """ Do a btrfs send. """ diff = self.toObj.diff(diffTo, diffFrom) self._open(self.butterStore.send(diff))
[ "def", "send", "(", "self", ",", "diffTo", ",", "diffFrom", ")", ":", "diff", "=", "self", ".", "toObj", ".", "diff", "(", "diffTo", ",", "diffFrom", ")", "self", ".", "_open", "(", "self", ".", "butterStore", ".", "send", "(", "diff", ")", ")" ]
Do a btrfs send.
[ "Do", "a", "btrfs", "send", "." ]
python
train
marrow/package
marrow/package/loader.py
https://github.com/marrow/package/blob/133d4bf67cc857d1b2423695938a00ff2dfa8af2/marrow/package/loader.py#L57-L104
def load(target:str, namespace:str=None, default=nodefault, executable:bool=False, separators:Sequence[str]=('.', ':'), protect:bool=True): """This helper function loads an object identified by a dotted-notation string. For example:: # Load class Foo from example.objects load('example.objects:Foo') # Load the result of the class method ``new`` of the Foo object load('example.objects:Foo.new', executable=True) If a plugin namespace is provided simple name references are allowed. For example:: # Load the plugin named 'routing' from the 'web.dispatch' namespace load('routing', 'web.dispatch') The ``executable``, ``protect``, and first tuple element of ``separators`` are passed to the traverse function. Providing a namespace does not prevent full object lookup (dot-colon notation) from working. """ assert check_argument_types() if namespace and ':' not in target: allowable = dict((i.name, i) for i in iter_entry_points(namespace)) if target not in allowable: raise LookupError('Unknown plugin "' + target + '"; found: ' + ', '.join(allowable)) return allowable[target].load() parts, _, target = target.partition(separators[1]) try: obj = __import__(parts) except ImportError: if default is not nodefault: return default raise return traverse( obj, separators[0].join(parts.split(separators[0])[1:] + target.split(separators[0])), default = default, executable = executable, protect = protect ) if target else obj
[ "def", "load", "(", "target", ":", "str", ",", "namespace", ":", "str", "=", "None", ",", "default", "=", "nodefault", ",", "executable", ":", "bool", "=", "False", ",", "separators", ":", "Sequence", "[", "str", "]", "=", "(", "'.'", ",", "':'", "...
This helper function loads an object identified by a dotted-notation string. For example:: # Load class Foo from example.objects load('example.objects:Foo') # Load the result of the class method ``new`` of the Foo object load('example.objects:Foo.new', executable=True) If a plugin namespace is provided simple name references are allowed. For example:: # Load the plugin named 'routing' from the 'web.dispatch' namespace load('routing', 'web.dispatch') The ``executable``, ``protect``, and first tuple element of ``separators`` are passed to the traverse function. Providing a namespace does not prevent full object lookup (dot-colon notation) from working.
[ "This", "helper", "function", "loads", "an", "object", "identified", "by", "a", "dotted", "-", "notation", "string", ".", "For", "example", "::", "#", "Load", "class", "Foo", "from", "example", ".", "objects", "load", "(", "example", ".", "objects", ":", ...
python
test
dschep/lambda-decorators
lambda_decorators.py
https://github.com/dschep/lambda-decorators/blob/9195914c8afe26843de9968d96dae6a89f061e8a/lambda_decorators.py#L492-L546
def json_schema_validator(request_schema=None, response_schema=None): """ Validate your request & response payloads against a JSONSchema. *NOTE: depends on the* `jsonschema <https://github.com/Julian/jsonschema>`_ *package. If you're using* `serverless-python-requirements <https://github.com/UnitedIncome/serverless-python-requirements>`_ *you're all set. If you cURLed* ``lambda_decorators.py`` *you'll have to install it manually in your service's root directory.* Usage:: >>> from jsonschema import ValidationError >>> from lambda_decorators import json_schema_validator >>> @json_schema_validator(request_schema={ ... 'type': 'object', 'properties': {'price': {'type': 'number'}}}) ... def handler(event, context): ... return event['price'] >>> handler({'price': 'bar'}, object()) {'statusCode': 400, 'body': "RequestValidationError: 'bar' is not of type 'number'"} >>> @json_schema_validator(response_schema={ ... 'type': 'object', 'properties': {'price': {'type': 'number'}}}) ... def handler(event, context): ... return {'price': 'bar'} >>> handler({}, object()) {'statusCode': 500, 'body': "ResponseValidationError: 'bar' is not of type 'number'"} """ def wrapper_wrapper(handler): @wraps(handler) def wrapper(event, context): if request_schema is not None: if jsonschema is None: logger.error('jsonschema is not installed, skipping request validation') else: try: jsonschema.validate(event, request_schema) except jsonschema.ValidationError as exception: return {'statusCode': 400, 'body': 'RequestValidationError: {}'.format( exception.message)} response = handler(event, context) if response_schema is not None: if jsonschema is None: logger.error('jsonschema is not installed, skipping response validation') else: try: jsonschema.validate(response, response_schema) except jsonschema.ValidationError as exception: return {'statusCode': 500, 'body': 'ResponseValidationError: {}'.format( exception.message)} return response return wrapper return wrapper_wrapper
[ "def", "json_schema_validator", "(", "request_schema", "=", "None", ",", "response_schema", "=", "None", ")", ":", "def", "wrapper_wrapper", "(", "handler", ")", ":", "@", "wraps", "(", "handler", ")", "def", "wrapper", "(", "event", ",", "context", ")", "...
Validate your request & response payloads against a JSONSchema. *NOTE: depends on the* `jsonschema <https://github.com/Julian/jsonschema>`_ *package. If you're using* `serverless-python-requirements <https://github.com/UnitedIncome/serverless-python-requirements>`_ *you're all set. If you cURLed* ``lambda_decorators.py`` *you'll have to install it manually in your service's root directory.* Usage:: >>> from jsonschema import ValidationError >>> from lambda_decorators import json_schema_validator >>> @json_schema_validator(request_schema={ ... 'type': 'object', 'properties': {'price': {'type': 'number'}}}) ... def handler(event, context): ... return event['price'] >>> handler({'price': 'bar'}, object()) {'statusCode': 400, 'body': "RequestValidationError: 'bar' is not of type 'number'"} >>> @json_schema_validator(response_schema={ ... 'type': 'object', 'properties': {'price': {'type': 'number'}}}) ... def handler(event, context): ... return {'price': 'bar'} >>> handler({}, object()) {'statusCode': 500, 'body': "ResponseValidationError: 'bar' is not of type 'number'"}
[ "Validate", "your", "request", "&", "response", "payloads", "against", "a", "JSONSchema", "." ]
python
train
ktbyers/netmiko
netmiko/_textfsm/_texttable.py
https://github.com/ktbyers/netmiko/blob/54e6116c0b4664de2123081937e0a9a27bdfdfea/netmiko/_textfsm/_texttable.py#L444-L478
def sort(self, cmp=None, key=None, reverse=False): """Sorts rows in the texttable. Args: cmp: func, non default sort algorithm to use. key: func, applied to each element before sorting. reverse: bool, reverse order of sort. """ def _DefaultKey(value): """Default key func is to create a list of all fields.""" result = [] for key in self.header: # Try sorting as numerical value if possible. try: result.append(float(value[key])) except ValueError: result.append(value[key]) return result key = key or _DefaultKey # Exclude header by copying table. new_table = self._table[1:] if cmp is not None: key = cmp_to_key(cmp) new_table.sort(key=key, reverse=reverse) # Regenerate the table with original header self._table = [self.header] self._table.extend(new_table) # Re-write the 'row' attribute of each row for index, row in enumerate(self._table): row.row = index
[ "def", "sort", "(", "self", ",", "cmp", "=", "None", ",", "key", "=", "None", ",", "reverse", "=", "False", ")", ":", "def", "_DefaultKey", "(", "value", ")", ":", "\"\"\"Default key func is to create a list of all fields.\"\"\"", "result", "=", "[", "]", "f...
Sorts rows in the texttable. Args: cmp: func, non default sort algorithm to use. key: func, applied to each element before sorting. reverse: bool, reverse order of sort.
[ "Sorts", "rows", "in", "the", "texttable", "." ]
python
train
seung-lab/cloud-volume
cloudvolume/cloudvolume.py
https://github.com/seung-lab/cloud-volume/blob/d2fd4500333f1bc3cd3e3919a8b649cec5d8e214/cloudvolume/cloudvolume.py#L911-L938
def delete(self, bbox_or_slices): """ Delete the files within the bounding box. bbox_or_slices: accepts either a Bbox or a tuple of slices representing the requested volume. """ if type(bbox_or_slices) is Bbox: requested_bbox = bbox_or_slices else: (requested_bbox, _, _) = self.__interpret_slices(bbox_or_slices) realized_bbox = self.__realized_bbox(requested_bbox) if requested_bbox != realized_bbox: raise exceptions.AlignmentError( "Unable to delete non-chunk aligned bounding boxes. Requested: {}, Realized: {}".format( requested_bbox, realized_bbox )) cloudpaths = txrx.chunknames(realized_bbox, self.bounds, self.key, self.underlying) cloudpaths = list(cloudpaths) with Storage(self.layer_cloudpath, progress=self.progress) as storage: storage.delete_files(cloudpaths) if self.cache.enabled: with Storage('file://' + self.cache.path, progress=self.progress) as storage: storage.delete_files(cloudpaths)
[ "def", "delete", "(", "self", ",", "bbox_or_slices", ")", ":", "if", "type", "(", "bbox_or_slices", ")", "is", "Bbox", ":", "requested_bbox", "=", "bbox_or_slices", "else", ":", "(", "requested_bbox", ",", "_", ",", "_", ")", "=", "self", ".", "__interpr...
Delete the files within the bounding box. bbox_or_slices: accepts either a Bbox or a tuple of slices representing the requested volume.
[ "Delete", "the", "files", "within", "the", "bounding", "box", "." ]
python
train
kpdyer/regex2dfa
third_party/re2/lib/codereview/codereview.py
https://github.com/kpdyer/regex2dfa/blob/109f877e60ef0dfcb430f11516d215930b7b9936/third_party/re2/lib/codereview/codereview.py#L1438-L1492
def release_apply(ui, repo, clname, **opts): """apply a CL to the release branch Creates a new CL copying a previously committed change from the main branch to the release branch. The current client must either be clean or already be in the release branch. The release branch must be created by starting with a clean client, disabling the code review plugin, and running: hg update weekly.YYYY-MM-DD hg branch release-branch.rNN hg commit -m 'create release-branch.rNN' hg push --new-branch Then re-enable the code review plugin. People can test the release branch by running hg update release-branch.rNN in a clean client. To return to the normal tree, hg update default Move changes since the weekly into the release branch using hg release-apply followed by the usual code review process and hg submit. When it comes time to tag the release, record the final long-form tag of the release-branch.rNN in the *default* branch's .hgtags file. That is, run hg update default and then edit .hgtags as you would for a weekly. """ c = repo[None] if not releaseBranch: raise hg_util.Abort("no active release branches") if c.branch() != releaseBranch: if c.modified() or c.added() or c.removed(): raise hg_util.Abort("uncommitted local changes - cannot switch branches") err = hg_clean(repo, releaseBranch) if err: raise hg_util.Abort(err) try: err = clpatch_or_undo(ui, repo, clname, opts, mode="backport") if err: raise hg_util.Abort(err) except Exception, e: hg_clean(repo, "default") raise e
[ "def", "release_apply", "(", "ui", ",", "repo", ",", "clname", ",", "*", "*", "opts", ")", ":", "c", "=", "repo", "[", "None", "]", "if", "not", "releaseBranch", ":", "raise", "hg_util", ".", "Abort", "(", "\"no active release branches\"", ")", "if", "...
apply a CL to the release branch Creates a new CL copying a previously committed change from the main branch to the release branch. The current client must either be clean or already be in the release branch. The release branch must be created by starting with a clean client, disabling the code review plugin, and running: hg update weekly.YYYY-MM-DD hg branch release-branch.rNN hg commit -m 'create release-branch.rNN' hg push --new-branch Then re-enable the code review plugin. People can test the release branch by running hg update release-branch.rNN in a clean client. To return to the normal tree, hg update default Move changes since the weekly into the release branch using hg release-apply followed by the usual code review process and hg submit. When it comes time to tag the release, record the final long-form tag of the release-branch.rNN in the *default* branch's .hgtags file. That is, run hg update default and then edit .hgtags as you would for a weekly.
[ "apply", "a", "CL", "to", "the", "release", "branch" ]
python
train
argaen/aiocache
aiocache/base.py
https://github.com/argaen/aiocache/blob/fdd282f37283ca04e22209f4d2ae4900f29e1688/aiocache/base.py#L417-L431
async def clear(self, namespace=None, _conn=None): """ Clears the cache in the cache namespace. If an alternative namespace is given, it will clear those ones instead. :param namespace: str alternative namespace to use :param timeout: int or float in seconds specifying maximum timeout for the operations to last :returns: True :raises: :class:`asyncio.TimeoutError` if it lasts more than self.timeout """ start = time.monotonic() ret = await self._clear(namespace, _conn=_conn) logger.debug("CLEAR %s %d (%.4f)s", namespace, ret, time.monotonic() - start) return ret
[ "async", "def", "clear", "(", "self", ",", "namespace", "=", "None", ",", "_conn", "=", "None", ")", ":", "start", "=", "time", ".", "monotonic", "(", ")", "ret", "=", "await", "self", ".", "_clear", "(", "namespace", ",", "_conn", "=", "_conn", ")...
Clears the cache in the cache namespace. If an alternative namespace is given, it will clear those ones instead. :param namespace: str alternative namespace to use :param timeout: int or float in seconds specifying maximum timeout for the operations to last :returns: True :raises: :class:`asyncio.TimeoutError` if it lasts more than self.timeout
[ "Clears", "the", "cache", "in", "the", "cache", "namespace", ".", "If", "an", "alternative", "namespace", "is", "given", "it", "will", "clear", "those", "ones", "instead", "." ]
python
train
pyviz/imagen
imagen/__init__.py
https://github.com/pyviz/imagen/blob/53c5685c880f54b42795964d8db50b02e8590e88/imagen/__init__.py#L546-L549
def get_current_generator(self): """Return the current generator (as specified by self.index).""" int_index=int(len(self.generators)*wrap(0,1.0,self.inspect_value('index'))) return self.generators[int_index]
[ "def", "get_current_generator", "(", "self", ")", ":", "int_index", "=", "int", "(", "len", "(", "self", ".", "generators", ")", "*", "wrap", "(", "0", ",", "1.0", ",", "self", ".", "inspect_value", "(", "'index'", ")", ")", ")", "return", "self", "....
Return the current generator (as specified by self.index).
[ "Return", "the", "current", "generator", "(", "as", "specified", "by", "self", ".", "index", ")", "." ]
python
train
MartijnBraam/pyElectronics
electronics/devices/mpu6050.py
https://github.com/MartijnBraam/pyElectronics/blob/a20878c9fa190135f1e478e9ea0b54ca43ff308e/electronics/devices/mpu6050.py#L120-L144
def acceleration(self): """Return the acceleration in G's :returns: Acceleration for every axis as a tuple :Example: >>> sensor = MPU6050I2C(gw) >>> sensor.wakeup() >>> sensor.acceleration() (0.6279296875, 0.87890625, 1.1298828125) """ if not self.awake: raise Exception("MPU6050 is in sleep mode, use wakeup()") raw = self.i2c_read_register(0x3B, 6) x, y, z = struct.unpack('>HHH', raw) scales = { self.RANGE_ACCEL_2G: 16384, self.RANGE_ACCEL_4G: 8192, self.RANGE_ACCEL_8G: 4096, self.RANGE_ACCEL_16G: 2048 } scale = scales[self.accel_range] return x / scale, y / scale, z / scale
[ "def", "acceleration", "(", "self", ")", ":", "if", "not", "self", ".", "awake", ":", "raise", "Exception", "(", "\"MPU6050 is in sleep mode, use wakeup()\"", ")", "raw", "=", "self", ".", "i2c_read_register", "(", "0x3B", ",", "6", ")", "x", ",", "y", ","...
Return the acceleration in G's :returns: Acceleration for every axis as a tuple :Example: >>> sensor = MPU6050I2C(gw) >>> sensor.wakeup() >>> sensor.acceleration() (0.6279296875, 0.87890625, 1.1298828125)
[ "Return", "the", "acceleration", "in", "G", "s" ]
python
train
specialunderwear/django-easymode
easymode/views.py
https://github.com/specialunderwear/django-easymode/blob/92f674b91fb8c54d6e379e2664e2000872d9c95e/easymode/views.py#L9-L32
def preview(request, content_type_id, object_id): """ This is an override for django.views.default.shortcut. It assumes that get_absolute_url returns an absolute url, so it does not do any of the very elaborate link checking that shortcut does. This version adds the language code to the url. (/en/blaat/). """ try: content_type = ContentType.objects.get(pk=content_type_id) obj = content_type.get_object_for_this_type(pk=object_id) except ObjectDoesNotExist: raise http.Http404("Content type %s object %s doesn't exist" % (content_type_id, object_id)) try: absolute_url = obj.get_absolute_url() except AttributeError: raise http.Http404("%s objects don't have get_absolute_url() methods" % content_type.name) if absolute_url.startswith('http://') or absolute_url.startswith('https://'): http.HttpResponseRedirect(absolute_url) else: absolute_url = fix_language_code(absolute_url, request.LANGUAGE_CODE) return http.HttpResponseRedirect(absolute_url)
[ "def", "preview", "(", "request", ",", "content_type_id", ",", "object_id", ")", ":", "try", ":", "content_type", "=", "ContentType", ".", "objects", ".", "get", "(", "pk", "=", "content_type_id", ")", "obj", "=", "content_type", ".", "get_object_for_this_type...
This is an override for django.views.default.shortcut. It assumes that get_absolute_url returns an absolute url, so it does not do any of the very elaborate link checking that shortcut does. This version adds the language code to the url. (/en/blaat/).
[ "This", "is", "an", "override", "for", "django", ".", "views", ".", "default", ".", "shortcut", ".", "It", "assumes", "that", "get_absolute_url", "returns", "an", "absolute", "url", "so", "it", "does", "not", "do", "any", "of", "the", "very", "elaborate", ...
python
train
Kortemme-Lab/klab
klab/bio/bonsai.py
https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/bio/bonsai.py#L231-L305
def parse(self, lines = None): '''Parses the PDB file into a indexed representation (a tagged list of lines, see constructor docstring). A set of Atoms is created, including x, y, z coordinates when applicable. These atoms are grouped into Residues. Finally, the limits of the 3D space are calculated to be used for Atom binning. ATOM serial numbers appear to be sequential within a model regardless of alternate locations (altLoc, see 1ABE). This code assumes that this holds as this serial number is used as an index. If an ATOM has a corresponding ANISOU record, the latter record uses the same serial number. ''' indexed_lines = [] MODEL_count = 0 records_types_with_atom_serial_numbers = set(['ATOM', 'HETATM', 'TER', 'ANISOU']) removable_records_types_with_atom_serial_numbers = set(['ATOM', 'HETATM', 'ANISOU']) removable_xyz_records_types_with_atom_serial_numbers = set(['ATOM', 'HETATM']) xs, ys, zs = [], [], [] # atoms maps ATOM/HETATM serial numbers to Atom objects. Atom objects know which Residue object they belong to and Residue objects maintain a list of their Atoms. atoms = {} # atoms maps chain -> residue IDs to Residue objects. Residue objects remember which ATOM/HETATM/ANISOU records (stored as Atom objects) belong to them residues = {} atom_name_to_group = {} for line in self.lines: record_type = line[:6].strip() if record_type in removable_records_types_with_atom_serial_numbers: #altLoc = line[16] atom_name = line[12:16].strip() chain = line[21] resid = line[22:27] # residue ID + insertion code serial_number = int(line[6:11]) element_name = None if record_type == 'ATOM': element_name = line[12:14].strip() # see the ATOM section of PDB format documentation. The element name is stored in these positions, right-justified. element_name = ''.join([w for w in element_name if w.isalpha()]) # e.g. 1 if atom_name not in atom_name_to_group: atom_name_to_group[atom_name] = element_name else: assert(atom_name_to_group[atom_name] == element_name) residues[chain] = residues.get(chain, {}) residues[chain][resid] = residues[chain].get(resid, Residue(chain, resid, line[17:20])) new_atom = Atom(residues[chain][resid], atom_name, element_name, serial_number, line[16]) residues[chain][resid].add(record_type.strip(), new_atom) if record_type in removable_xyz_records_types_with_atom_serial_numbers: x, y, z = float(line[30:38]), float(line[38:46]), float(line[46:54]) xs.append(x) ys.append(y) zs.append(z) assert(serial_number not in atoms) # the logic of this class relies on this assertion - that placed records have a unique identifier atoms[serial_number] = new_atom atoms[serial_number].place(x, y, z, record_type) indexed_lines.append((record_type, serial_number, line, new_atom)) else: indexed_lines.append((record_type, serial_number, line)) else: if record_type == 'MODEL ': MODEL_count += 1 if MODEL_count > 1: raise Exception('This code needs to be updated to properly handle NMR structures.') indexed_lines.append((None, line)) if not xs: raise Exception('No coordinates found.') # Calculate the side size needed for a cube to contain all of the points, with buffers to account for edge-cases min_x, min_y, min_z, max_x, max_y, max_z = min(xs), min(ys), min(zs), max(xs), max(ys), max(zs) self.min_x, self.min_y, self.min_z, self.max_x, self.max_y, self.max_z = min(xs)-self.buffer, min(ys)-self.buffer, min(zs)-self.buffer, max(xs)+self.buffer, max(ys)+self.buffer, max(zs)+self.buffer self.max_dimension = (self.buffer * 4) + max(self.max_x - self.min_x, self.max_y - self.min_y, self.max_z - self.min_z) self.residues = residues self.atoms = atoms self.indexed_lines = indexed_lines self.atom_name_to_group = atom_name_to_group
[ "def", "parse", "(", "self", ",", "lines", "=", "None", ")", ":", "indexed_lines", "=", "[", "]", "MODEL_count", "=", "0", "records_types_with_atom_serial_numbers", "=", "set", "(", "[", "'ATOM'", ",", "'HETATM'", ",", "'TER'", ",", "'ANISOU'", "]", ")", ...
Parses the PDB file into a indexed representation (a tagged list of lines, see constructor docstring). A set of Atoms is created, including x, y, z coordinates when applicable. These atoms are grouped into Residues. Finally, the limits of the 3D space are calculated to be used for Atom binning. ATOM serial numbers appear to be sequential within a model regardless of alternate locations (altLoc, see 1ABE). This code assumes that this holds as this serial number is used as an index. If an ATOM has a corresponding ANISOU record, the latter record uses the same serial number.
[ "Parses", "the", "PDB", "file", "into", "a", "indexed", "representation", "(", "a", "tagged", "list", "of", "lines", "see", "constructor", "docstring", ")", ".", "A", "set", "of", "Atoms", "is", "created", "including", "x", "y", "z", "coordinates", "when",...
python
train
spyder-ide/spyder
spyder/plugins/workingdirectory/plugin.py
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/workingdirectory/plugin.py#L203-L205
def parent_directory(self): """Change working directory to parent directory""" self.chdir(os.path.join(getcwd_or_home(), os.path.pardir))
[ "def", "parent_directory", "(", "self", ")", ":", "self", ".", "chdir", "(", "os", ".", "path", ".", "join", "(", "getcwd_or_home", "(", ")", ",", "os", ".", "path", ".", "pardir", ")", ")" ]
Change working directory to parent directory
[ "Change", "working", "directory", "to", "parent", "directory" ]
python
train
CalebBell/thermo
thermo/safety.py
https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/safety.py#L1022-L1071
def Suzuki_LFL(Hc=None): r'''Calculates lower flammability limit, using the Suzuki [1]_ correlation. Uses heat of combustion only. The lower flammability limit of a gas is air is: .. math:: \text{LFL} = \frac{-3.42}{\Delta H_c^{\circ}} + 0.569 \Delta H_c^{\circ} + 0.0538\Delta H_c^{\circ 2} + 1.80 Parameters ---------- Hc : float Heat of combustion of gas [J/mol] Returns ------- LFL : float Lower flammability limit, mole fraction [-] Notes ----- Fit performed with 112 compounds, r^2 was 0.977. LFL in percent volume in air. Hc is at standard conditions, in MJ/mol. 11 compounds left out as they were outliers. Equation does not apply for molecules with halogen atoms, only hydrocarbons with oxygen or nitrogen or sulfur. No sample calculation provided with the article. However, the equation is straightforward. Limits of equations's validity are -6135596 J where it predicts a LFL of 0, and -48322129 J where it predicts a LFL of 1. Examples -------- Pentane, 1.5 % LFL in literature >>> Suzuki_LFL(-3536600) 0.014276107095811815 References ---------- .. [1] Suzuki, Takahiro. "Note: Empirical Relationship between Lower Flammability Limits and Standard Enthalpies of Combustion of Organic Compounds." Fire and Materials 18, no. 5 (September 1, 1994): 333-36. doi:10.1002/fam.810180509. ''' Hc = Hc/1E6 LFL = -3.42/Hc + 0.569*Hc + 0.0538*Hc*Hc + 1.80 return LFL/100.
[ "def", "Suzuki_LFL", "(", "Hc", "=", "None", ")", ":", "Hc", "=", "Hc", "/", "1E6", "LFL", "=", "-", "3.42", "/", "Hc", "+", "0.569", "*", "Hc", "+", "0.0538", "*", "Hc", "*", "Hc", "+", "1.80", "return", "LFL", "/", "100." ]
r'''Calculates lower flammability limit, using the Suzuki [1]_ correlation. Uses heat of combustion only. The lower flammability limit of a gas is air is: .. math:: \text{LFL} = \frac{-3.42}{\Delta H_c^{\circ}} + 0.569 \Delta H_c^{\circ} + 0.0538\Delta H_c^{\circ 2} + 1.80 Parameters ---------- Hc : float Heat of combustion of gas [J/mol] Returns ------- LFL : float Lower flammability limit, mole fraction [-] Notes ----- Fit performed with 112 compounds, r^2 was 0.977. LFL in percent volume in air. Hc is at standard conditions, in MJ/mol. 11 compounds left out as they were outliers. Equation does not apply for molecules with halogen atoms, only hydrocarbons with oxygen or nitrogen or sulfur. No sample calculation provided with the article. However, the equation is straightforward. Limits of equations's validity are -6135596 J where it predicts a LFL of 0, and -48322129 J where it predicts a LFL of 1. Examples -------- Pentane, 1.5 % LFL in literature >>> Suzuki_LFL(-3536600) 0.014276107095811815 References ---------- .. [1] Suzuki, Takahiro. "Note: Empirical Relationship between Lower Flammability Limits and Standard Enthalpies of Combustion of Organic Compounds." Fire and Materials 18, no. 5 (September 1, 1994): 333-36. doi:10.1002/fam.810180509.
[ "r", "Calculates", "lower", "flammability", "limit", "using", "the", "Suzuki", "[", "1", "]", "_", "correlation", ".", "Uses", "heat", "of", "combustion", "only", "." ]
python
valid
jayclassless/tidypy
src/tidypy/util.py
https://github.com/jayclassless/tidypy/blob/3c3497ca377fbbe937103b77b02b326c860c748f/src/tidypy/util.py#L221-L236
def read_file(filepath): """ Retrieves the contents of the specified file. This function performs simple caching so that the same file isn't read more than once per process. :param filepath: the file to read :type filepath: str :returns: str """ with _FILE_CACHE_LOCK: if filepath not in _FILE_CACHE: _FILE_CACHE[filepath] = _read_file(filepath) return _FILE_CACHE[filepath]
[ "def", "read_file", "(", "filepath", ")", ":", "with", "_FILE_CACHE_LOCK", ":", "if", "filepath", "not", "in", "_FILE_CACHE", ":", "_FILE_CACHE", "[", "filepath", "]", "=", "_read_file", "(", "filepath", ")", "return", "_FILE_CACHE", "[", "filepath", "]" ]
Retrieves the contents of the specified file. This function performs simple caching so that the same file isn't read more than once per process. :param filepath: the file to read :type filepath: str :returns: str
[ "Retrieves", "the", "contents", "of", "the", "specified", "file", "." ]
python
valid
edeposit/marcxml_parser
src/marcxml_parser/query.py
https://github.com/edeposit/marcxml_parser/blob/6d1c77c61fc2827b71f1b3d5aa3332d7f5807820/src/marcxml_parser/query.py#L373-L383
def get_authors(self): """ Returns: list: Authors represented as :class:`.Person` objects. """ authors = self._parse_persons("100", "a") authors += self._parse_persons("600", "a") authors += self._parse_persons("700", "a") authors += self._parse_persons("800", "a") return authors
[ "def", "get_authors", "(", "self", ")", ":", "authors", "=", "self", ".", "_parse_persons", "(", "\"100\"", ",", "\"a\"", ")", "authors", "+=", "self", ".", "_parse_persons", "(", "\"600\"", ",", "\"a\"", ")", "authors", "+=", "self", ".", "_parse_persons"...
Returns: list: Authors represented as :class:`.Person` objects.
[ "Returns", ":", "list", ":", "Authors", "represented", "as", ":", "class", ":", ".", "Person", "objects", "." ]
python
valid
MLAB-project/pymlab
src/pymlab/sensors/gpio.py
https://github.com/MLAB-project/pymlab/blob/d18d858ae83b203defcf2aead0dbd11b3c444658/src/pymlab/sensors/gpio.py#L242-L246
def set_ports(self, port0 = 0x00, port1 = 0x00): 'Writes specified value to the pins defined as output by method. Writing to input pins has no effect.' self.bus.write_byte_data(self.address, self.CONTROL_PORT0, port0) self.bus.write_byte_data(self.address, self.CONTROL_PORT0, port1) return
[ "def", "set_ports", "(", "self", ",", "port0", "=", "0x00", ",", "port1", "=", "0x00", ")", ":", "self", ".", "bus", ".", "write_byte_data", "(", "self", ".", "address", ",", "self", ".", "CONTROL_PORT0", ",", "port0", ")", "self", ".", "bus", ".", ...
Writes specified value to the pins defined as output by method. Writing to input pins has no effect.
[ "Writes", "specified", "value", "to", "the", "pins", "defined", "as", "output", "by", "method", ".", "Writing", "to", "input", "pins", "has", "no", "effect", "." ]
python
train
Unity-Technologies/ml-agents
ml-agents/mlagents/trainers/models.py
https://github.com/Unity-Technologies/ml-agents/blob/37d139af636e4a2351751fbf0f2fca5a9ed7457f/ml-agents/mlagents/trainers/models.py#L158-L175
def create_discrete_action_masking_layer(all_logits, action_masks, action_size): """ Creates a masking layer for the discrete actions :param all_logits: The concatenated unnormalized action probabilities for all branches :param action_masks: The mask for the logits. Must be of dimension [None x total_number_of_action] :param action_size: A list containing the number of possible actions for each branch :return: The action output dimension [batch_size, num_branches] and the concatenated normalized logits """ action_idx = [0] + list(np.cumsum(action_size)) branches_logits = [all_logits[:, action_idx[i]:action_idx[i + 1]] for i in range(len(action_size))] branch_masks = [action_masks[:, action_idx[i]:action_idx[i + 1]] for i in range(len(action_size))] raw_probs = [tf.multiply(tf.nn.softmax(branches_logits[k]) + 1.0e-10, branch_masks[k]) for k in range(len(action_size))] normalized_probs = [ tf.divide(raw_probs[k], tf.reduce_sum(raw_probs[k], axis=1, keepdims=True)) for k in range(len(action_size))] output = tf.concat([tf.multinomial(tf.log(normalized_probs[k]), 1) for k in range(len(action_size))], axis=1) return output, tf.concat([tf.log(normalized_probs[k] + 1.0e-10) for k in range(len(action_size))], axis=1)
[ "def", "create_discrete_action_masking_layer", "(", "all_logits", ",", "action_masks", ",", "action_size", ")", ":", "action_idx", "=", "[", "0", "]", "+", "list", "(", "np", ".", "cumsum", "(", "action_size", ")", ")", "branches_logits", "=", "[", "all_logits...
Creates a masking layer for the discrete actions :param all_logits: The concatenated unnormalized action probabilities for all branches :param action_masks: The mask for the logits. Must be of dimension [None x total_number_of_action] :param action_size: A list containing the number of possible actions for each branch :return: The action output dimension [batch_size, num_branches] and the concatenated normalized logits
[ "Creates", "a", "masking", "layer", "for", "the", "discrete", "actions", ":", "param", "all_logits", ":", "The", "concatenated", "unnormalized", "action", "probabilities", "for", "all", "branches", ":", "param", "action_masks", ":", "The", "mask", "for", "the", ...
python
train
dfm/george
george/modeling.py
https://github.com/dfm/george/blob/44819680036387625ee89f81c55104f3c1600759/george/modeling.py#L268-L277
def freeze_parameter(self, name): """ Freeze a parameter by name Args: name: The name of the parameter """ i = self.get_parameter_names(include_frozen=True).index(name) self.unfrozen_mask[i] = False
[ "def", "freeze_parameter", "(", "self", ",", "name", ")", ":", "i", "=", "self", ".", "get_parameter_names", "(", "include_frozen", "=", "True", ")", ".", "index", "(", "name", ")", "self", ".", "unfrozen_mask", "[", "i", "]", "=", "False" ]
Freeze a parameter by name Args: name: The name of the parameter
[ "Freeze", "a", "parameter", "by", "name" ]
python
train
FutunnOpen/futuquant
futuquant/examples/TinyQuant/TinyQuantBase.py
https://github.com/FutunnOpen/futuquant/blob/1512b321845f92ec9c578ce2689aa4e8482669e4/futuquant/examples/TinyQuant/TinyQuantBase.py#L122-L127
def sma(self, n, array=False): """简单均线""" result = talib.SMA(self.close, n) if array: return result return result[-1]
[ "def", "sma", "(", "self", ",", "n", ",", "array", "=", "False", ")", ":", "result", "=", "talib", ".", "SMA", "(", "self", ".", "close", ",", "n", ")", "if", "array", ":", "return", "result", "return", "result", "[", "-", "1", "]" ]
简单均线
[ "简单均线" ]
python
train
quintusdias/glymur
glymur/jp2box.py
https://github.com/quintusdias/glymur/blob/8b8fb091130fff00f1028dc82219e69e3f9baf6d/glymur/jp2box.py#L3309-L3323
def _parse_raw_data(self): """ Private function for parsing UUID payloads if possible. """ if self.uuid == _XMP_UUID: txt = self.raw_data.decode('utf-8') elt = ET.fromstring(txt) self.data = ET.ElementTree(elt) elif self.uuid == _GEOTIFF_UUID: self.data = tiff_header(self.raw_data) elif self.uuid == _EXIF_UUID: # Cut off 'EXIF\0\0' part. self.data = tiff_header(self.raw_data[6:]) else: self.data = self.raw_data
[ "def", "_parse_raw_data", "(", "self", ")", ":", "if", "self", ".", "uuid", "==", "_XMP_UUID", ":", "txt", "=", "self", ".", "raw_data", ".", "decode", "(", "'utf-8'", ")", "elt", "=", "ET", ".", "fromstring", "(", "txt", ")", "self", ".", "data", ...
Private function for parsing UUID payloads if possible.
[ "Private", "function", "for", "parsing", "UUID", "payloads", "if", "possible", "." ]
python
train
gitpython-developers/GitPython
git/refs/log.py
https://github.com/gitpython-developers/GitPython/blob/1f66e25c25cde2423917ee18c4704fff83b837d1/git/refs/log.py#L295-L302
def write(self): """Write this instance's data to the file we are originating from :return: self""" if self._path is None: raise ValueError("Instance was not initialized with a path, use to_file(...) instead") # END assert path self.to_file(self._path) return self
[ "def", "write", "(", "self", ")", ":", "if", "self", ".", "_path", "is", "None", ":", "raise", "ValueError", "(", "\"Instance was not initialized with a path, use to_file(...) instead\"", ")", "# END assert path", "self", ".", "to_file", "(", "self", ".", "_path", ...
Write this instance's data to the file we are originating from :return: self
[ "Write", "this", "instance", "s", "data", "to", "the", "file", "we", "are", "originating", "from", ":", "return", ":", "self" ]
python
train
derpferd/little-python
littlepython/parser.py
https://github.com/derpferd/little-python/blob/3f89c74cffb6532c12c5b40843bd8ff8605638ba/littlepython/parser.py#L99-L116
def control(self): """ control : 'if' ctrl_exp block ('elif' ctrl_exp block)* ('else' block) """ self.eat(TokenTypes.IF) ctrl = self.expression() block = self.block() ifs = [If(ctrl, block)] else_block = Block() while self.cur_token.type == TokenTypes.ELIF: self.eat(TokenTypes.ELIF) ctrl = self.expression() block = self.block() ifs.append(If(ctrl, block)) if self.cur_token.type == TokenTypes.ELSE: self.eat(TokenTypes.ELSE) else_block = self.block() return ControlBlock(ifs, else_block)
[ "def", "control", "(", "self", ")", ":", "self", ".", "eat", "(", "TokenTypes", ".", "IF", ")", "ctrl", "=", "self", ".", "expression", "(", ")", "block", "=", "self", ".", "block", "(", ")", "ifs", "=", "[", "If", "(", "ctrl", ",", "block", ")...
control : 'if' ctrl_exp block ('elif' ctrl_exp block)* ('else' block)
[ "control", ":", "if", "ctrl_exp", "block", "(", "elif", "ctrl_exp", "block", ")", "*", "(", "else", "block", ")" ]
python
train
mapillary/mapillary_tools
mapillary_tools/exif_write.py
https://github.com/mapillary/mapillary_tools/blob/816785e90c589cae6e8e34a5530ce8417d29591c/mapillary_tools/exif_write.py#L40-L46
def add_date_time_original(self, date_time, time_format='%Y:%m:%d %H:%M:%S.%f'): """Add date time original.""" try: DateTimeOriginal = date_time.strftime(time_format)[:-3] self._ef['Exif'][piexif.ExifIFD.DateTimeOriginal] = DateTimeOriginal except Exception as e: print_error("Error writing DateTimeOriginal, due to " + str(e))
[ "def", "add_date_time_original", "(", "self", ",", "date_time", ",", "time_format", "=", "'%Y:%m:%d %H:%M:%S.%f'", ")", ":", "try", ":", "DateTimeOriginal", "=", "date_time", ".", "strftime", "(", "time_format", ")", "[", ":", "-", "3", "]", "self", ".", "_e...
Add date time original.
[ "Add", "date", "time", "original", "." ]
python
train
alephdata/memorious
memorious/helpers/__init__.py
https://github.com/alephdata/memorious/blob/b4033c5064447ed5f696f9c2bbbc6c12062d2fa4/memorious/helpers/__init__.py#L42-L46
def search_results_last_url(html, xpath, label): """ Get the URL of the 'last' button in a search results listing. """ for container in html.findall(xpath): if container.text_content().strip() == label: return container.find('.//a').get('href')
[ "def", "search_results_last_url", "(", "html", ",", "xpath", ",", "label", ")", ":", "for", "container", "in", "html", ".", "findall", "(", "xpath", ")", ":", "if", "container", ".", "text_content", "(", ")", ".", "strip", "(", ")", "==", "label", ":",...
Get the URL of the 'last' button in a search results listing.
[ "Get", "the", "URL", "of", "the", "last", "button", "in", "a", "search", "results", "listing", "." ]
python
train
apple/turicreate
src/unity/python/turicreate/toolkits/graph_analytics/_model_base.py
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/graph_analytics/_model_base.py#L90-L130
def _get_summary_struct(self): """ Returns a structured description of the model, including (where relevant) the schema of the training data, description of the training data, training statistics, and model hyperparameters. Returns ------- sections : list (of list of tuples) A list of summary sections. Each section is a list. Each item in a section list is a tuple of the form: ('<label>','<field>') section_titles: list A list of section titles. The order matches that of the 'sections' object. """ g = self.graph section_titles = ['Graph'] graph_summary = [(k, _precomputed_field(v)) for k, v in six.iteritems(g.summary())] sections = [graph_summary] # collect other sections results = [(k, _precomputed_field(v)) for k, v in six.iteritems(self._result_fields())] methods = [(k, _precomputed_field(v)) for k, v in six.iteritems(self._method_fields())] settings = [(k, v) for k, v in six.iteritems(self._setting_fields())] metrics = [(k, v) for k, v in six.iteritems(self._metric_fields())] optional_sections = [('Results', results), ('Settings', settings), \ ('Metrics', metrics), ('Methods', methods)] # if section is not empty, append to summary structure for (title, section) in optional_sections: if len(section) > 0: section_titles.append(title) sections.append(section) return (sections, section_titles)
[ "def", "_get_summary_struct", "(", "self", ")", ":", "g", "=", "self", ".", "graph", "section_titles", "=", "[", "'Graph'", "]", "graph_summary", "=", "[", "(", "k", ",", "_precomputed_field", "(", "v", ")", ")", "for", "k", ",", "v", "in", "six", "....
Returns a structured description of the model, including (where relevant) the schema of the training data, description of the training data, training statistics, and model hyperparameters. Returns ------- sections : list (of list of tuples) A list of summary sections. Each section is a list. Each item in a section list is a tuple of the form: ('<label>','<field>') section_titles: list A list of section titles. The order matches that of the 'sections' object.
[ "Returns", "a", "structured", "description", "of", "the", "model", "including", "(", "where", "relevant", ")", "the", "schema", "of", "the", "training", "data", "description", "of", "the", "training", "data", "training", "statistics", "and", "model", "hyperparam...
python
train
alex-kostirin/pyatomac
atomac/AXClasses.py
https://github.com/alex-kostirin/pyatomac/blob/3f46f6feb4504315eec07abb18bb41be4d257aeb/atomac/AXClasses.py#L384-L393
def _holdModifierKeys(self, modifiers): """Hold given modifier keys (provided in list form). Parameters: modifiers list Returns: Unsigned int representing flags to set """ modFlags = self._pressModifiers(modifiers) # Post the queued keypresses: self._postQueuedEvents() return modFlags
[ "def", "_holdModifierKeys", "(", "self", ",", "modifiers", ")", ":", "modFlags", "=", "self", ".", "_pressModifiers", "(", "modifiers", ")", "# Post the queued keypresses:", "self", ".", "_postQueuedEvents", "(", ")", "return", "modFlags" ]
Hold given modifier keys (provided in list form). Parameters: modifiers list Returns: Unsigned int representing flags to set
[ "Hold", "given", "modifier", "keys", "(", "provided", "in", "list", "form", ")", "." ]
python
valid
jobovy/galpy
galpy/potential/planarPotential.py
https://github.com/jobovy/galpy/blob/9c5b9fe65d58835624dffe432be282060918ee08/galpy/potential/planarPotential.py#L867-L882
def _phiforce(self,R,phi=0.,t=0.): """ NAME: _phiforce PURPOSE: evaluate the azimuthal force INPUT: R phi t OUTPUT: F_phi(R(,\phi,t)) HISTORY: 2016-06-02 - Written - Bovy (UofT) """ return self._Pot.phiforce(R,0.,phi=phi,t=t,use_physical=False)
[ "def", "_phiforce", "(", "self", ",", "R", ",", "phi", "=", "0.", ",", "t", "=", "0.", ")", ":", "return", "self", ".", "_Pot", ".", "phiforce", "(", "R", ",", "0.", ",", "phi", "=", "phi", ",", "t", "=", "t", ",", "use_physical", "=", "False...
NAME: _phiforce PURPOSE: evaluate the azimuthal force INPUT: R phi t OUTPUT: F_phi(R(,\phi,t)) HISTORY: 2016-06-02 - Written - Bovy (UofT)
[ "NAME", ":", "_phiforce", "PURPOSE", ":", "evaluate", "the", "azimuthal", "force", "INPUT", ":", "R", "phi", "t", "OUTPUT", ":", "F_phi", "(", "R", "(", "\\", "phi", "t", "))", "HISTORY", ":", "2016", "-", "06", "-", "02", "-", "Written", "-", "Bov...
python
train
klen/muffin-metrics
muffin_metrics.py
https://github.com/klen/muffin-metrics/blob/b62fc25172e3e1e9fc6dc6c8da3170935ee69f01/muffin_metrics.py#L185-L189
def connect(self): """Connect to socket.""" self.transport, _ = yield from self.parent.app.loop.create_datagram_endpoint( DatagramProtocol, remote_addr=(self.hostname, self.port)) return self
[ "def", "connect", "(", "self", ")", ":", "self", ".", "transport", ",", "_", "=", "yield", "from", "self", ".", "parent", ".", "app", ".", "loop", ".", "create_datagram_endpoint", "(", "DatagramProtocol", ",", "remote_addr", "=", "(", "self", ".", "hostn...
Connect to socket.
[ "Connect", "to", "socket", "." ]
python
train
wonambi-python/wonambi
wonambi/ioeeg/wonambi.py
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/ioeeg/wonambi.py#L50-L102
def return_dat(self, chan, begsam, endsam): """Return the data as 2D numpy.ndarray. Parameters ---------- chan : int or list index (indices) of the channels to read begsam : int index of the first sample endsam : int index of the last sample Returns ------- numpy.ndarray A 2d matrix, with dimension chan X samples. To save memory, the data are memory-mapped, and you cannot change the values on disk. Raises ------ FileNotFoundError if .dat file is not in the same directory, with the same name. Notes ----- When asking for an interval outside the data boundaries, it returns NaN for those values. It then converts the memmap to a normal numpy array, I think, and so it reads the data into memory. However, I'm not 100% sure that this is what happens. """ memmap_file = Path(self.filename).with_suffix('.dat') if not memmap_file.exists(): raise FileNotFoundError('Could not find ' + str(memmap_file)) data = memmap(str(memmap_file), self.dtype, mode='c', shape=self.memshape, order='F') n_smp = self.memshape[1] dat = data[chan, max((begsam, 0)):min((endsam, n_smp))].astype(float64) if begsam < 0: pad = empty((dat.shape[0], 0 - begsam)) pad.fill(NaN) dat = c_[pad, dat] if endsam >= n_smp: pad = empty((dat.shape[0], endsam - n_smp)) pad.fill(NaN) dat = c_[dat, pad] return dat
[ "def", "return_dat", "(", "self", ",", "chan", ",", "begsam", ",", "endsam", ")", ":", "memmap_file", "=", "Path", "(", "self", ".", "filename", ")", ".", "with_suffix", "(", "'.dat'", ")", "if", "not", "memmap_file", ".", "exists", "(", ")", ":", "r...
Return the data as 2D numpy.ndarray. Parameters ---------- chan : int or list index (indices) of the channels to read begsam : int index of the first sample endsam : int index of the last sample Returns ------- numpy.ndarray A 2d matrix, with dimension chan X samples. To save memory, the data are memory-mapped, and you cannot change the values on disk. Raises ------ FileNotFoundError if .dat file is not in the same directory, with the same name. Notes ----- When asking for an interval outside the data boundaries, it returns NaN for those values. It then converts the memmap to a normal numpy array, I think, and so it reads the data into memory. However, I'm not 100% sure that this is what happens.
[ "Return", "the", "data", "as", "2D", "numpy", ".", "ndarray", "." ]
python
train
tensorflow/tensor2tensor
tensor2tensor/layers/common_attention.py
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L3572-L3582
def scatter_blocks_2d(x, indices, shape): """scatters blocks from x into shape with indices.""" x_shape = common_layers.shape_list(x) # [length, batch, heads, dim] x_t = tf.transpose( tf.reshape(x, [x_shape[0], x_shape[1], -1, x_shape[-1]]), [2, 0, 1, 3]) x_t_shape = common_layers.shape_list(x_t) indices = tf.reshape(indices, [-1, 1]) scattered_x = tf.scatter_nd(indices, x_t, x_t_shape) scattered_x = tf.transpose(scattered_x, [1, 2, 0, 3]) return tf.reshape(scattered_x, shape)
[ "def", "scatter_blocks_2d", "(", "x", ",", "indices", ",", "shape", ")", ":", "x_shape", "=", "common_layers", ".", "shape_list", "(", "x", ")", "# [length, batch, heads, dim]", "x_t", "=", "tf", ".", "transpose", "(", "tf", ".", "reshape", "(", "x", ",", ...
scatters blocks from x into shape with indices.
[ "scatters", "blocks", "from", "x", "into", "shape", "with", "indices", "." ]
python
train
fabioz/PyDev.Debugger
third_party/pep8/pycodestyle.py
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/third_party/pep8/pycodestyle.py#L1688-L1701
def generate_tokens(self): """Tokenize the file, run physical line checks and yield tokens.""" if self._io_error: self.report_error(1, 0, 'E902 %s' % self._io_error, readlines) tokengen = tokenize.generate_tokens(self.readline) try: for token in tokengen: if token[2][0] > self.total_lines: return self.noqa = token[4] and noqa(token[4]) self.maybe_check_physical(token) yield token except (SyntaxError, tokenize.TokenError): self.report_invalid_syntax()
[ "def", "generate_tokens", "(", "self", ")", ":", "if", "self", ".", "_io_error", ":", "self", ".", "report_error", "(", "1", ",", "0", ",", "'E902 %s'", "%", "self", ".", "_io_error", ",", "readlines", ")", "tokengen", "=", "tokenize", ".", "generate_tok...
Tokenize the file, run physical line checks and yield tokens.
[ "Tokenize", "the", "file", "run", "physical", "line", "checks", "and", "yield", "tokens", "." ]
python
train
ShenggaoZhu/midict
midict/__init__.py
https://github.com/ShenggaoZhu/midict/blob/2fad2edcfb753035b443a70fe15852affae1b5bb/midict/__init__.py#L456-L603
def MI_parse_args(self, args, ingore_index2=False, allow_new=False): ''' Parse the arguments for indexing in MIDict. Full syntax: ``d[index1:key, index2]``. ``index2`` can be flexible indexing (int, list, slice etc.) as in ``IndexDict``. Short syntax: * d[key] <==> d[key,] <==> d[first_index:key, all_indice_except_first] * d[:key] <==> d[:key,] <==> d[None:key] <==> d[last_index:key, all_indice_except_last] * d[key, index2] <==> d[first_index:key, index2] # this is valid # only when index2 is a list or slice object * d[index1:key, index2_1, index2_2, ...] <==> d[index1:key, (index2_1, index2_2, ...)] ''' empty = len(self.indices) == 0 if empty and not allow_new: raise KeyError('Item not found (dictionary is empty): %s' % (args,)) names = force_list(self.indices.keys()) Nargs = len(args) if isinstance(args, tuple) else 1 _default = object() index1 = index2 = _default if isinstance(args, tuple): # easy handle of default logic (use continue/break as shortcut) for _ in (1,): if ingore_index2: continue if isinstance(args[0], slice): index1, key = args[0].start, args[0].stop if Nargs == 2: index2 = args[1] elif Nargs > 2: index2 = args[1:] break # args[0] is not a slice if Nargs > 1 and isinstance(args[1], (list, slice)): if Nargs == 2: key, index2 = args break else: raise KeyError('No arguments allowed after index2, found: %s' % (args[2:],)) else: key = args elif isinstance(args, slice): index1, key = args.start, args.stop else: key = args if empty: # allow_new is True index1_last = False exist_names = [] # list of names already passed in as arguments if index1 is not _default: if index1 is None: # slice syntax d[:key] index1_last = True index1 = _default elif isinstance(index1, int): raise TypeError('Index1 can not be int when dictionary ' 'is empty: %s' % (index1,)) else: MI_check_index_name(index1) exist_names.append(index1) if index2 is not _default: if isinstance(index2, (tuple, list)): map(MI_check_index_name, index2) exist_names.extend(index2) elif isinstance(index2, (int, slice)): raise TypeError('Index2 can not be int or slice when ' 'dictionary is empty: %s' % (index2,)) else: MI_check_index_name(index2) exist_names.append(index2) # auto generate index names and avoid conficts with existing names if index1 is _default: if index1_last: if len(exist_names) > 1: # index2 is specified name1 = 'index_%s' % (len(exist_names) + 1) else: name1 = 'index_2' else: name1 = 'index_1' index1 = get_unique_name(name1, exist_names) exist_names.append(index1) if index2 is _default: name2 = 'index_1' if index1_last else 'index_2' index2 = get_unique_name(name2, exist_names) return index1, key, index2, index1_last # not empty: if index1 is _default: # not specified index1 = 0 elif index1 is None: # slice syntax d[:key] index1 = -1 # index1 is always returned as an int index1 = _key_to_index_single(names, index1) try: item = MI_get_item(self, key, index1) except KeyError: if allow_new: # new key for setitem; item_d = None item = None else: raise KeyError('Key not found in index #%s "%s": %s' % (index1, names[index1], key)) if ingore_index2: # used by delitem return item if index2 is _default: # not specified # index2 defaults to all indices except index1 if len(names) == 1: index2 = 0 # index2 defaults to the only one index else: index2 = force_list(range(len(names))) index2.remove(index1) if len(index2) == 1: # single index index2 = index2[0] else: # index2 is always returned as int or list of int index2 = _key_to_index(names, index2) if item is None: # allow_new. item and value are None return index1, key, index2, None, None # try: # value = mget_list(item, index2) # except IndexError: # raise KeyError('Index not found: %s' % (index2,)) # no need to try since index2 is always returned as int or list of int value = mget_list(item, index2) return index1, key, index2, item, value
[ "def", "MI_parse_args", "(", "self", ",", "args", ",", "ingore_index2", "=", "False", ",", "allow_new", "=", "False", ")", ":", "empty", "=", "len", "(", "self", ".", "indices", ")", "==", "0", "if", "empty", "and", "not", "allow_new", ":", "raise", ...
Parse the arguments for indexing in MIDict. Full syntax: ``d[index1:key, index2]``. ``index2`` can be flexible indexing (int, list, slice etc.) as in ``IndexDict``. Short syntax: * d[key] <==> d[key,] <==> d[first_index:key, all_indice_except_first] * d[:key] <==> d[:key,] <==> d[None:key] <==> d[last_index:key, all_indice_except_last] * d[key, index2] <==> d[first_index:key, index2] # this is valid # only when index2 is a list or slice object * d[index1:key, index2_1, index2_2, ...] <==> d[index1:key, (index2_1, index2_2, ...)]
[ "Parse", "the", "arguments", "for", "indexing", "in", "MIDict", "." ]
python
train
StackStorm/pybind
pybind/nos/v7_2_0/__init__.py
https://github.com/StackStorm/pybind/blob/44c467e71b2b425be63867aba6e6fa28b2cfe7fb/pybind/nos/v7_2_0/__init__.py#L9506-L9527
def _set_police_priority_map(self, v, load=False): """ Setter method for police_priority_map, mapped from YANG variable /police_priority_map (list) If this variable is read-only (config: false) in the source YANG file, then _set_police_priority_map is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_police_priority_map() directly. """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=YANGListType("name",police_priority_map.police_priority_map, yang_name="police-priority-map", rest_name="police-priority-map", parent=self, is_container='list', user_ordered=False, path_helper=self._path_helper, yang_keys='name', extensions={u'tailf-common': {u'info': u'Policer Priority Map Configuration', u'sort-priority': u'69', u'cli-suppress-list-no': None, u'cli-full-command': None, u'callpoint': u'policer-priority-map', u'cli-mode-name': u'config-policepmap'}}), is_container='list', yang_name="police-priority-map", rest_name="police-priority-map", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'Policer Priority Map Configuration', u'sort-priority': u'69', u'cli-suppress-list-no': None, u'cli-full-command': None, u'callpoint': u'policer-priority-map', u'cli-mode-name': u'config-policepmap'}}, namespace='urn:brocade.com:mgmt:brocade-policer', defining_module='brocade-policer', yang_type='list', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """police_priority_map must be of a type compatible with list""", 'defined-type': "list", 'generated-type': """YANGDynClass(base=YANGListType("name",police_priority_map.police_priority_map, yang_name="police-priority-map", rest_name="police-priority-map", parent=self, is_container='list', user_ordered=False, path_helper=self._path_helper, yang_keys='name', extensions={u'tailf-common': {u'info': u'Policer Priority Map Configuration', u'sort-priority': u'69', u'cli-suppress-list-no': None, u'cli-full-command': None, u'callpoint': u'policer-priority-map', u'cli-mode-name': u'config-policepmap'}}), is_container='list', yang_name="police-priority-map", rest_name="police-priority-map", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'Policer Priority Map Configuration', u'sort-priority': u'69', u'cli-suppress-list-no': None, u'cli-full-command': None, u'callpoint': u'policer-priority-map', u'cli-mode-name': u'config-policepmap'}}, namespace='urn:brocade.com:mgmt:brocade-policer', defining_module='brocade-policer', yang_type='list', is_config=True)""", }) self.__police_priority_map = t if hasattr(self, '_set'): self._set()
[ "def", "_set_police_priority_map", "(", "self", ",", "v", ",", "load", "=", "False", ")", ":", "if", "hasattr", "(", "v", ",", "\"_utype\"", ")", ":", "v", "=", "v", ".", "_utype", "(", "v", ")", "try", ":", "t", "=", "YANGDynClass", "(", "v", ",...
Setter method for police_priority_map, mapped from YANG variable /police_priority_map (list) If this variable is read-only (config: false) in the source YANG file, then _set_police_priority_map is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_police_priority_map() directly.
[ "Setter", "method", "for", "police_priority_map", "mapped", "from", "YANG", "variable", "/", "police_priority_map", "(", "list", ")", "If", "this", "variable", "is", "read", "-", "only", "(", "config", ":", "false", ")", "in", "the", "source", "YANG", "file"...
python
train
twisted/txaws
txaws/ec2/client.py
https://github.com/twisted/txaws/blob/5c3317376cd47e536625027e38c3b37840175ce0/txaws/ec2/client.py#L1099-L1105
def old_signing_text(self): """Return the text needed for signing using SignatureVersion 1.""" result = [] lower_cmp = lambda x, y: cmp(x[0].lower(), y[0].lower()) for key, value in sorted(self.params.items(), cmp=lower_cmp): result.append("%s%s" % (key, value)) return "".join(result)
[ "def", "old_signing_text", "(", "self", ")", ":", "result", "=", "[", "]", "lower_cmp", "=", "lambda", "x", ",", "y", ":", "cmp", "(", "x", "[", "0", "]", ".", "lower", "(", ")", ",", "y", "[", "0", "]", ".", "lower", "(", ")", ")", "for", ...
Return the text needed for signing using SignatureVersion 1.
[ "Return", "the", "text", "needed", "for", "signing", "using", "SignatureVersion", "1", "." ]
python
train
raiden-network/raiden
raiden/api/python.py
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/api/python.py#L357-L447
def channel_open( self, registry_address: PaymentNetworkID, token_address: TokenAddress, partner_address: Address, settle_timeout: BlockTimeout = None, retry_timeout: NetworkTimeout = DEFAULT_RETRY_TIMEOUT, ) -> ChannelID: """ Open a channel with the peer at `partner_address` with the given `token_address`. """ if settle_timeout is None: settle_timeout = self.raiden.config['settle_timeout'] if settle_timeout < self.raiden.config['reveal_timeout'] * 2: raise InvalidSettleTimeout( 'settle_timeout can not be smaller than double the reveal_timeout', ) if not is_binary_address(registry_address): raise InvalidAddress('Expected binary address format for registry in channel open') if not is_binary_address(token_address): raise InvalidAddress('Expected binary address format for token in channel open') if not is_binary_address(partner_address): raise InvalidAddress('Expected binary address format for partner in channel open') chain_state = views.state_from_raiden(self.raiden) channel_state = views.get_channelstate_for( chain_state=chain_state, payment_network_id=registry_address, token_address=token_address, partner_address=partner_address, ) if channel_state: raise DuplicatedChannelError('Channel with given partner address already exists') registry = self.raiden.chain.token_network_registry(registry_address) token_network_address = registry.get_token_network(token_address) if token_network_address is None: raise TokenNotRegistered( 'Token network for token %s does not exist' % to_checksum_address(token_address), ) token_network = self.raiden.chain.token_network( registry.get_token_network(token_address), ) with self.raiden.gas_reserve_lock: has_enough_reserve, estimated_required_reserve = has_enough_gas_reserve( self.raiden, channels_to_open=1, ) if not has_enough_reserve: raise InsufficientGasReserve(( 'The account balance is below the estimated amount necessary to ' 'finish the lifecycles of all active channels. A balance of at ' f'least {estimated_required_reserve} wei is required.' )) try: token_network.new_netting_channel( partner=partner_address, settle_timeout=settle_timeout, given_block_identifier=views.state_from_raiden(self.raiden).block_hash, ) except DuplicatedChannelError: log.info('partner opened channel first') waiting.wait_for_newchannel( raiden=self.raiden, payment_network_id=registry_address, token_address=token_address, partner_address=partner_address, retry_timeout=retry_timeout, ) chain_state = views.state_from_raiden(self.raiden) channel_state = views.get_channelstate_for( chain_state=chain_state, payment_network_id=registry_address, token_address=token_address, partner_address=partner_address, ) assert channel_state, f'channel {channel_state} is gone' return channel_state.identifier
[ "def", "channel_open", "(", "self", ",", "registry_address", ":", "PaymentNetworkID", ",", "token_address", ":", "TokenAddress", ",", "partner_address", ":", "Address", ",", "settle_timeout", ":", "BlockTimeout", "=", "None", ",", "retry_timeout", ":", "NetworkTimeo...
Open a channel with the peer at `partner_address` with the given `token_address`.
[ "Open", "a", "channel", "with", "the", "peer", "at", "partner_address", "with", "the", "given", "token_address", "." ]
python
train
quantopian/zipline
zipline/data/minute_bars.py
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/minute_bars.py#L991-L1013
def _minutes_to_exclude(self): """ Calculate the minutes which should be excluded when a window occurs on days which had an early close, i.e. days where the close based on the regular period of minutes per day and the market close do not match. Returns ------- List of DatetimeIndex representing the minutes to exclude because of early closes. """ market_opens = self._market_opens.values.astype('datetime64[m]') market_closes = self._market_closes.values.astype('datetime64[m]') minutes_per_day = (market_closes - market_opens).astype(np.int64) early_indices = np.where( minutes_per_day != self._minutes_per_day - 1)[0] early_opens = self._market_opens[early_indices] early_closes = self._market_closes[early_indices] minutes = [(market_open, early_close) for market_open, early_close in zip(early_opens, early_closes)] return minutes
[ "def", "_minutes_to_exclude", "(", "self", ")", ":", "market_opens", "=", "self", ".", "_market_opens", ".", "values", ".", "astype", "(", "'datetime64[m]'", ")", "market_closes", "=", "self", ".", "_market_closes", ".", "values", ".", "astype", "(", "'datetim...
Calculate the minutes which should be excluded when a window occurs on days which had an early close, i.e. days where the close based on the regular period of minutes per day and the market close do not match. Returns ------- List of DatetimeIndex representing the minutes to exclude because of early closes.
[ "Calculate", "the", "minutes", "which", "should", "be", "excluded", "when", "a", "window", "occurs", "on", "days", "which", "had", "an", "early", "close", "i", ".", "e", ".", "days", "where", "the", "close", "based", "on", "the", "regular", "period", "of...
python
train
senaite/senaite.core
bika/lims/setuphandlers.py
https://github.com/senaite/senaite.core/blob/7602ce2ea2f9e81eb34e20ce17b98a3e70713f85/bika/lims/setuphandlers.py#L389-L407
def reindex_content_structure(portal): """Reindex contents generated by Generic Setup """ logger.info("*** Reindex content structure ***") def reindex(obj, recurse=False): # skip catalog tools etc. if api.is_object(obj): obj.reindexObject() if recurse and hasattr(aq_base(obj), "objectValues"): map(reindex, obj.objectValues()) setup = api.get_setup() setupitems = setup.objectValues() rootitems = portal.objectValues() for obj in itertools.chain(setupitems, rootitems): logger.info("Reindexing {}".format(repr(obj))) reindex(obj)
[ "def", "reindex_content_structure", "(", "portal", ")", ":", "logger", ".", "info", "(", "\"*** Reindex content structure ***\"", ")", "def", "reindex", "(", "obj", ",", "recurse", "=", "False", ")", ":", "# skip catalog tools etc.", "if", "api", ".", "is_object",...
Reindex contents generated by Generic Setup
[ "Reindex", "contents", "generated", "by", "Generic", "Setup" ]
python
train
inveniosoftware-contrib/json-merger
json_merger/contrib/inspirehep/match.py
https://github.com/inveniosoftware-contrib/json-merger/blob/adc6d372da018427e1db7b92424d3471e01a4118/json_merger/contrib/inspirehep/match.py#L79-L138
def _match_by_norm_func(l1, l2, norm_fn, dist_fn, thresh): """Matches elements in l1 and l2 using normalization functions. Splits the elements in each list into buckets given by the normalization function. If the same normalization value points to a bucket from the first list and a bucket from the second list, both with a single element we consider the elements in the list as matching if the distance between them is less (or equal) than the threshold. e.g. l1 = ['X1', 'Y1', 'Y2', 'Z5'], l2 = ['X1', 'Y3', 'Z1'] norm_fn = lambda x: x[0] dist_fn = lambda e1, e2: 0 if e1 == e2 else 1 thresh = 0 The buckets will then be: l1_bucket = {'X': ['X1'], 'Y': ['Y1', 'Y2'], 'Z': ['Z5']} l2_bucket = {'X': ['X1'], 'Y': ['Y3'], 'Z': ['Z1']} For each normalized value: 'X' -> consider 'X1' equal with 'X1' since the distance is equal with the thershold 'Y' -> skip the lists since we have multiple possible matches 'Z' -> consider 'Z1' and 'Z5' as different since the distance is greater than the threshold. Return: [('X1', 'X2')] """ common = [] l1_only_idx = set(range(len(l1))) l2_only_idx = set(range(len(l2))) buckets_l1 = _group_by_fn(enumerate(l1), lambda x: norm_fn(x[1])) buckets_l2 = _group_by_fn(enumerate(l2), lambda x: norm_fn(x[1])) for normed, l1_elements in buckets_l1.items(): l2_elements = buckets_l2.get(normed, []) if not l1_elements or not l2_elements: continue _, (_, e1_first) = l1_elements[0] _, (_, e2_first) = l2_elements[0] match_is_ambiguous = not ( len(l1_elements) == len(l2_elements) and ( all(e2 == e2_first for (_, (_, e2)) in l2_elements) or all(e1 == e1_first for (_, (_, e1)) in l1_elements) ) ) if match_is_ambiguous: continue for (e1_idx, e1), (e2_idx, e2) in zip(l1_elements, l2_elements): if dist_fn(e1, e2) > thresh: continue l1_only_idx.remove(e1_idx) l2_only_idx.remove(e2_idx) common.append((e1, e2)) l1_only = [l1[i] for i in l1_only_idx] l2_only = [l2[i] for i in l2_only_idx] return common, l1_only, l2_only
[ "def", "_match_by_norm_func", "(", "l1", ",", "l2", ",", "norm_fn", ",", "dist_fn", ",", "thresh", ")", ":", "common", "=", "[", "]", "l1_only_idx", "=", "set", "(", "range", "(", "len", "(", "l1", ")", ")", ")", "l2_only_idx", "=", "set", "(", "ra...
Matches elements in l1 and l2 using normalization functions. Splits the elements in each list into buckets given by the normalization function. If the same normalization value points to a bucket from the first list and a bucket from the second list, both with a single element we consider the elements in the list as matching if the distance between them is less (or equal) than the threshold. e.g. l1 = ['X1', 'Y1', 'Y2', 'Z5'], l2 = ['X1', 'Y3', 'Z1'] norm_fn = lambda x: x[0] dist_fn = lambda e1, e2: 0 if e1 == e2 else 1 thresh = 0 The buckets will then be: l1_bucket = {'X': ['X1'], 'Y': ['Y1', 'Y2'], 'Z': ['Z5']} l2_bucket = {'X': ['X1'], 'Y': ['Y3'], 'Z': ['Z1']} For each normalized value: 'X' -> consider 'X1' equal with 'X1' since the distance is equal with the thershold 'Y' -> skip the lists since we have multiple possible matches 'Z' -> consider 'Z1' and 'Z5' as different since the distance is greater than the threshold. Return: [('X1', 'X2')]
[ "Matches", "elements", "in", "l1", "and", "l2", "using", "normalization", "functions", "." ]
python
train
materialsproject/pymatgen
pymatgen/analysis/chemenv/coordination_environments/coordination_geometries.py
https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/analysis/chemenv/coordination_environments/coordination_geometries.py#L700-L715
def edges(self, sites, permutation=None, input='sites'): """ Returns the list of edges of this coordination geometry. Each edge is given as a list of its end vertices coordinates. """ if input == 'sites': coords = [site.coords for site in sites] elif input == 'coords': coords = sites # if permutation is None: # coords = [site.coords for site in sites] # else: # coords = [sites[ii].coords for ii in permutation] if permutation is not None: coords = [coords[ii] for ii in permutation] return [[coords[ii] for ii in e] for e in self._edges]
[ "def", "edges", "(", "self", ",", "sites", ",", "permutation", "=", "None", ",", "input", "=", "'sites'", ")", ":", "if", "input", "==", "'sites'", ":", "coords", "=", "[", "site", ".", "coords", "for", "site", "in", "sites", "]", "elif", "input", ...
Returns the list of edges of this coordination geometry. Each edge is given as a list of its end vertices coordinates.
[ "Returns", "the", "list", "of", "edges", "of", "this", "coordination", "geometry", ".", "Each", "edge", "is", "given", "as", "a", "list", "of", "its", "end", "vertices", "coordinates", "." ]
python
train
spyder-ide/spyder
spyder/widgets/findreplace.py
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/widgets/findreplace.py#L251-L257
def toggle_highlighting(self, state): """Toggle the 'highlight all results' feature""" if self.editor is not None: if state: self.highlight_matches() else: self.clear_matches()
[ "def", "toggle_highlighting", "(", "self", ",", "state", ")", ":", "if", "self", ".", "editor", "is", "not", "None", ":", "if", "state", ":", "self", ".", "highlight_matches", "(", ")", "else", ":", "self", ".", "clear_matches", "(", ")" ]
Toggle the 'highlight all results' feature
[ "Toggle", "the", "highlight", "all", "results", "feature" ]
python
train
Azure/azure-storage-python
azure-storage-file/azure/storage/file/_deserialization.py
https://github.com/Azure/azure-storage-python/blob/52327354b192cbcf6b7905118ec6b5d57fa46275/azure-storage-file/azure/storage/file/_deserialization.py#L82-L142
def _convert_xml_to_shares(response): ''' <?xml version="1.0" encoding="utf-8"?> <EnumerationResults AccountName="https://myaccount.file.core.windows.net"> <Prefix>string-value</Prefix> <Marker>string-value</Marker> <MaxResults>int-value</MaxResults> <Shares> <Share> <Name>share-name</Name> <Snapshot>date-time-value</Snapshot> <Properties> <Last-Modified>date/time-value</Last-Modified> <Etag>etag</Etag> <Quota>max-share-size</Quota> </Properties> <Metadata> <metadata-name>value</metadata-name> </Metadata> </Share> </Shares> <NextMarker>marker-value</NextMarker> </EnumerationResults> ''' if response is None or response.body is None: return None shares = _list() list_element = ETree.fromstring(response.body) # Set next marker next_marker = list_element.findtext('NextMarker') or None setattr(shares, 'next_marker', next_marker) shares_element = list_element.find('Shares') for share_element in shares_element.findall('Share'): # Name element share = Share() share.name = share_element.findtext('Name') # Snapshot share.snapshot = share_element.findtext('Snapshot') # Metadata metadata_root_element = share_element.find('Metadata') if metadata_root_element is not None: share.metadata = dict() for metadata_element in metadata_root_element: share.metadata[metadata_element.tag] = metadata_element.text # Properties properties_element = share_element.find('Properties') share.properties.last_modified = parser.parse(properties_element.findtext('Last-Modified')) share.properties.etag = properties_element.findtext('Etag') share.properties.quota = int(properties_element.findtext('Quota')) # Add share to list shares.append(share) return shares
[ "def", "_convert_xml_to_shares", "(", "response", ")", ":", "if", "response", "is", "None", "or", "response", ".", "body", "is", "None", ":", "return", "None", "shares", "=", "_list", "(", ")", "list_element", "=", "ETree", ".", "fromstring", "(", "respons...
<?xml version="1.0" encoding="utf-8"?> <EnumerationResults AccountName="https://myaccount.file.core.windows.net"> <Prefix>string-value</Prefix> <Marker>string-value</Marker> <MaxResults>int-value</MaxResults> <Shares> <Share> <Name>share-name</Name> <Snapshot>date-time-value</Snapshot> <Properties> <Last-Modified>date/time-value</Last-Modified> <Etag>etag</Etag> <Quota>max-share-size</Quota> </Properties> <Metadata> <metadata-name>value</metadata-name> </Metadata> </Share> </Shares> <NextMarker>marker-value</NextMarker> </EnumerationResults>
[ "<?xml", "version", "=", "1", ".", "0", "encoding", "=", "utf", "-", "8", "?", ">", "<EnumerationResults", "AccountName", "=", "https", ":", "//", "myaccount", ".", "file", ".", "core", ".", "windows", ".", "net", ">", "<Prefix", ">", "string", "-", ...
python
train
wright-group/WrightTools
WrightTools/units.py
https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/units.py#L96-L135
def converter(val, current_unit, destination_unit): """Convert from one unit to another. Parameters ---------- val : number Number to convert. current_unit : string Current unit. destination_unit : string Destination unit. Returns ------- number Converted value. """ x = val for dic in dicts.values(): if current_unit in dic.keys() and destination_unit in dic.keys(): try: native = eval(dic[current_unit][0]) except ZeroDivisionError: native = np.inf x = native # noqa: F841 try: out = eval(dic[destination_unit][1]) except ZeroDivisionError: out = np.inf return out # if all dictionaries fail if current_unit is None and destination_unit is None: pass else: warnings.warn( "conversion {0} to {1} not valid: returning input".format( current_unit, destination_unit ) ) return val
[ "def", "converter", "(", "val", ",", "current_unit", ",", "destination_unit", ")", ":", "x", "=", "val", "for", "dic", "in", "dicts", ".", "values", "(", ")", ":", "if", "current_unit", "in", "dic", ".", "keys", "(", ")", "and", "destination_unit", "in...
Convert from one unit to another. Parameters ---------- val : number Number to convert. current_unit : string Current unit. destination_unit : string Destination unit. Returns ------- number Converted value.
[ "Convert", "from", "one", "unit", "to", "another", "." ]
python
train
michael-lazar/rtv
rtv/terminal.py
https://github.com/michael-lazar/rtv/blob/ccef2af042566ad384977028cf0bde01bc524dda/rtv/terminal.py#L414-L423
def get_link_page_text(link_page): """ Construct the dialog box to display a list of links to the user. """ text = '' for i, link in enumerate(link_page): capped_link_text = (link['text'] if len(link['text']) <= 20 else link['text'][:19] + '…') text += '[{}] [{}]({})\n'.format(i, capped_link_text, link['href']) return text
[ "def", "get_link_page_text", "(", "link_page", ")", ":", "text", "=", "''", "for", "i", ",", "link", "in", "enumerate", "(", "link_page", ")", ":", "capped_link_text", "=", "(", "link", "[", "'text'", "]", "if", "len", "(", "link", "[", "'text'", "]", ...
Construct the dialog box to display a list of links to the user.
[ "Construct", "the", "dialog", "box", "to", "display", "a", "list", "of", "links", "to", "the", "user", "." ]
python
train
gtaylor/EVE-Market-Data-Structures
emds/data_structures.py
https://github.com/gtaylor/EVE-Market-Data-Structures/blob/77d69b24f2aada3aeff8fba3d75891bfba8fdcf3/emds/data_structures.py#L474-L500
def set_empty_region(self, region_id, type_id, generated_at, error_if_entries_present=True): """ Prepares for the given region+item combo by instantiating a :py:class:`HistoryItemsInRegionList` instance, which will track region ID, type ID, and generated time. This is mostly used for the JSON deserialization process in case there are no orders for the given region+item combo. :param int region_id: The region ID. :param int type_id: The item's type ID. :param datetime.datetime generated_at: The time that the order set was generated. :keyword bool error_if_entries_present: If True, raise an exception if an entry already exists for this item+region combo when this is called. This failsafe may be disabled by passing False here. """ key = '%s_%s' % (region_id, type_id) if error_if_entries_present and self._history.has_key(key): raise ItemAlreadyPresentError( "Orders already exist for the given region and type ID. " "Pass error_if_orders_present=False to disable this failsafe, " "if desired." ) self._history[key] = HistoryItemsInRegionList( region_id, type_id, generated_at)
[ "def", "set_empty_region", "(", "self", ",", "region_id", ",", "type_id", ",", "generated_at", ",", "error_if_entries_present", "=", "True", ")", ":", "key", "=", "'%s_%s'", "%", "(", "region_id", ",", "type_id", ")", "if", "error_if_entries_present", "and", "...
Prepares for the given region+item combo by instantiating a :py:class:`HistoryItemsInRegionList` instance, which will track region ID, type ID, and generated time. This is mostly used for the JSON deserialization process in case there are no orders for the given region+item combo. :param int region_id: The region ID. :param int type_id: The item's type ID. :param datetime.datetime generated_at: The time that the order set was generated. :keyword bool error_if_entries_present: If True, raise an exception if an entry already exists for this item+region combo when this is called. This failsafe may be disabled by passing False here.
[ "Prepares", "for", "the", "given", "region", "+", "item", "combo", "by", "instantiating", "a", ":", "py", ":", "class", ":", "HistoryItemsInRegionList", "instance", "which", "will", "track", "region", "ID", "type", "ID", "and", "generated", "time", ".", "Thi...
python
train
projectshift/shift-boiler
boiler/timer/restart_timer.py
https://github.com/projectshift/shift-boiler/blob/8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b/boiler/timer/restart_timer.py#L6-L22
def time_restarts(data_path): """ When called will create a file and measure its mtime on restarts """ path = os.path.join(data_path, 'last_restarted') if not os.path.isfile(path): with open(path, 'a'): os.utime(path, None) last_modified = os.stat(path).st_mtime with open(path, 'a'): os.utime(path, None) now = os.stat(path).st_mtime dif = round(now - last_modified, 2) last_restart = datetime.fromtimestamp(now).strftime('%H:%M:%S') result = 'LAST RESTART WAS {} SECONDS AGO at {}'.format(dif, last_restart) print(style(fg='green', bg='red', text=result))
[ "def", "time_restarts", "(", "data_path", ")", ":", "path", "=", "os", ".", "path", ".", "join", "(", "data_path", ",", "'last_restarted'", ")", "if", "not", "os", ".", "path", ".", "isfile", "(", "path", ")", ":", "with", "open", "(", "path", ",", ...
When called will create a file and measure its mtime on restarts
[ "When", "called", "will", "create", "a", "file", "and", "measure", "its", "mtime", "on", "restarts" ]
python
train
PGower/PyCanvas
pycanvas/apis/modules.py
https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/modules.py#L19-L61
def list_modules(self, course_id, include=None, search_term=None, student_id=None): """ List modules. List the modules in a course """ path = {} data = {} params = {} # REQUIRED - PATH - course_id """ID""" path["course_id"] = course_id # OPTIONAL - include """- "items": Return module items inline if possible. This parameter suggests that Canvas return module items directly in the Module object JSON, to avoid having to make separate API requests for each module when enumerating modules and items. Canvas is free to omit 'items' for any particular module if it deems them too numerous to return inline. Callers must be prepared to use the {api:ContextModuleItemsApiController#index List Module Items API} if items are not returned. - "content_details": Requires include['items']. Returns additional details with module items specific to their associated content items. Includes standard lock information for each item.""" if include is not None: self._validate_enum(include, ["items", "content_details"]) params["include"] = include # OPTIONAL - search_term """The partial name of the modules (and module items, if include['items'] is specified) to match and return.""" if search_term is not None: params["search_term"] = search_term # OPTIONAL - student_id """Returns module completion information for the student with this id.""" if student_id is not None: params["student_id"] = student_id self.logger.debug("GET /api/v1/courses/{course_id}/modules with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("GET", "/api/v1/courses/{course_id}/modules".format(**path), data=data, params=params, all_pages=True)
[ "def", "list_modules", "(", "self", ",", "course_id", ",", "include", "=", "None", ",", "search_term", "=", "None", ",", "student_id", "=", "None", ")", ":", "path", "=", "{", "}", "data", "=", "{", "}", "params", "=", "{", "}", "# REQUIRED - PATH - co...
List modules. List the modules in a course
[ "List", "modules", ".", "List", "the", "modules", "in", "a", "course" ]
python
train
clinicedc/edc-form-label
edc_form_label/custom_label_condition.py
https://github.com/clinicedc/edc-form-label/blob/9d90807ddf784045b3867d676bee6e384a8e9d71/edc_form_label/custom_label_condition.py#L64-L78
def previous_obj(self): """Returns a model obj that is the first occurrence of a previous obj relative to this object's appointment. Override this method if not am EDC subject model / CRF. """ previous_obj = None if self.previous_visit: try: previous_obj = self.model.objects.get( **{f"{self.model.visit_model_attr()}": self.previous_visit} ) except ObjectDoesNotExist: pass return previous_obj
[ "def", "previous_obj", "(", "self", ")", ":", "previous_obj", "=", "None", "if", "self", ".", "previous_visit", ":", "try", ":", "previous_obj", "=", "self", ".", "model", ".", "objects", ".", "get", "(", "*", "*", "{", "f\"{self.model.visit_model_attr()}\""...
Returns a model obj that is the first occurrence of a previous obj relative to this object's appointment. Override this method if not am EDC subject model / CRF.
[ "Returns", "a", "model", "obj", "that", "is", "the", "first", "occurrence", "of", "a", "previous", "obj", "relative", "to", "this", "object", "s", "appointment", "." ]
python
train
mswart/pyopenmensa
feed.py
https://github.com/mswart/pyopenmensa/blob/c651da6ace33e2278349636daaa709d043dee6ff/feed.py#L627-L630
def setLegendData(self, *args, **kwargs): """ Set or genernate the legend data from this canteen. Uses :py:func:`.buildLegend` for genernating """ self.legendData = buildLegend(*args, key=self.legendKeyFunc, **kwargs)
[ "def", "setLegendData", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "legendData", "=", "buildLegend", "(", "*", "args", ",", "key", "=", "self", ".", "legendKeyFunc", ",", "*", "*", "kwargs", ")" ]
Set or genernate the legend data from this canteen. Uses :py:func:`.buildLegend` for genernating
[ "Set", "or", "genernate", "the", "legend", "data", "from", "this", "canteen", ".", "Uses", ":", "py", ":", "func", ":", ".", "buildLegend", "for", "genernating" ]
python
train
ncclient/ncclient
ncclient/xml_.py
https://github.com/ncclient/ncclient/blob/2b75f2c6a06bd2a5d1be67b01bb65c5ffd2e2d7a/ncclient/xml_.py#L116-L123
def parse_root(raw): "Efficiently parses the root element of a *raw* XML document, returning a tuple of its qualified name and attribute dictionary." if sys.version < '3': fp = StringIO(raw) else: fp = BytesIO(raw.encode('UTF-8')) for event, element in etree.iterparse(fp, events=('start',)): return (element.tag, element.attrib)
[ "def", "parse_root", "(", "raw", ")", ":", "if", "sys", ".", "version", "<", "'3'", ":", "fp", "=", "StringIO", "(", "raw", ")", "else", ":", "fp", "=", "BytesIO", "(", "raw", ".", "encode", "(", "'UTF-8'", ")", ")", "for", "event", ",", "element...
Efficiently parses the root element of a *raw* XML document, returning a tuple of its qualified name and attribute dictionary.
[ "Efficiently", "parses", "the", "root", "element", "of", "a", "*", "raw", "*", "XML", "document", "returning", "a", "tuple", "of", "its", "qualified", "name", "and", "attribute", "dictionary", "." ]
python
train
matllubos/django-is-core
is_core/filters/default_filters.py
https://github.com/matllubos/django-is-core/blob/3f87ec56a814738683c732dce5f07e0328c2300d/is_core/filters/default_filters.py#L76-L87
def get_widget(self, request): """ Table view is not able to get form field from reverse relation. Therefore this widget returns similar form field as direct relation (ModelChoiceField). Because there is used "RestrictedSelectWidget" it is returned textarea or selectox with choices according to count objects in the queryset. """ return self._update_widget_choices( forms.ModelChoiceField( widget=RestrictedSelectWidget, queryset=self.field.related_model._default_manager.all() ).widget )
[ "def", "get_widget", "(", "self", ",", "request", ")", ":", "return", "self", ".", "_update_widget_choices", "(", "forms", ".", "ModelChoiceField", "(", "widget", "=", "RestrictedSelectWidget", ",", "queryset", "=", "self", ".", "field", ".", "related_model", ...
Table view is not able to get form field from reverse relation. Therefore this widget returns similar form field as direct relation (ModelChoiceField). Because there is used "RestrictedSelectWidget" it is returned textarea or selectox with choices according to count objects in the queryset.
[ "Table", "view", "is", "not", "able", "to", "get", "form", "field", "from", "reverse", "relation", ".", "Therefore", "this", "widget", "returns", "similar", "form", "field", "as", "direct", "relation", "(", "ModelChoiceField", ")", ".", "Because", "there", "...
python
train
DarkEnergySurvey/ugali
ugali/scratch/simulation/survey_selection_function.py
https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/scratch/simulation/survey_selection_function.py#L282-L371
def validateClassifier(self, cut_detect, cut_train, cut_geometry, y_pred): """ Make some diagnostic plots """ color = {'detect': 'Red', 'nondetect': 'Gold', 'why_not': 'none', 'actual': 'DodgerBlue', 'hsc': 'lime'} size = {'detect': 5, 'nondetect': 5, 'why_not': 35, 'actual': None, 'hsc': None} marker = {'detect': 'o', 'nondetect': 'o', 'why_not': 'o', 'actual': 's', 'hsc': 's'} alpha = {'detect': None, 'nondetect': None, 'why_not': None, 'actual': None, 'hsc': None} edgecolor = {'detect': None, 'nondetect': None, 'why_not': 'magenta', 'actual': 'black', 'hsc': 'black'} title = 'N_train = %i ; N_test = %i'%(len(cut_train),len(cut_test)) import matplotlib cmap = matplotlib.colors.ListedColormap(['Gold', 'Orange', 'DarkOrange', 'OrangeRed', 'Red']) pylab.figure() pylab.xscale('log') pylab.scatter(1.e3 * self.data_population['r_physical'][cut_train & cut_geometry], self.data_population['abs_mag'][cut_train & cut_geometry], c=cut_detect[cut_train & cut_geometry].astype(int), vmin=0., vmax=1., s=size['detect'], cmap=cmap, label=None) pylab.scatter(1.e3 * self.data_population['r_physical'][~cut_train & cut_geometry], self.data_population['abs_mag'][~cut_train & cut_geometry], c=y_pred, edgecolor='black', vmin=0., vmax=1., s=(3 * size['detect']), cmap=cmap, label=None) colorbar = pylab.colorbar() colorbar.set_label('ML Predicted Detection Probability') pylab.scatter(0., 0., s=(3 * size['detect']), c='none', edgecolor='black', label='Test') #pylab.scatter(1.e3 * r_physical_actual, abs_mag_actual, # c=color['actual'], s=size['actual'], marker=marker['actual'], edgecolor=edgecolor['actual'], alpha=alpha['actual'], label='Actual MW Satellites') #pylab.scatter(1.e3 * r_physical_actual[cut_hsc], abs_mag_actual[cut_hsc], # c=color['hsc'], s=size['hsc'], marker=marker['hsc'], edgecolor=edgecolor['hsc'], alpha=alpha['hsc'], label='Actual MW Satellites: HSC') pylab.xlim(1., 3.e3) pylab.ylim(6., -12.) pylab.xlabel('Half-light Radius (pc)') pylab.ylabel('M_V (mag)') pylab.legend(loc='upper left', markerscale=2) pylab.title(title) import ugali.utils.bayesian_efficiency # Replace with standalone util bins = np.linspace(0., 1., 10 + 1) centers = np.empty(len(bins) - 1) bin_prob = np.empty(len(bins) - 1) bin_prob_err_hi = np.empty(len(bins) - 1) bin_prob_err_lo = np.empty(len(bins) - 1) bin_counts = np.empty(len(bins) - 1) for ii in range(0, len(centers)): cut_bin = (y_pred > bins[ii]) & (y_pred < bins[ii + 1]) centers[ii] = np.mean(y_pred[cut_bin]) n_trials = np.sum(cut_bin) n_successes = np.sum(cut_detect[~cut_train & cut_geometry] & cut_bin) efficiency, errorbar = ugali.utils.bayesian_efficiency.bayesianInterval(n_trials, n_successes, errorbar=True) bin_prob[ii] = efficiency bin_prob_err_hi[ii] = errorbar[1] bin_prob_err_lo[ii] = errorbar[0] #bin_prob[ii] = float(np.sum(cut_detect[~cut_train] & cut_bin)) / np.sum(cut_bin) #bin_prob[ii] = np.mean(y[cut].astype(float)) bin_counts[ii] = np.sum(cut_bin) pylab.figure() pylab.plot([0., 1.], [0., 1.], c='black', ls='--') pylab.errorbar(centers, bin_prob, yerr=[bin_prob_err_lo, bin_prob_err_hi], c='red') pylab.plot(centers, bin_prob, c='red') pylab.scatter(centers, bin_prob, c=bin_counts, edgecolor='red', s=50, cmap='Reds', zorder=999) colorbar = pylab.colorbar() colorbar.set_label('Counts') pylab.xlabel('ML Predicted Detection Probability') pylab.ylabel('Fraction Detected') pylab.xlim(0., 1.) pylab.ylim(0., 1.) pylab.title(title)
[ "def", "validateClassifier", "(", "self", ",", "cut_detect", ",", "cut_train", ",", "cut_geometry", ",", "y_pred", ")", ":", "color", "=", "{", "'detect'", ":", "'Red'", ",", "'nondetect'", ":", "'Gold'", ",", "'why_not'", ":", "'none'", ",", "'actual'", "...
Make some diagnostic plots
[ "Make", "some", "diagnostic", "plots" ]
python
train
modin-project/modin
modin/experimental/engines/pandas_on_ray/sql.py
https://github.com/modin-project/modin/blob/5b77d242596560c646b8405340c9ce64acb183cb/modin/experimental/engines/pandas_on_ray/sql.py#L34-L46
def is_table(engine, sql): """ Check with the given sql arg is query or table Args: engine: SQLAlchemy connection engine sql: SQL query or table name Returns: True for table or False if not """ if engine.dialect.has_table(engine, sql): return True return False
[ "def", "is_table", "(", "engine", ",", "sql", ")", ":", "if", "engine", ".", "dialect", ".", "has_table", "(", "engine", ",", "sql", ")", ":", "return", "True", "return", "False" ]
Check with the given sql arg is query or table Args: engine: SQLAlchemy connection engine sql: SQL query or table name Returns: True for table or False if not
[ "Check", "with", "the", "given", "sql", "arg", "is", "query", "or", "table" ]
python
train
mattloper/chumpy
chumpy/ch.py
https://github.com/mattloper/chumpy/blob/a3cfdb1be3c8265c369c507b22f6f3f89414c772/chumpy/ch.py#L275-L280
def compute_dr_wrt(self,wrt): """Default method for objects that just contain a number or ndarray""" if wrt is self: # special base case return sp.eye(self.x.size, self.x.size) #return np.array([[1]]) return None
[ "def", "compute_dr_wrt", "(", "self", ",", "wrt", ")", ":", "if", "wrt", "is", "self", ":", "# special base case ", "return", "sp", ".", "eye", "(", "self", ".", "x", ".", "size", ",", "self", ".", "x", ".", "size", ")", "#return np.array([[1]])", "re...
Default method for objects that just contain a number or ndarray
[ "Default", "method", "for", "objects", "that", "just", "contain", "a", "number", "or", "ndarray" ]
python
train
ibis-project/ibis
ibis/mapd/client.py
https://github.com/ibis-project/ibis/blob/1e39a5fd9ef088b45c155e8a5f541767ee8ef2e7/ibis/mapd/client.py#L768-L781
def exists_table(self, name, database=None): """ Determine if the indicated table or view exists Parameters ---------- name : string database : string, default None Returns ------- if_exists : boolean """ return bool(self.list_tables(like=name, database=database))
[ "def", "exists_table", "(", "self", ",", "name", ",", "database", "=", "None", ")", ":", "return", "bool", "(", "self", ".", "list_tables", "(", "like", "=", "name", ",", "database", "=", "database", ")", ")" ]
Determine if the indicated table or view exists Parameters ---------- name : string database : string, default None Returns ------- if_exists : boolean
[ "Determine", "if", "the", "indicated", "table", "or", "view", "exists" ]
python
train
saltstack/salt
salt/modules/runit.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/runit.py#L690-L722
def remove(name): ''' Remove the service <name> from system. Returns ``True`` if operation is successful. The service will be also stopped. name the service's name CLI Example: .. code-block:: bash salt '*' service.remove <name> ''' if not enabled(name): return False svc_path = _service_path(name) if not os.path.islink(svc_path): log.error('%s is not a symlink: not removed', svc_path) return False if not stop(name): log.error('Failed to stop service %s', name) return False try: os.remove(svc_path) except IOError: log.error('Unable to remove symlink %s', svc_path) return False return True
[ "def", "remove", "(", "name", ")", ":", "if", "not", "enabled", "(", "name", ")", ":", "return", "False", "svc_path", "=", "_service_path", "(", "name", ")", "if", "not", "os", ".", "path", ".", "islink", "(", "svc_path", ")", ":", "log", ".", "err...
Remove the service <name> from system. Returns ``True`` if operation is successful. The service will be also stopped. name the service's name CLI Example: .. code-block:: bash salt '*' service.remove <name>
[ "Remove", "the", "service", "<name", ">", "from", "system", ".", "Returns", "True", "if", "operation", "is", "successful", ".", "The", "service", "will", "be", "also", "stopped", "." ]
python
train
Fizzadar/pyinfra
pyinfra/api/connectors/local.py
https://github.com/Fizzadar/pyinfra/blob/006f751f7db2e07d32522c0285160783de2feb79/pyinfra/api/connectors/local.py#L39-L110
def run_shell_command( state, host, command, get_pty=False, timeout=None, print_output=False, **command_kwargs ): ''' Execute a command on the local machine. Args: state (``pyinfra.api.State`` obj): state object for this command hostname (string): hostname of the target command (string): actual command to execute sudo (boolean): whether to wrap the command with sudo sudo_user (string): user to sudo to get_pty (boolean): whether to get a PTY before executing the command env (dict): envrionment variables to set timeout (int): timeout for this command to complete before erroring Returns: tuple: (exit_code, stdout, stderr) stdout and stderr are both lists of strings from each buffer. ''' command = make_command(command, **command_kwargs) logger.debug('--> Running command on localhost: {0}'.format(command)) if print_output: print('{0}>>> {1}'.format(host.print_prefix, command)) process = Popen(command, shell=True, stdout=PIPE, stderr=PIPE) # Iterate through outputs to get an exit status and generate desired list # output, done in two greenlets so stdout isn't printed before stderr. Not # attached to state.pool to avoid blocking it with 2x n-hosts greenlets. stdout_reader = gevent.spawn( read_buffer, process.stdout, print_output=print_output, print_func=lambda line: '{0}{1}'.format(host.print_prefix, line), ) stderr_reader = gevent.spawn( read_buffer, process.stderr, print_output=print_output, print_func=lambda line: '{0}{1}'.format( host.print_prefix, click.style(line, 'red'), ), ) # Wait on output, with our timeout (or None) greenlets = gevent.wait((stdout_reader, stderr_reader), timeout=timeout) # Timeout doesn't raise an exception, but gevent.wait returns the greenlets # which did complete. So if both haven't completed, we kill them and fail # with a timeout. if len(greenlets) != 2: stdout_reader.kill() stderr_reader.kill() raise timeout_error() # Read the buffers into a list of lines stdout = stdout_reader.get() stderr = stderr_reader.get() logger.debug('--> Waiting for exit status...') process.wait() # Close any open file descriptor process.stdout.close() logger.debug('--> Command exit status: {0}'.format(process.returncode)) return process.returncode == 0, stdout, stderr
[ "def", "run_shell_command", "(", "state", ",", "host", ",", "command", ",", "get_pty", "=", "False", ",", "timeout", "=", "None", ",", "print_output", "=", "False", ",", "*", "*", "command_kwargs", ")", ":", "command", "=", "make_command", "(", "command", ...
Execute a command on the local machine. Args: state (``pyinfra.api.State`` obj): state object for this command hostname (string): hostname of the target command (string): actual command to execute sudo (boolean): whether to wrap the command with sudo sudo_user (string): user to sudo to get_pty (boolean): whether to get a PTY before executing the command env (dict): envrionment variables to set timeout (int): timeout for this command to complete before erroring Returns: tuple: (exit_code, stdout, stderr) stdout and stderr are both lists of strings from each buffer.
[ "Execute", "a", "command", "on", "the", "local", "machine", "." ]
python
train
awslabs/serverless-application-model
samtranslator/model/api/api_generator.py
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/model/api/api_generator.py#L251-L281
def _add_auth(self): """ Add Auth configuration to the Swagger file, if necessary """ if not self.auth: return if self.auth and not self.definition_body: raise InvalidResourceException(self.logical_id, "Auth works only with inline Swagger specified in " "'DefinitionBody' property") # Make sure keys in the dict are recognized if not all(key in AuthProperties._fields for key in self.auth.keys()): raise InvalidResourceException( self.logical_id, "Invalid value for 'Auth' property") if not SwaggerEditor.is_valid(self.definition_body): raise InvalidResourceException(self.logical_id, "Unable to add Auth configuration because " "'DefinitionBody' does not contain a valid Swagger") swagger_editor = SwaggerEditor(self.definition_body) auth_properties = AuthProperties(**self.auth) authorizers = self._get_authorizers(auth_properties.Authorizers, auth_properties.DefaultAuthorizer) if authorizers: swagger_editor.add_authorizers(authorizers) self._set_default_authorizer(swagger_editor, authorizers, auth_properties.DefaultAuthorizer) # Assign the Swagger back to template self.definition_body = swagger_editor.swagger
[ "def", "_add_auth", "(", "self", ")", ":", "if", "not", "self", ".", "auth", ":", "return", "if", "self", ".", "auth", "and", "not", "self", ".", "definition_body", ":", "raise", "InvalidResourceException", "(", "self", ".", "logical_id", ",", "\"Auth work...
Add Auth configuration to the Swagger file, if necessary
[ "Add", "Auth", "configuration", "to", "the", "Swagger", "file", "if", "necessary" ]
python
train
saltstack/salt
salt/modules/chocolatey.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/chocolatey.py#L890-L945
def version(name, check_remote=False, source=None, pre_versions=False): ''' Instructs Chocolatey to check an installed package version, and optionally compare it to one available from a remote feed. Args: name (str): The name of the package to check. Required. check_remote (bool): Get the version number of the latest package from the remote feed. Default is False. source (str): Chocolatey repository (directory, share or remote URL feed) the package comes from. Defaults to the official Chocolatey feed. Default is None. pre_versions (bool): Include pre-release packages in comparison. Default is False. Returns: dict: A dictionary of currently installed software and versions CLI Example: .. code-block:: bash salt "*" chocolatey.version <package name> salt "*" chocolatey.version <package name> check_remote=True ''' installed = list_(narrow=name, local_only=True) installed = {k.lower(): v for k, v in installed.items()} packages = {} lower_name = name.lower() for pkg in installed: if lower_name in pkg.lower(): packages[pkg] = installed[pkg] if check_remote: available = list_(narrow=name, pre_versions=pre_versions, source=source) available = {k.lower(): v for k, v in available.items()} for pkg in packages: # Grab the current version from the package that was installed packages[pkg] = {'installed': installed[pkg]} # If there's a remote package available, then also include that # in the dictionary that we return. if pkg in available: packages[pkg]['available'] = available[pkg] continue return packages
[ "def", "version", "(", "name", ",", "check_remote", "=", "False", ",", "source", "=", "None", ",", "pre_versions", "=", "False", ")", ":", "installed", "=", "list_", "(", "narrow", "=", "name", ",", "local_only", "=", "True", ")", "installed", "=", "{"...
Instructs Chocolatey to check an installed package version, and optionally compare it to one available from a remote feed. Args: name (str): The name of the package to check. Required. check_remote (bool): Get the version number of the latest package from the remote feed. Default is False. source (str): Chocolatey repository (directory, share or remote URL feed) the package comes from. Defaults to the official Chocolatey feed. Default is None. pre_versions (bool): Include pre-release packages in comparison. Default is False. Returns: dict: A dictionary of currently installed software and versions CLI Example: .. code-block:: bash salt "*" chocolatey.version <package name> salt "*" chocolatey.version <package name> check_remote=True
[ "Instructs", "Chocolatey", "to", "check", "an", "installed", "package", "version", "and", "optionally", "compare", "it", "to", "one", "available", "from", "a", "remote", "feed", "." ]
python
train
bitshares/python-bitshares
bitsharesapi/bitsharesnoderpc.py
https://github.com/bitshares/python-bitshares/blob/8a3b5954a6abcaaff7c6a5c41d910e58eea3142f/bitsharesapi/bitsharesnoderpc.py#L30-L41
def get_network(self): """ Identify the connected network. This call returns a dictionary with keys chain_id, core_symbol and prefix """ props = self.get_chain_properties() chain_id = props["chain_id"] for k, v in known_chains.items(): if v["chain_id"] == chain_id: return v raise exceptions.UnknownNetworkException( "Connecting to unknown network (chain_id: {})!".format(props["chain_id"]) )
[ "def", "get_network", "(", "self", ")", ":", "props", "=", "self", ".", "get_chain_properties", "(", ")", "chain_id", "=", "props", "[", "\"chain_id\"", "]", "for", "k", ",", "v", "in", "known_chains", ".", "items", "(", ")", ":", "if", "v", "[", "\"...
Identify the connected network. This call returns a dictionary with keys chain_id, core_symbol and prefix
[ "Identify", "the", "connected", "network", ".", "This", "call", "returns", "a", "dictionary", "with", "keys", "chain_id", "core_symbol", "and", "prefix" ]
python
train
ShenggaoZhu/midict
midict/__init__.py
https://github.com/ShenggaoZhu/midict/blob/2fad2edcfb753035b443a70fe15852affae1b5bb/midict/__init__.py#L739-L830
def _MI_setitem(self, args, value): 'Separate __setitem__ function of MIMapping' indices = self.indices N = len(indices) empty = N == 0 if empty: # init the dict index1, key, index2, index1_last = MI_parse_args(self, args, allow_new=True) exist_names = [index1] item = [key] try: MI_check_index_name(index2) exist_names.append(index2) item.append(value) except TypeError: Nvalue, value = get_value_len(value) if len(index2) != Nvalue: raise ValueError( 'Number of keys (%s) based on argument %s does not match ' 'number of values (%s)' % (len(index2), index2, Nvalue)) exist_names.extend(index2) item.extend(value) if index1_last: exist_names = exist_names[1:] + exist_names[:1] item = item[1:] + item[:1] _MI_init(self, [item], exist_names) return index1, key, index2, item, old_value = MI_parse_args(self, args, allow_new=True) names = force_list(indices.keys()) is_new_key = item is None single = isinstance(index2, int) if single: index2_list = [index2] value = [value] old_value = [old_value] else: index2_list = index2 Nvalue, value = get_value_len(value) if len(index2_list) != Nvalue: raise ValueError('Number of keys (%s) based on argument %s does not match ' 'number of values (%s)' % (len(index2_list), index2, Nvalue)) if is_new_key: old_value = [None] * Nvalue # fake it # remove duplicate in index2_list index2_d = OrderedDict() for e, index in enumerate(index2_list): index2_d[index] = e # order of each unique index if len(index2_d) < len(index2_list): # exist duplicate indices idx = index2_d.values() index2_list = mget_list(index2_list, idx) value = mget_list(value, idx) old_value = mget_list(old_value, idx) # check duplicate values for i, v, old_v in zip(index2_list, value, old_value): # index2_list may contain index1; not allow duplicate value for index1 either if v in indices[i]: if is_new_key or v != old_v: raise ValueExistsError(v, i, names[i]) if is_new_key: if set(index2_list + [index1]) != set(range(N)): raise ValueError('Indices of the new item do not match existing indices') d = {} d[index1] = key # index2_list may also override index1 d.update(zip(index2_list, value)) values = [d[i] for i in range(N)] # reorder based on the indices key = values[0] val = values[1] if len(values) == 2 else values[1:] super(MIMapping, self).__setitem__(key, val) for i, v in zip(names[1:], values[1:]): indices[i][v] = key else: # not new key # import pdb;pdb.set_trace() key1 = item[0] item2 = list(item) # copy item first mset_list(item2, index2_list, value) # index2_list may also override index1 key2 = item2[0] val = item2[1] if len(item2) == 2 else item2[1:] if key1 == key2: super(MIMapping, self).__setitem__(key1, val) else: od_replace_key(self, key1, key2, val) for i, v_old, v_new in zip(names[1:], item[1:], item2[1:]): od_replace_key(indices[i], v_old, v_new, key2)
[ "def", "_MI_setitem", "(", "self", ",", "args", ",", "value", ")", ":", "indices", "=", "self", ".", "indices", "N", "=", "len", "(", "indices", ")", "empty", "=", "N", "==", "0", "if", "empty", ":", "# init the dict", "index1", ",", "key", ",", "i...
Separate __setitem__ function of MIMapping
[ "Separate", "__setitem__", "function", "of", "MIMapping" ]
python
train
petl-developers/petl
petl/util/misc.py
https://github.com/petl-developers/petl/blob/1d33ca055f7e04e0d28a772041c9fd30c8d415d6/petl/util/misc.py#L68-L90
def diffvalues(t1, t2, f): """ Return the difference between the values under the given field in the two tables, e.g.:: >>> import petl as etl >>> table1 = [['foo', 'bar'], ... ['a', 1], ... ['b', 3]] >>> table2 = [['bar', 'foo'], ... [1, 'a'], ... [3, 'c']] >>> add, sub = etl.diffvalues(table1, table2, 'foo') >>> add {'c'} >>> sub {'b'} """ t1v = set(values(t1, f)) t2v = set(values(t2, f)) return t2v - t1v, t1v - t2v
[ "def", "diffvalues", "(", "t1", ",", "t2", ",", "f", ")", ":", "t1v", "=", "set", "(", "values", "(", "t1", ",", "f", ")", ")", "t2v", "=", "set", "(", "values", "(", "t2", ",", "f", ")", ")", "return", "t2v", "-", "t1v", ",", "t1v", "-", ...
Return the difference between the values under the given field in the two tables, e.g.:: >>> import petl as etl >>> table1 = [['foo', 'bar'], ... ['a', 1], ... ['b', 3]] >>> table2 = [['bar', 'foo'], ... [1, 'a'], ... [3, 'c']] >>> add, sub = etl.diffvalues(table1, table2, 'foo') >>> add {'c'} >>> sub {'b'}
[ "Return", "the", "difference", "between", "the", "values", "under", "the", "given", "field", "in", "the", "two", "tables", "e", ".", "g", ".", "::" ]
python
train
linkedin/naarad
src/naarad/utils.py
https://github.com/linkedin/naarad/blob/261e2c0760fd6a6b0ee59064180bd8e3674311fe/src/naarad/utils.py#L671-L701
def detect_timestamp_format(timestamp): """ Given an input timestamp string, determine what format is it likely in. :param string timestamp: the timestamp string for which we need to determine format :return: best guess timestamp format """ time_formats = { 'epoch': re.compile(r'^[0-9]{10}$'), 'epoch_ms': re.compile(r'^[0-9]{13}$'), 'epoch_fraction': re.compile(r'^[0-9]{10}\.[0-9]{3,9}$'), '%Y-%m-%d %H:%M:%S': re.compile(r'^[0-9]{4}-[0-1][0-9]-[0-3][0-9] [0-2][0-9]:[0-5][0-9]:[0-5][0-9]$'), '%Y-%m-%dT%H:%M:%S': re.compile(r'^[0-9]{4}-[0-1][0-9]-[0-3][0-9]T[0-2][0-9]:[0-5][0-9]:[0-5][0-9]$'), '%Y-%m-%d_%H:%M:%S': re.compile(r'^[0-9]{4}-[0-1][0-9]-[0-3][0-9]_[0-2][0-9]:[0-5][0-9]:[0-5][0-9]$'), '%Y-%m-%d %H:%M:%S.%f': re.compile(r'^[0-9]{4}-[0-1][0-9]-[0-3][0-9] [0-2][0-9]:[0-5][0-9]:[0-5][0-9].[0-9]+$'), '%Y-%m-%dT%H:%M:%S.%f': re.compile(r'^[0-9]{4}-[0-1][0-9]-[0-3][0-9]T[0-2][0-9]:[0-5][0-9]:[0-5][0-9].[0-9]+$'), '%Y-%m-%d_%H:%M:%S.%f': re.compile(r'^[0-9]{4}-[0-1][0-9]-[0-3][0-9]_[0-2][0-9]:[0-5][0-9]:[0-5][0-9].[0-9]+$'), '%Y%m%d %H:%M:%S': re.compile(r'^[0-9]{4}[0-1][0-9][0-3][0-9] [0-2][0-9]:[0-5][0-9]:[0-5][0-9]$'), '%Y%m%dT%H:%M:%S': re.compile(r'^[0-9]{4}[0-1][0-9][0-3][0-9]T[0-2][0-9]:[0-5][0-9]:[0-5][0-9]$'), '%Y%m%d_%H:%M:%S': re.compile(r'^[0-9]{4}[0-1][0-9][0-3][0-9]_[0-2][0-9]:[0-5][0-9]:[0-5][0-9]$'), '%Y%m%d %H:%M:%S.%f': re.compile(r'^[0-9]{4}[0-1][0-9][0-3][0-9] [0-2][0-9]:[0-5][0-9]:[0-5][0-9].[0-9]+$'), '%Y%m%dT%H:%M:%S.%f': re.compile(r'^[0-9]{4}[0-1][0-9][0-3][0-9]T[0-2][0-9]:[0-5][0-9]:[0-5][0-9].[0-9]+$'), '%Y%m%d_%H:%M:%S.%f': re.compile(r'^[0-9]{4}[0-1][0-9][0-3][0-9]_[0-2][0-9]:[0-5][0-9]:[0-5][0-9].[0-9]+$'), '%H:%M:%S': re.compile(r'^[0-2][0-9]:[0-5][0-9]:[0-5][0-9]$'), '%H:%M:%S.%f': re.compile(r'^[0-2][0-9]:[0-5][0-9]:[0-5][0-9].[0-9]+$'), '%Y-%m-%dT%H:%M:%S.%f%z': re.compile(r'^[0-9]{4}-[0-1][0-9]-[0-3][0-9]T[0-2][0-9]:[0-5][0-9]:[0-5][0-9].[0-9]+[+-][0-9]{4}$') } for time_format in time_formats: if re.match(time_formats[time_format], timestamp): return time_format return 'unknown'
[ "def", "detect_timestamp_format", "(", "timestamp", ")", ":", "time_formats", "=", "{", "'epoch'", ":", "re", ".", "compile", "(", "r'^[0-9]{10}$'", ")", ",", "'epoch_ms'", ":", "re", ".", "compile", "(", "r'^[0-9]{13}$'", ")", ",", "'epoch_fraction'", ":", ...
Given an input timestamp string, determine what format is it likely in. :param string timestamp: the timestamp string for which we need to determine format :return: best guess timestamp format
[ "Given", "an", "input", "timestamp", "string", "determine", "what", "format", "is", "it", "likely", "in", "." ]
python
valid