{"SOURCE": "codesearchnet", "instruction": "How would you code a function in Python 3 to\nget attribute by name.", "response": "def get_attribute_by_name(el, name, default=None):\n \"\"\"Get attribute by name.\"\"\"\n\n value = default\n if el._is_xml:\n try:\n value = el.attrs[name]\n except KeyError:\n pass\n else:\n for k, v in el.attrs.items():\n if util.lower(k) == name:\n value = v\n break\n return value"}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef get_text(self, el, no_iframe=False):\n\n return ''.join(\n [node for node in self.get_descendants(el, tags=False, no_iframe=no_iframe) if self.is_content_string(node)]\n )", "response": "Get text from the element."}
{"SOURCE": "codesearchnet", "instruction": "How would you code a function in Python 3 to\nparse the input value.", "response": "def parse_value(cls, itype, value):\n \"\"\"Parse the input value.\"\"\"\n\n parsed = None\n if itype == \"date\":\n m = RE_DATE.match(value)\n if m:\n year = int(m.group('year'), 10)\n month = int(m.group('month'), 10)\n day = int(m.group('day'), 10)\n if cls.validate_year(year) and cls.validate_month(month) and cls.validate_day(year, month, day):\n parsed = (year, month, day)\n elif itype == \"month\":\n m = RE_MONTH.match(value)\n if m:\n year = int(m.group('year'), 10)\n month = int(m.group('month'), 10)\n if cls.validate_year(year) and cls.validate_month(month):\n parsed = (year, month)\n elif itype == \"week\":\n m = RE_WEEK.match(value)\n if m:\n year = int(m.group('year'), 10)\n week = int(m.group('week'), 10)\n if cls.validate_year(year) and cls.validate_week(year, week):\n parsed = (year, week)\n elif itype == \"time\":\n m = RE_TIME.match(value)\n if m:\n hour = int(m.group('hour'), 10)\n minutes = int(m.group('minutes'), 10)\n if cls.validate_hour(hour) and cls.validate_minutes(minutes):\n parsed = (hour, minutes)\n elif itype == \"datetime-local\":\n m = RE_DATETIME.match(value)\n if m:\n year = int(m.group('year'), 10)\n month = int(m.group('month'), 10)\n day = int(m.group('day'), 10)\n hour = int(m.group('hour'), 10)\n minutes = int(m.group('minutes'), 10)\n if (\n cls.validate_year(year) and cls.validate_month(month) and cls.validate_day(year, month, day) and\n cls.validate_hour(hour) and cls.validate_minutes(minutes)\n ):\n parsed = (year, month, day, hour, minutes)\n elif itype in (\"number\", \"range\"):\n m = RE_NUM.match(value)\n if m:\n parsed = float(m.group('value'))\n return parsed"}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef find_bidi(self, el):\n\n for node in self.get_children(el, tags=False):\n\n # Analyze child text nodes\n if self.is_tag(node):\n\n # Avoid analyzing certain elements specified in the specification.\n direction = DIR_MAP.get(util.lower(self.get_attribute_by_name(node, 'dir', '')), None)\n if (\n self.get_tag(node) in ('bdi', 'script', 'style', 'textarea', 'iframe') or\n not self.is_html_tag(node) or\n direction is not None\n ):\n continue # pragma: no cover\n\n # Check directionality of this node's text\n value = self.find_bidi(node)\n if value is not None:\n return value\n\n # Direction could not be determined\n continue # pragma: no cover\n\n # Skip `doctype` comments, etc.\n if self.is_special_string(node):\n continue\n\n # Analyze text nodes for directionality.\n for c in node:\n bidi = unicodedata.bidirectional(c)\n if bidi in ('AL', 'R', 'L'):\n return ct.SEL_DIR_LTR if bidi == 'L' else ct.SEL_DIR_RTL\n return None", "response": "Find the bidi of an element."}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function for\nmatching attribute name and return value if it exists.", "response": "def match_attribute_name(self, el, attr, prefix):\n \"\"\"Match attribute name and return value if it exists.\"\"\"\n\n value = None\n if self.supports_namespaces():\n value = None\n # If we have not defined namespaces, we can't very well find them, so don't bother trying.\n if prefix:\n ns = self.namespaces.get(prefix)\n if ns is None and prefix != '*':\n return None\n else:\n ns = None\n\n for k, v in self.iter_attributes(el):\n\n # Get attribute parts\n namespace, name = self.split_namespace(el, k)\n\n # Can't match a prefix attribute as we haven't specified one to match\n # Try to match it normally as a whole `p:a` as selector may be trying `p\\:a`.\n if ns is None:\n if (self.is_xml and attr == k) or (not self.is_xml and util.lower(attr) == util.lower(k)):\n value = v\n break\n # Coverage is not finding this even though it is executed.\n # Adding a print statement before this (and erasing coverage) causes coverage to find the line.\n # Ignore the false positive message.\n continue # pragma: no cover\n\n # We can't match our desired prefix attribute as the attribute doesn't have a prefix\n if namespace is None or ns != namespace and prefix != '*':\n continue\n\n # The attribute doesn't match.\n if (util.lower(attr) != util.lower(name)) if not self.is_xml else (attr != name):\n continue\n\n value = v\n break\n else:\n for k, v in self.iter_attributes(el):\n if util.lower(attr) != util.lower(k):\n continue\n value = v\n break\n return value"}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef match_namespace(self, el, tag):\n\n match = True\n namespace = self.get_tag_ns(el)\n default_namespace = self.namespaces.get('')\n tag_ns = '' if tag.prefix is None else self.namespaces.get(tag.prefix, None)\n # We must match the default namespace if one is not provided\n if tag.prefix is None and (default_namespace is not None and namespace != default_namespace):\n match = False\n # If we specified `|tag`, we must not have a namespace.\n elif (tag.prefix is not None and tag.prefix == '' and namespace):\n match = False\n # Verify prefix matches\n elif (\n tag.prefix and\n tag.prefix != '*' and (tag_ns is None or namespace != tag_ns)\n ):\n match = False\n return match", "response": "Match the namespace of the element."}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function to\nmatch relationship to other elements.", "response": "def match_relations(self, el, relation):\n \"\"\"Match relationship to other elements.\"\"\"\n\n found = False\n\n if relation[0].rel_type.startswith(':'):\n found = self.match_future_relations(el, relation)\n else:\n found = self.match_past_relations(el, relation)\n\n return found"}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef match_id(self, el, ids):\n\n found = True\n for i in ids:\n if i != self.get_attribute_by_name(el, 'id', ''):\n found = False\n break\n return found", "response": "Match element s ID."}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef match_classes(self, el, classes):\n\n current_classes = self.get_classes(el)\n found = True\n for c in classes:\n if c not in current_classes:\n found = False\n break\n return found", "response": "Match element s classes."}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef match_nth_tag_type(self, el, child):\n\n return(\n (self.get_tag(child) == self.get_tag(el)) and\n (self.get_tag_ns(child) == self.get_tag_ns(el))\n )", "response": "Match tag type for nth matches."}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef match_empty(self, el):\n\n is_empty = True\n for child in self.get_children(el, tags=False):\n if self.is_tag(child):\n is_empty = False\n break\n elif self.is_content_string(child) and RE_NOT_EMPTY.search(child):\n is_empty = False\n break\n return is_empty", "response": "Check if element is empty."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef match_contains(self, el, contains):\n\n match = True\n content = None\n for contain_list in contains:\n if content is None:\n content = self.get_text(el, no_iframe=self.is_html)\n found = False\n for text in contain_list.text:\n if text in content:\n found = True\n break\n if not found:\n match = False\n return match", "response": "Match element if it contains text."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function for\nmatching the input element with the default form.", "response": "def match_default(self, el):\n \"\"\"Match default.\"\"\"\n\n match = False\n\n # Find this input's form\n form = None\n parent = self.get_parent(el, no_iframe=True)\n while parent and form is None:\n if self.get_tag(parent) == 'form' and self.is_html_tag(parent):\n form = parent\n else:\n parent = self.get_parent(parent, no_iframe=True)\n\n # Look in form cache to see if we've already located its default button\n found_form = False\n for f, t in self.cached_default_forms:\n if f is form:\n found_form = True\n if t is el:\n match = True\n break\n\n # We didn't have the form cached, so look for its default button\n if not found_form:\n for child in self.get_descendants(form, no_iframe=True):\n name = self.get_tag(child)\n # Can't do nested forms (haven't figured out why we never hit this)\n if name == 'form': # pragma: no cover\n break\n if name in ('input', 'button'):\n v = self.get_attribute_by_name(child, 'type', '')\n if v and util.lower(v) == 'submit':\n self.cached_default_forms.append([form, child])\n if el is child:\n match = True\n break\n return match"}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef match_indeterminate(self, el):\n\n match = False\n name = self.get_attribute_by_name(el, 'name')\n\n def get_parent_form(el):\n \"\"\"Find this input's form.\"\"\"\n form = None\n parent = self.get_parent(el, no_iframe=True)\n while form is None:\n if self.get_tag(parent) == 'form' and self.is_html_tag(parent):\n form = parent\n break\n last_parent = parent\n parent = self.get_parent(parent, no_iframe=True)\n if parent is None:\n form = last_parent\n break\n return form\n\n form = get_parent_form(el)\n\n # Look in form cache to see if we've already evaluated that its fellow radio buttons are indeterminate\n found_form = False\n for f, n, i in self.cached_indeterminate_forms:\n if f is form and n == name:\n found_form = True\n if i is True:\n match = True\n break\n\n # We didn't have the form cached, so validate that the radio button is indeterminate\n if not found_form:\n checked = False\n for child in self.get_descendants(form, no_iframe=True):\n if child is el:\n continue\n tag_name = self.get_tag(child)\n if tag_name == 'input':\n is_radio = False\n check = False\n has_name = False\n for k, v in self.iter_attributes(child):\n if util.lower(k) == 'type' and util.lower(v) == 'radio':\n is_radio = True\n elif util.lower(k) == 'name' and v == name:\n has_name = True\n elif util.lower(k) == 'checked':\n check = True\n if is_radio and check and has_name and get_parent_form(child) is form:\n checked = True\n break\n if checked:\n break\n if not checked:\n match = True\n self.cached_indeterminate_forms.append([form, name, match])\n\n return match", "response": "Match an indeterminate form."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef match_dir(self, el, directionality):\n\n # If we have to match both left and right, we can't match either.\n if directionality & ct.SEL_DIR_LTR and directionality & ct.SEL_DIR_RTL:\n return False\n\n if el is None or not self.is_html_tag(el):\n return False\n\n # Element has defined direction of left to right or right to left\n direction = DIR_MAP.get(util.lower(self.get_attribute_by_name(el, 'dir', '')), None)\n if direction not in (None, 0):\n return direction == directionality\n\n # Element is the document element (the root) and no direction assigned, assume left to right.\n is_root = self.is_root(el)\n if is_root and direction is None:\n return ct.SEL_DIR_LTR == directionality\n\n # If `input[type=telephone]` and no direction is assigned, assume left to right.\n name = self.get_tag(el)\n is_input = name == 'input'\n is_textarea = name == 'textarea'\n is_bdi = name == 'bdi'\n itype = util.lower(self.get_attribute_by_name(el, 'type', '')) if is_input else ''\n if is_input and itype == 'tel' and direction is None:\n return ct.SEL_DIR_LTR == directionality\n\n # Auto handling for text inputs\n if ((is_input and itype in ('text', 'search', 'tel', 'url', 'email')) or is_textarea) and direction == 0:\n if is_textarea:\n value = []\n for node in self.get_contents(el, no_iframe=True):\n if self.is_content_string(node):\n value.append(node)\n value = ''.join(value)\n else:\n value = self.get_attribute_by_name(el, 'value', '')\n if value:\n for c in value:\n bidi = unicodedata.bidirectional(c)\n if bidi in ('AL', 'R', 'L'):\n direction = ct.SEL_DIR_LTR if bidi == 'L' else ct.SEL_DIR_RTL\n return direction == directionality\n # Assume left to right\n return ct.SEL_DIR_LTR == directionality\n elif is_root:\n return ct.SEL_DIR_LTR == directionality\n return self.match_dir(self.get_parent(el, no_iframe=True), directionality)\n\n # Auto handling for `bdi` and other non text inputs.\n if (is_bdi and direction is None) or direction == 0:\n direction = self.find_bidi(el)\n if direction is not None:\n return direction == directionality\n elif is_root:\n return ct.SEL_DIR_LTR == directionality\n return self.match_dir(self.get_parent(el, no_iframe=True), directionality)\n\n # Match parents direction\n return self.match_dir(self.get_parent(el, no_iframe=True), directionality)", "response": "Check if the element is in the given directionality."}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef match_range(self, el, condition):\n\n out_of_range = False\n\n itype = self.get_attribute_by_name(el, 'type').lower()\n mn = self.get_attribute_by_name(el, 'min', None)\n if mn is not None:\n mn = Inputs.parse_value(itype, mn)\n mx = self.get_attribute_by_name(el, 'max', None)\n if mx is not None:\n mx = Inputs.parse_value(itype, mx)\n\n # There is no valid min or max, so we cannot evaluate a range\n if mn is None and mx is None:\n return False\n\n value = self.get_attribute_by_name(el, 'value', None)\n if value is not None:\n value = Inputs.parse_value(itype, value)\n if value is not None:\n if itype in (\"date\", \"datetime-local\", \"month\", \"week\", \"number\", \"range\"):\n if mn is not None and value < mn:\n out_of_range = True\n if not out_of_range and mx is not None and value > mx:\n out_of_range = True\n elif itype == \"time\":\n if mn is not None and mx is not None and mn > mx:\n # Time is periodic, so this is a reversed/discontinuous range\n if value < mn and value > mx:\n out_of_range = True\n else:\n if mn is not None and value < mn:\n out_of_range = True\n if not out_of_range and mx is not None and value > mx:\n out_of_range = True\n\n return not out_of_range if condition & ct.SEL_IN_RANGE else out_of_range", "response": "Match the range of the elements in the element el."}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef match_defined(self, el):\n\n name = self.get_tag(el)\n return (\n name.find('-') == -1 or\n name.find(':') != -1 or\n self.get_prefix(el) is not None\n )", "response": "Match defined.\n\n `:defined` is related to custom elements in a browser.\n\n - If the document is XML (not XHTML), all tags will match.\n - Tags that are not custom (don't have a hyphen) are marked defined.\n - If the tag has a prefix (without or without a namespace), it will not match.\n\n This is of course requires the parser to provide us with the proper prefix and namespace info,\n if it doesn't, there is nothing we can do."}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef match_selectors(self, el, selectors):\n\n match = False\n is_not = selectors.is_not\n is_html = selectors.is_html\n\n # Internal selector lists that use the HTML flag, will automatically get the `html` namespace.\n if is_html:\n namespaces = self.namespaces\n iframe_restrict = self.iframe_restrict\n self.namespaces = {'html': NS_XHTML}\n self.iframe_restrict = True\n\n if not is_html or self.is_html:\n for selector in selectors:\n match = is_not\n # We have a un-matchable situation (like `:focus` as you can focus an element in this environment)\n if isinstance(selector, ct.SelectorNull):\n continue\n # Verify tag matches\n if not self.match_tag(el, selector.tag):\n continue\n # Verify tag is defined\n if selector.flags & ct.SEL_DEFINED and not self.match_defined(el):\n continue\n # Verify element is root\n if selector.flags & ct.SEL_ROOT and not self.match_root(el):\n continue\n # Verify element is scope\n if selector.flags & ct.SEL_SCOPE and not self.match_scope(el):\n continue\n # Verify `nth` matches\n if not self.match_nth(el, selector.nth):\n continue\n if selector.flags & ct.SEL_EMPTY and not self.match_empty(el):\n continue\n # Verify id matches\n if selector.ids and not self.match_id(el, selector.ids):\n continue\n # Verify classes match\n if selector.classes and not self.match_classes(el, selector.classes):\n continue\n # Verify attribute(s) match\n if not self.match_attributes(el, selector.attributes):\n continue\n # Verify ranges\n if selector.flags & RANGES and not self.match_range(el, selector.flags & RANGES):\n continue\n # Verify language patterns\n if selector.lang and not self.match_lang(el, selector.lang):\n continue\n # Verify pseudo selector patterns\n if selector.selectors and not self.match_subselectors(el, selector.selectors):\n continue\n # Verify relationship selectors\n if selector.relation and not self.match_relations(el, selector.relation):\n continue\n # Validate that the current default selector match corresponds to the first submit button in the form\n if selector.flags & ct.SEL_DEFAULT and not self.match_default(el):\n continue\n # Validate that the unset radio button is among radio buttons with the same name in a form that are\n # also not set.\n if selector.flags & ct.SEL_INDETERMINATE and not self.match_indeterminate(el):\n continue\n # Validate element directionality\n if selector.flags & DIR_FLAGS and not self.match_dir(el, selector.flags & DIR_FLAGS):\n continue\n # Validate that the tag contains the specified text.\n if not self.match_contains(el, selector.contains):\n continue\n match = not is_not\n break\n\n # Restore actual namespaces being used for external selector lists\n if is_html:\n self.namespaces = namespaces\n self.iframe_restrict = iframe_restrict\n\n return match", "response": "Check if element matches one of the selectors."}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function to\nmatch all tags under the targeted tag.", "response": "def select(self, limit=0):\n \"\"\"Match all tags under the targeted tag.\"\"\"\n\n if limit < 1:\n limit = None\n\n for child in self.get_descendants(self.tag):\n if self.match(child):\n yield child\n if limit is not None:\n limit -= 1\n if limit < 1:\n break"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef filter(self): # noqa A001\n\n return [tag for tag in self.get_contents(self.tag) if not self.is_navigable_string(tag) and self.match(tag)]", "response": "Filter tag s children."}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef match(self, tag):\n\n return CSSMatch(self.selectors, tag, self.namespaces, self.flags).match(tag)", "response": "Match the given tag."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef closest(self, tag):\n\n return CSSMatch(self.selectors, tag, self.namespaces, self.flags).closest()", "response": "Return the closest ancestor."}
{"SOURCE": "codesearchnet", "instruction": "Implement a Python 3 function for\nfiltering an iterable of nodes.", "response": "def filter(self, iterable): # noqa A001\n \"\"\"\n Filter.\n\n `CSSMatch` can cache certain searches for tags of the same document,\n so if we are given a tag, all tags are from the same document,\n and we can take advantage of the optimization.\n\n Any other kind of iterable could have tags from different documents or detached tags,\n so for those, we use a new `CSSMatch` for each item in the iterable.\n \"\"\"\n\n if CSSMatch.is_tag(iterable):\n return CSSMatch(self.selectors, iterable, self.namespaces, self.flags).filter()\n else:\n return [node for node in iterable if not CSSMatch.is_navigable_string(node) and self.match(node)]"}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function to\nselect a single tag.", "response": "def select_one(self, tag):\n \"\"\"Select a single tag.\"\"\"\n\n tags = self.select(tag, limit=1)\n return tags[0] if tags else None"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function that can\niterate the specified tags.", "response": "def iselect(self, tag, limit=0):\n \"\"\"Iterate the specified tags.\"\"\"\n\n for el in CSSMatch(self.selectors, tag, self.namespaces, self.flags).select(limit):\n yield el"}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef deprecated(message, stacklevel=2): # pragma: no cover\n\n def _decorator(func):\n @wraps(func)\n def _func(*args, **kwargs):\n warnings.warn(\n \"'{}' is deprecated. {}\".format(func.__name__, message),\n category=DeprecationWarning,\n stacklevel=stacklevel\n )\n return func(*args, **kwargs)\n return _func\n return _decorator", "response": "A decorator that marks a function as deprecated."}
{"SOURCE": "codesearchnet", "instruction": "Can you create a Python 3 function that\ngets the pattern context.", "response": "def get_pattern_context(pattern, index):\n \"\"\"Get the pattern context.\"\"\"\n\n last = 0\n current_line = 1\n col = 1\n text = []\n line = 1\n\n # Split pattern by newline and handle the text before the newline\n for m in RE_PATTERN_LINE_SPLIT.finditer(pattern):\n linetext = pattern[last:m.start(0)]\n if not len(m.group(0)) and not len(text):\n indent = ''\n offset = -1\n col = index - last + 1\n elif last <= index < m.end(0):\n indent = '--> '\n offset = (-1 if index > m.start(0) else 0) + 3\n col = index - last + 1\n else:\n indent = ' '\n offset = None\n if len(text):\n # Regardless of whether we are presented with `\\r\\n`, `\\r`, or `\\n`,\n # we will render the output with just `\\n`. We will still log the column\n # correctly though.\n text.append('\\n')\n text.append('{}{}'.format(indent, linetext))\n if offset is not None:\n text.append('\\n')\n text.append(' ' * (col + offset) + '^')\n line = current_line\n\n current_line += 1\n last = m.end(0)\n\n return ''.join(text), line, col"}
{"SOURCE": "codesearchnet", "instruction": "Implement a function in Python 3 to\nfilter list of nodes.", "response": "def filter(select, iterable, namespaces=None, flags=0, **kwargs): # noqa: A001\n \"\"\"Filter list of nodes.\"\"\"\n\n return compile(select, namespaces, flags, **kwargs).filter(iterable)"}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef select_one(select, tag, namespaces=None, flags=0, **kwargs):\n\n return compile(select, namespaces, flags, **kwargs).select_one(tag)", "response": "Select a single tag."}
{"SOURCE": "codesearchnet", "instruction": "Can you write a function in Python 3 where it\nselects the specified tags.", "response": "def select(select, tag, namespaces=None, limit=0, flags=0, **kwargs):\n \"\"\"Select the specified tags.\"\"\"\n\n return compile(select, namespaces, flags, **kwargs).select(tag, limit)"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef iselect(select, tag, namespaces=None, limit=0, flags=0, **kwargs):\n\n for el in compile(select, namespaces, flags, **kwargs).iselect(tag, limit):\n yield el", "response": "Iterate the specified tags."}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef all(cls, connection=None, **params):\n\n request = cls._make_request('GET', cls._get_all_path(), connection, params=params)\n return cls._create_object(request, connection=connection)", "response": "Returns a list of all the user s infrastructure."}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef iterall(cls, connection=None, **kwargs):\n\n try:\n limit = kwargs['limit']\n except KeyError:\n limit = None\n\n try:\n page = kwargs['page']\n except KeyError:\n page = None\n\n def _all_responses():\n page = 1 # one based\n params = kwargs.copy()\n\n while True:\n params.update(page=page, limit=250)\n rsp = cls._make_request('GET', cls._get_all_path(), connection, params=params)\n if rsp:\n yield rsp\n page += 1\n else:\n yield [] # needed for case where there is no objects\n break\n\n if not (limit or page):\n for rsp in _all_responses():\n for obj in rsp:\n yield cls._create_object(obj, connection=connection)\n\n else:\n response = cls._make_request('GET', cls._get_all_path(), connection, params=kwargs)\n for obj in cls._create_object(response, connection=connection):\n yield obj", "response": "Returns an autopaging generator that yields each object returned one by one."}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef get(self, resource=\"\", rid=None, **query):\n if rid:\n if resource[-1] != '/':\n resource += '/'\n resource += str(rid)\n response = self._run_method('GET', resource, query=query)\n return self._handle_response(resource, response)", "response": "Retrieves the resource with given id rid or all resources with given id rid or all resources with given id rid."}
{"SOURCE": "codesearchnet", "instruction": "Can you create a Python 3 function that\nupdates the resource with id rid with the given updates dictionary.", "response": "def update(self, resource, rid, updates):\n \"\"\"\n Updates the resource with id 'rid' with the given updates dictionary.\n \"\"\"\n if resource[-1] != '/':\n resource += '/'\n resource += str(rid)\n return self.put(resource, data=updates)"}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef delete(self, resource, rid=None): # note that rid can't be 0 - problem?\n if rid:\n if resource[-1] != '/':\n resource += '/'\n resource += str(rid)\n response = self._run_method('DELETE', resource)\n return self._handle_response(resource, response, suppress_empty=True)", "response": "Delete the resource with given id rid."}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef put(self, url, data):\n response = self._run_method('PUT', url, data=data)\n log.debug(\"OUTPUT: %s\" % response.content)\n return self._handle_response(url, response)", "response": "Make a PUT request to save data."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef post(self, url, data, headers={}):\n response = self._run_method('POST', url, data=data, headers=headers)\n return self._handle_response(url, response)", "response": "POST request for creating new objects."}
{"SOURCE": "codesearchnet", "instruction": "Implement a function in Python 3 to\nhandle the response from the server and returns the parsed JSON or raises an exception appropriately.", "response": "def _handle_response(self, url, res, suppress_empty=True):\n \"\"\"\n Returns parsed JSON or raises an exception appropriately.\n \"\"\"\n self._last_response = res\n result = {}\n if res.status_code in (200, 201, 202):\n try:\n result = res.json()\n except Exception as e: # json might be invalid, or store might be down\n e.message += \" (_handle_response failed to decode JSON: \" + str(res.content) + \")\"\n raise # TODO better exception\n elif res.status_code == 204 and not suppress_empty:\n raise EmptyResponseWarning(\"%d %s @ %s: %s\" % (res.status_code, res.reason, url, res.content), res)\n elif res.status_code >= 500:\n raise ServerException(\"%d %s @ %s: %s\" % (res.status_code, res.reason, url, res.content), res)\n elif res.status_code == 429:\n raise RateLimitingException(\"%d %s @ %s: %s\" % (res.status_code, res.reason, url, res.content), res)\n elif res.status_code >= 400:\n raise ClientRequestException(\"%d %s @ %s: %s\" % (res.status_code, res.reason, url, res.content), res)\n elif res.status_code >= 300:\n raise RedirectionException(\"%d %s @ %s: %s\" % (res.status_code, res.reason, url, res.content), res)\n return result"}
{"SOURCE": "codesearchnet", "instruction": "How would you implement a function in Python 3 that\nverifies that a signed payload is valid and return the user s data.", "response": "def verify_payload(signed_payload, client_secret):\n \"\"\"\n Given a signed payload (usually passed as parameter in a GET request to the app's load URL) and a client secret,\n authenticates the payload and returns the user's data, or False on fail.\n\n Uses constant-time str comparison to prevent vulnerability to timing attacks.\n \"\"\"\n encoded_json, encoded_hmac = signed_payload.split('.')\n dc_json = base64.b64decode(encoded_json)\n signature = base64.b64decode(encoded_hmac)\n expected_sig = hmac.new(client_secret.encode(), base64.b64decode(encoded_json), hashlib.sha256).hexdigest()\n authorised = hmac.compare_digest(signature, expected_sig.encode())\n return json.loads(dc_json.decode()) if authorised else False"}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function to\nfetch a token from given token_url and sets session headers for the session.", "response": "def fetch_token(self, client_secret, code, context, scope, redirect_uri,\n token_url='https://login.bigcommerce.com/oauth2/token'):\n \"\"\"\n Fetches a token from given token_url, using given parameters, and sets up session headers for\n future requests.\n redirect_uri should be the same as your callback URL.\n code, context, and scope should be passed as parameters to your callback URL on app installation.\n\n Raises HttpException on failure (same as Connection methods).\n \"\"\"\n res = self.post(token_url, {'client_id': self.client_id,\n 'client_secret': client_secret,\n 'code': code,\n 'context': context,\n 'scope': scope,\n 'grant_type': 'authorization_code',\n 'redirect_uri': redirect_uri},\n headers={'Content-Type': 'application/x-www-form-urlencoded'})\n self._session.headers.update(self._oauth_headers(self.client_id, res['access_token']))\n return res"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef _handle_response(self, url, res, suppress_empty=True):\n result = Connection._handle_response(self, url, res, suppress_empty)\n if 'X-Rate-Limit-Time-Reset-Ms' in res.headers:\n self.rate_limit = dict(ms_until_reset=int(res.headers['X-Rate-Limit-Time-Reset-Ms']),\n window_size_ms=int(res.headers['X-Rate-Limit-Time-Window-Ms']),\n requests_remaining=int(res.headers['X-Rate-Limit-Requests-Left']),\n requests_quota=int(res.headers['X-Rate-Limit-Requests-Quota']))\n if self.rate_limiting_management:\n if self.rate_limiting_management['min_requests_remaining'] >= self.rate_limit['requests_remaining']:\n if self.rate_limiting_management['wait']:\n sleep(ceil(float(self.rate_limit['ms_until_reset']) / 1000))\n if self.rate_limiting_management.get('callback_function'):\n callback = self.rate_limiting_management['callback_function']\n args_dict = self.rate_limiting_management.get('callback_args')\n if args_dict:\n callback(args_dict)\n else:\n callback()\n\n return result", "response": "Handles the response from the server."}
{"SOURCE": "codesearchnet", "instruction": "Can you implement a function in Python 3 that\nescapes a string of HTML.", "response": "def escape_html(text, escape_slash=False):\n \"\"\"\n Binding for Hoedown's HTML escaping function.\n\n The implementation is inspired by the OWASP XSS Prevention recommendations:\n\n .. code-block:: none\n\n & --> &\n < --> <\n > --> >\n \" --> "\n ' --> '\n / --> / when escape_slash is set to True\n\n .. versionadded:: 2.1.0\n \"\"\"\n byte_str = text.encode('utf-8')\n ob = lib.hoedown_buffer_new(OUNIT)\n lib.hoedown_escape_html(ob, byte_str, len(byte_str), int(escape_slash))\n\n try:\n return to_string(ob)\n finally:\n lib.hoedown_buffer_free(ob)"}
{"SOURCE": "codesearchnet", "instruction": "Implement a Python 3 function for\nconverting markdown text to HTML.", "response": "def html(text, extensions=0, render_flags=0):\n \"\"\"\n Convert markdown text to HTML.\n\n ``extensions`` can be a list or tuple of extensions (e.g.\n ``('fenced-code', 'footnotes', 'strikethrough')``) or an integer\n (e.g. ``EXT_FENCED_CODE | EXT_FOOTNOTES | EXT_STRIKETHROUGH``).\n\n ``render_flags`` can be a list or tuple of flags (e.g.\n ``('skip-html', 'hard-wrap')``) or an integer\n (e.g. ``HTML_SKIP_HTML | HTML_HARD_WRAP``).\n \"\"\"\n extensions = args_to_int(extension_map, extensions)\n render_flags = args_to_int(html_flag_map, render_flags)\n\n ib = lib.hoedown_buffer_new(IUNIT)\n ob = lib.hoedown_buffer_new(OUNIT)\n renderer = lib.hoedown_html_renderer_new(render_flags, 0)\n document = lib.hoedown_document_new(renderer, extensions, 16);\n\n lib.hoedown_buffer_puts(ib, text.encode('utf-8'))\n lib.hoedown_document_render(document, ob, ib.data, ib.size);\n lib.hoedown_buffer_free(ib);\n lib.hoedown_document_free(document);\n lib.hoedown_html_renderer_free(renderer);\n\n try:\n return to_string(ob)\n finally:\n lib.hoedown_buffer_free(ob);"}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef smartypants(text):\n byte_str = text.encode('utf-8')\n ob = lib.hoedown_buffer_new(OUNIT)\n lib.hoedown_html_smartypants(ob, byte_str, len(byte_str))\n\n try:\n return to_string(ob)\n finally:\n lib.hoedown_buffer_free(ob);", "response": "Returns a new node that can be used to render a string of text into HTML entities."}
{"SOURCE": "codesearchnet", "instruction": "Can you create a Python 3 function that\nfilters links generated by the autolink extension.", "response": "def autolink(self, raw_url, is_email):\n \"\"\"\n Filters links generated by the ``autolink`` extension.\n \"\"\"\n if self.check_url(raw_url):\n url = self.rewrite_url(('mailto:' if is_email else '') + raw_url)\n url = escape_html(url)\n return '%s' % (url, escape_html(raw_url))\n else:\n return escape_html('<%s>' % raw_url)"}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef image(self, raw_url, title='', alt=''):\n if self.check_url(raw_url, is_image_src=True):\n url = self.rewrite_url(raw_url, is_image_src=True)\n maybe_alt = ' alt=\"%s\"' % escape_html(alt) if alt else ''\n maybe_title = ' title=\"%s\"' % escape_html(title) if title else ''\n url = escape_html(url)\n return '' % (url, maybe_alt, maybe_title)\n else:\n return escape_html(\"\" % (alt, raw_url))", "response": "Returns an image tag with optional alt title and alt attributes."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef check_url(self, url, is_image_src=False):\n return bool(self._allowed_url_re.match(url))", "response": "Checks if the given URL is safe."}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef rewrite_url(self, url, is_image_src=False):\n rewrite = self.img_src_rewrite if is_image_src else self.link_rewrite\n if rewrite:\n return rewrite.format(url=urlquote(url))\n return url", "response": "This method is called to rewrite the URL. It returns the URL unchanged if the corresponding attribute is None."}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef args_to_int(mapping, argument):\n if isinstance(argument, int):\n if argument == 0:\n return 0\n deprecation('passing extensions and flags as constants is deprecated')\n return argument\n elif isinstance(argument, (tuple, list)):\n return reduce(op.or_, [mapping[n] for n in set(argument) if n in mapping], 0)\n raise TypeError('argument must be a list of strings or an int')", "response": "Convert list of strings to an int using a mapping."}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef _pack3(obj, fp, **options):\n global compatibility\n\n ext_handlers = options.get(\"ext_handlers\")\n\n if obj is None:\n _pack_nil(obj, fp, options)\n elif ext_handlers and obj.__class__ in ext_handlers:\n _pack_ext(ext_handlers[obj.__class__](obj), fp, options)\n elif isinstance(obj, bool):\n _pack_boolean(obj, fp, options)\n elif isinstance(obj, int):\n _pack_integer(obj, fp, options)\n elif isinstance(obj, float):\n _pack_float(obj, fp, options)\n elif compatibility and isinstance(obj, str):\n _pack_oldspec_raw(obj.encode('utf-8'), fp, options)\n elif compatibility and isinstance(obj, bytes):\n _pack_oldspec_raw(obj, fp, options)\n elif isinstance(obj, str):\n _pack_string(obj, fp, options)\n elif isinstance(obj, bytes):\n _pack_binary(obj, fp, options)\n elif isinstance(obj, (list, tuple)):\n _pack_array(obj, fp, options)\n elif isinstance(obj, dict):\n _pack_map(obj, fp, options)\n elif isinstance(obj, datetime.datetime):\n _pack_ext_timestamp(obj, fp, options)\n elif isinstance(obj, Ext):\n _pack_ext(obj, fp, options)\n elif ext_handlers:\n # Linear search for superclass\n t = next((t for t in ext_handlers.keys() if isinstance(obj, t)), None)\n if t:\n _pack_ext(ext_handlers[t](obj), fp, options)\n else:\n raise UnsupportedTypeException(\n \"unsupported type: %s\" % str(type(obj)))\n else:\n raise UnsupportedTypeException(\n \"unsupported type: %s\" % str(type(obj)))", "response": "Serializes a Python object into MessagePack bytes."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef _get_task_target():\n # Break circular dependency.\n # pylint: disable=g-import-not-at-top\n import pipeline\n if pipeline._TEST_MODE:\n return None\n\n # Further protect against test cases that doesn't set env vars\n # propertly.\n if (\"CURRENT_VERSION_ID\" not in os.environ or\n \"CURRENT_MODULE_ID\" not in os.environ):\n logging.warning(\"Running Pipeline in non TEST_MODE but important \"\n \"env vars are not set.\")\n return None\n\n version = os.environ[\"CURRENT_VERSION_ID\"].split(\".\")[0]\n module = os.environ[\"CURRENT_MODULE_ID\"]\n return \"%s.%s\" % (version, module)", "response": "Get the default target for a pipeline task."}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef for_name(fq_name, recursive=False):\n fq_name = str(fq_name)\n module_name = __name__\n short_name = fq_name\n\n if fq_name.rfind(\".\") >= 0:\n (module_name, short_name) = (fq_name[:fq_name.rfind(\".\")],\n fq_name[fq_name.rfind(\".\") + 1:])\n\n try:\n result = __import__(module_name, None, None, [short_name])\n return result.__dict__[short_name]\n except KeyError:\n # If we're recursively inside a for_name() chain, then we want to raise\n # this error as a key error so we can report the actual source of the\n # problem. If we're *not* recursively being called, that means the\n # module was found and the specific item could not be loaded, and thus\n # we want to raise an ImportError directly.\n if recursive:\n raise\n else:\n raise ImportError(\"Could not find '%s' on path '%s'\" % (\n short_name, module_name))\n except ImportError, e:\n # module_name is not actually a module. Try for_name for it to figure\n # out what's this.\n try:\n module = for_name(module_name, recursive=True)\n if hasattr(module, short_name):\n return getattr(module, short_name)\n else:\n # The module was found, but the function component is missing.\n raise KeyError()\n except KeyError:\n raise ImportError(\"Could not find '%s' on path '%s'\" % (\n short_name, module_name))\n except ImportError:\n # This means recursive import attempts failed, thus we will raise the\n # first ImportError we encountered, since it's likely the most accurate.\n pass\n # Raise the original import error that caused all of this, since it is\n # likely the real cause of the overall problem.\n raise", "response": "Find class or function or method specified by its fully qualified name."}
{"SOURCE": "codesearchnet", "instruction": "Implement a Python 3 function for\nreturning true if the object is a user - defined generator function.", "response": "def is_generator_function(obj):\n \"\"\"Return true if the object is a user-defined generator function.\n\n Generator function objects provides same attributes as functions.\n See isfunction.__doc__ for attributes listing.\n\n Adapted from Python 2.6.\n\n Args:\n obj: an object to test.\n\n Returns:\n true if the object is generator function.\n \"\"\"\n CO_GENERATOR = 0x20\n return bool(((inspect.isfunction(obj) or inspect.ismethod(obj)) and\n obj.func_code.co_flags & CO_GENERATOR))"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef _register_json_primitive(object_type, encoder, decoder):\n global _TYPE_TO_ENCODER\n global _TYPE_NAME_TO_DECODER\n if object_type not in _TYPE_TO_ENCODER:\n _TYPE_TO_ENCODER[object_type] = encoder\n _TYPE_NAME_TO_DECODER[object_type.__name__] = decoder", "response": "Extend what Pipeline can serialize."}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef _dict_to_obj(self, d):\n if JsonEncoder.TYPE_ID not in d:\n return d\n\n type_name = d.pop(JsonEncoder.TYPE_ID)\n if type_name in _TYPE_NAME_TO_DECODER:\n decoder = _TYPE_NAME_TO_DECODER[type_name]\n return decoder(d)\n else:\n raise TypeError(\"Invalid type %s.\", type_name)", "response": "Converts a dictionary of json object to a Python object."}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef _short_repr(obj):\n stringified = pprint.saferepr(obj)\n if len(stringified) > 200:\n return '%s... (%d bytes)' % (stringified[:200], len(stringified))\n return stringified", "response": "Helper function returns a truncated repr of an object."}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef _write_json_blob(encoded_value, pipeline_id=None):\n\n default_bucket = app_identity.get_default_gcs_bucket_name()\n if default_bucket is None:\n raise Exception(\n \"No default cloud storage bucket has been set for this application. \"\n \"This app was likely created before v1.9.0, please see: \"\n \"https://cloud.google.com/appengine/docs/php/googlestorage/setup\")\n\n path_components = ['/', default_bucket, \"appengine_pipeline\"]\n if pipeline_id:\n path_components.append(pipeline_id)\n path_components.append(uuid.uuid4().hex)\n # Use posixpath to get a / even if we're running on windows somehow\n file_name = posixpath.join(*path_components)\n with cloudstorage.open(file_name, 'w', content_type='application/json') as f:\n for start_index in xrange(0, len(encoded_value), _MAX_JSON_SIZE):\n end_index = start_index + _MAX_JSON_SIZE\n f.write(encoded_value[start_index:end_index])\n\n key_str = blobstore.create_gs_key(\"/gs\" + file_name)\n logging.debug(\"Created blob for filename = %s gs_key = %s\", file_name, key_str)\n return blobstore.BlobKey(key_str)", "response": "Writes a JSON encoded value to a Cloud Storage File."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef _dereference_args(pipeline_name, args, kwargs):\n lookup_slots = set()\n for arg in itertools.chain(args, kwargs.itervalues()):\n if arg['type'] == 'slot':\n lookup_slots.add(db.Key(arg['slot_key']))\n\n slot_dict = {}\n for key, slot_record in zip(lookup_slots, db.get(lookup_slots)):\n if slot_record is None or slot_record.status != _SlotRecord.FILLED:\n raise SlotNotFilledError(\n 'Slot \"%s\" missing its value. From %s(*args=%s, **kwargs=%s)' %\n (key, pipeline_name, _short_repr(args), _short_repr(kwargs)))\n slot_dict[key] = slot_record.value\n\n arg_list = []\n for current_arg in args:\n if current_arg['type'] == 'slot':\n arg_list.append(slot_dict[db.Key(current_arg['slot_key'])])\n elif current_arg['type'] == 'value':\n arg_list.append(current_arg['value'])\n else:\n raise UnexpectedPipelineError('Unknown parameter type: %r' % current_arg)\n\n kwarg_dict = {}\n for key, current_arg in kwargs.iteritems():\n if current_arg['type'] == 'slot':\n kwarg_dict[key] = slot_dict[db.Key(current_arg['slot_key'])]\n elif current_arg['type'] == 'value':\n kwarg_dict[key] = current_arg['value']\n else:\n raise UnexpectedPipelineError('Unknown parameter type: %r' % current_arg)\n\n return (arg_list, kwarg_dict)", "response": "Dereferences a Pipeline s arguments that are slots validating them."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef _generate_args(pipeline, future, queue_name, base_path):\n params = {\n 'args': [],\n 'kwargs': {},\n 'after_all': [],\n 'output_slots': {},\n 'class_path': pipeline._class_path,\n 'queue_name': queue_name,\n 'base_path': base_path,\n 'backoff_seconds': pipeline.backoff_seconds,\n 'backoff_factor': pipeline.backoff_factor,\n 'max_attempts': pipeline.max_attempts,\n 'task_retry': pipeline.task_retry,\n 'target': pipeline.target,\n }\n dependent_slots = set()\n\n arg_list = params['args']\n for current_arg in pipeline.args:\n if isinstance(current_arg, PipelineFuture):\n current_arg = current_arg.default\n if isinstance(current_arg, Slot):\n arg_list.append({'type': 'slot', 'slot_key': str(current_arg.key)})\n dependent_slots.add(current_arg.key)\n else:\n arg_list.append({'type': 'value', 'value': current_arg})\n\n kwarg_dict = params['kwargs']\n for name, current_arg in pipeline.kwargs.iteritems():\n if isinstance(current_arg, PipelineFuture):\n current_arg = current_arg.default\n if isinstance(current_arg, Slot):\n kwarg_dict[name] = {'type': 'slot', 'slot_key': str(current_arg.key)}\n dependent_slots.add(current_arg.key)\n else:\n kwarg_dict[name] = {'type': 'value', 'value': current_arg}\n\n after_all = params['after_all']\n for other_future in future._after_all_pipelines:\n slot_key = other_future._output_dict['default'].key\n after_all.append(str(slot_key))\n dependent_slots.add(slot_key)\n\n output_slots = params['output_slots']\n output_slot_keys = set()\n for name, slot in future._output_dict.iteritems():\n output_slot_keys.add(slot.key)\n output_slots[name] = str(slot.key)\n\n params_encoded = json.dumps(params, cls=mr_util.JsonEncoder)\n params_text = None\n params_blob = None\n if len(params_encoded) > _MAX_JSON_SIZE:\n params_blob = _write_json_blob(params_encoded, pipeline.pipeline_id)\n else:\n params_text = params_encoded\n\n return dependent_slots, output_slot_keys, params_text, params_blob", "response": "Generate the arguments needed to describe a Pipeline."}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef _get_timestamp_ms(when):\n if when is None:\n return None\n ms_since_epoch = float(time.mktime(when.utctimetuple()) * 1000.0)\n ms_since_epoch += when.microsecond / 1000.0\n return int(ms_since_epoch)", "response": "Converts a datetime. datetime instance to integer milliseconds since the epoch."}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef _get_internal_status(pipeline_key=None,\n pipeline_dict=None,\n slot_dict=None,\n barrier_dict=None,\n status_dict=None):\n \"\"\"Gets the UI dictionary of a pipeline from a set of status dictionaries.\n\n Args:\n pipeline_key: The key of the pipeline to lookup.\n pipeline_dict: Dictionary mapping pipeline db.Key to _PipelineRecord.\n Default is an empty dictionary.\n slot_dict: Dictionary mapping slot db.Key to _SlotRecord.\n Default is an empty dictionary.\n barrier_dict: Dictionary mapping barrier db.Key to _BarrierRecord.\n Default is an empty dictionary.\n status_dict: Dictionary mapping status record db.Key to _StatusRecord.\n Default is an empty dictionary.\n\n Returns:\n Dictionary with the keys:\n classPath: The pipeline function being run.\n args: List of positional argument slot dictionaries.\n kwargs: Dictionary of keyword argument slot dictionaries.\n outputs: Dictionary of output slot dictionaries.\n children: List of child pipeline IDs.\n queueName: Queue on which this pipeline is running.\n afterSlotKeys: List of Slot Ids after which this pipeline runs.\n currentAttempt: Number of the current attempt, starting at 1.\n maxAttempts: Maximum number of attempts before aborting.\n backoffSeconds: Constant factor for backoff before retrying.\n backoffFactor: Exponential factor for backoff before retrying.\n status: Current status of the pipeline.\n startTimeMs: When this pipeline ran or will run due to retries, if present.\n endTimeMs: When this pipeline finalized, if present.\n lastRetryMessage: Why the pipeline failed during the last retry, if there\n was a failure; may be empty.\n abortMessage: For root pipelines, why the pipeline was aborted if it was\n aborted; may be empty.\n\n Dictionary will contain these keys if explicit status is set:\n statusTimeMs: When the status was set as milliseconds since the epoch.\n statusMessage: Status message, if present.\n statusConsoleUrl: The relative URL for the console of this pipeline.\n statusLinks: Dictionary mapping human-readable names to relative URLs\n for related URLs to this pipeline.\n\n Raises:\n PipelineStatusError if any input is bad.\n \"\"\"\n if pipeline_dict is None:\n pipeline_dict = {}\n if slot_dict is None:\n slot_dict = {}\n if barrier_dict is None:\n barrier_dict = {}\n if status_dict is None:\n status_dict = {}\n\n pipeline_record = pipeline_dict.get(pipeline_key)\n if pipeline_record is None:\n raise PipelineStatusError(\n 'Could not find pipeline ID \"%s\"' % pipeline_key.name())\n\n params = pipeline_record.params\n root_pipeline_key = \\\n _PipelineRecord.root_pipeline.get_value_for_datastore(pipeline_record)\n default_slot_key = db.Key(params['output_slots']['default'])\n start_barrier_key = db.Key.from_path(\n _BarrierRecord.kind(), _BarrierRecord.START, parent=pipeline_key)\n finalize_barrier_key = db.Key.from_path(\n _BarrierRecord.kind(), _BarrierRecord.FINALIZE, parent=pipeline_key)\n status_record_key = db.Key.from_path(\n _StatusRecord.kind(), pipeline_key.name())\n\n start_barrier = barrier_dict.get(start_barrier_key)\n finalize_barrier = barrier_dict.get(finalize_barrier_key)\n default_slot = slot_dict.get(default_slot_key)\n status_record = status_dict.get(status_record_key)\n if finalize_barrier is None:\n raise PipelineStatusError(\n 'Finalization barrier missing for pipeline ID \"%s\"' %\n pipeline_key.name())\n if default_slot is None:\n raise PipelineStatusError(\n 'Default output slot with key=%s missing for pipeline ID \"%s\"' % (\n default_slot_key, pipeline_key.name()))\n\n output = {\n 'classPath': pipeline_record.class_path,\n 'args': list(params['args']),\n 'kwargs': params['kwargs'].copy(),\n 'outputs': params['output_slots'].copy(),\n 'children': [key.name() for key in pipeline_record.fanned_out],\n 'queueName': params['queue_name'],\n 'afterSlotKeys': [str(key) for key in params['after_all']],\n 'currentAttempt': pipeline_record.current_attempt + 1,\n 'maxAttempts': pipeline_record.max_attempts,\n 'backoffSeconds': pipeline_record.params['backoff_seconds'],\n 'backoffFactor': pipeline_record.params['backoff_factor'],\n }\n\n # TODO(user): Truncate args, kwargs, and outputs to < 1MB each so we\n # can reasonably return the whole tree of pipelines and their outputs.\n # Coerce each value to a string to truncate if necessary. For now if the\n # params are too big it will just cause the whole status page to break.\n\n # Fix the key names in parameters to match JavaScript style.\n for value_dict in itertools.chain(\n output['args'], output['kwargs'].itervalues()):\n if 'slot_key' in value_dict:\n value_dict['slotKey'] = value_dict.pop('slot_key')\n\n # Figure out the pipeline's status.\n if pipeline_record.status in (_PipelineRecord.WAITING, _PipelineRecord.RUN):\n if default_slot.status == _SlotRecord.FILLED:\n status = 'finalizing'\n elif (pipeline_record.status == _PipelineRecord.WAITING and\n pipeline_record.next_retry_time is not None):\n status = 'retry'\n elif start_barrier and start_barrier.status == _BarrierRecord.WAITING:\n # start_barrier will be missing for root pipelines\n status = 'waiting'\n else:\n status = 'run'\n elif pipeline_record.status == _PipelineRecord.DONE:\n status = 'done'\n elif pipeline_record.status == _PipelineRecord.ABORTED:\n status = 'aborted'\n\n output['status'] = status\n\n if status_record:\n output['statusTimeMs'] = _get_timestamp_ms(status_record.status_time)\n if status_record.message:\n output['statusMessage'] = status_record.message\n if status_record.console_url:\n output['statusConsoleUrl'] = status_record.console_url\n if status_record.link_names:\n output['statusLinks'] = dict(\n zip(status_record.link_names, status_record.link_urls))\n\n # Populate status-depenedent fields.\n if status in ('run', 'finalizing', 'done', 'retry'):\n if pipeline_record.next_retry_time is not None:\n output['startTimeMs'] = _get_timestamp_ms(pipeline_record.next_retry_time)\n elif start_barrier:\n # start_barrier will be missing for root pipelines\n output['startTimeMs'] = _get_timestamp_ms(start_barrier.trigger_time)\n elif pipeline_record.start_time:\n # Assume this pipeline ran immediately upon spawning with no\n # start barrier or it's the root pipeline.\n output['startTimeMs'] = _get_timestamp_ms(pipeline_record.start_time)\n\n if status in ('finalizing',):\n output['endTimeMs'] = _get_timestamp_ms(default_slot.fill_time)\n\n if status in ('done',):\n output['endTimeMs'] = _get_timestamp_ms(pipeline_record.finalized_time)\n\n if pipeline_record.next_retry_time is not None:\n output['lastRetryMessage'] = pipeline_record.retry_message\n\n if pipeline_record.abort_message:\n output['abortMessage'] = pipeline_record.abort_message\n\n return output", "response": "Internal helper function for _get_pipeline_status."}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef _get_internal_slot(slot_key=None,\n filler_pipeline_key=None,\n slot_dict=None):\n \"\"\"Gets information about a _SlotRecord for display in UI.\n\n Args:\n slot_key: The db.Key of the slot to fetch.\n filler_pipeline_key: In the case the slot has not yet been filled, assume\n that the given db.Key (for a _PipelineRecord) will be the filler of\n the slot in the future.\n slot_dict: The slot JSON dictionary.\n\n Returns:\n Dictionary with the keys:\n status: Slot status: 'filled' or 'waiting'\n fillTimeMs: Time in milliseconds since the epoch of when it was filled.\n value: The current value of the slot, which is a slot's JSON dictionary.\n fillerPipelineId: The pipeline ID of what stage has or should fill\n this slot.\n\n Raises:\n PipelineStatusError if any input is bad.\n \"\"\"\n if slot_dict is None:\n slot_dict = {}\n\n slot_record = slot_dict.get(slot_key)\n if slot_record is None:\n raise PipelineStatusError(\n 'Could not find data for output slot key \"%s\".' % slot_key)\n\n output = {}\n if slot_record.status == _SlotRecord.FILLED:\n output['status'] = 'filled'\n output['fillTimeMs'] = _get_timestamp_ms(slot_record.fill_time)\n output['value'] = slot_record.value\n filler_pipeline_key = (\n _SlotRecord.filler.get_value_for_datastore(slot_record))\n else:\n output['status'] = 'waiting'\n\n if filler_pipeline_key:\n output['fillerPipelineId'] = filler_pipeline_key.name()\n\n return output", "response": "Returns a dictionary of _SlotRecord objects for display in UI."}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef get_status_tree(root_pipeline_id):\n root_pipeline_key = db.Key.from_path(_PipelineRecord.kind(), root_pipeline_id)\n root_pipeline_record = db.get(root_pipeline_key)\n if root_pipeline_record is None:\n raise PipelineStatusError(\n 'Could not find pipeline ID \"%s\"' % root_pipeline_id)\n\n # If the supplied root_pipeline_id is not actually the root pipeline that's\n # okay. We'll find the real root and override the value they passed in.\n actual_root_key = _PipelineRecord.root_pipeline.get_value_for_datastore(\n root_pipeline_record)\n if actual_root_key != root_pipeline_key:\n root_pipeline_key = actual_root_key\n root_pipeline_id = root_pipeline_key.id_or_name()\n root_pipeline_record = db.get(root_pipeline_key)\n if not root_pipeline_record:\n raise PipelineStatusError(\n 'Could not find pipeline ID \"%s\"' % root_pipeline_id)\n\n # Run all queries asynchronously.\n queries = {}\n for model in (_PipelineRecord, _SlotRecord, _BarrierRecord, _StatusRecord):\n queries[model] = model.all().filter(\n 'root_pipeline =', root_pipeline_key).run(batch_size=1000)\n\n found_pipeline_dict = dict(\n (stage.key(), stage) for stage in queries[_PipelineRecord])\n found_slot_dict = dict(\n (slot.key(), slot) for slot in queries[_SlotRecord])\n found_barrier_dict = dict(\n (barrier.key(), barrier) for barrier in queries[_BarrierRecord])\n found_status_dict = dict(\n (status.key(), status) for status in queries[_StatusRecord])\n\n # Breadth-first traversal of _PipelineRecord instances by following\n # _PipelineRecord.fanned_out property values.\n valid_pipeline_keys = set([root_pipeline_key])\n slot_filler_dict = {} # slot_key to pipeline_key\n expand_stack = [root_pipeline_record]\n while expand_stack:\n old_stack = expand_stack\n expand_stack = []\n for pipeline_record in old_stack:\n for child_pipeline_key in pipeline_record.fanned_out:\n # This will let us prune off those pipelines which were allocated in\n # the Datastore but were never run due to mid-flight task failures.\n child_pipeline_record = found_pipeline_dict.get(child_pipeline_key)\n if child_pipeline_record is None:\n raise PipelineStatusError(\n 'Pipeline ID \"%s\" points to child ID \"%s\" which does not exist.'\n % (pipeline_record.key().name(), child_pipeline_key.name()))\n expand_stack.append(child_pipeline_record)\n valid_pipeline_keys.add(child_pipeline_key)\n\n # Figure out the deepest pipeline that's responsible for outputting to\n # a particular _SlotRecord, so we can report which pipeline *should*\n # be the filler.\n child_outputs = child_pipeline_record.params['output_slots']\n for output_slot_key in child_outputs.itervalues():\n slot_filler_dict[db.Key(output_slot_key)] = child_pipeline_key\n\n output = {\n 'rootPipelineId': root_pipeline_id,\n 'slots': {},\n 'pipelines': {},\n }\n\n for pipeline_key in found_pipeline_dict.keys():\n if pipeline_key not in valid_pipeline_keys:\n continue\n output['pipelines'][pipeline_key.name()] = _get_internal_status(\n pipeline_key=pipeline_key,\n pipeline_dict=found_pipeline_dict,\n slot_dict=found_slot_dict,\n barrier_dict=found_barrier_dict,\n status_dict=found_status_dict)\n\n for slot_key, filler_pipeline_key in slot_filler_dict.iteritems():\n output['slots'][str(slot_key)] = _get_internal_slot(\n slot_key=slot_key,\n filler_pipeline_key=filler_pipeline_key,\n slot_dict=found_slot_dict)\n\n return output", "response": "Gets the full status tree of a pipeline."}
{"SOURCE": "codesearchnet", "instruction": "How would you code a function in Python 3 to\nreturn the class paths of all Pipelines defined in alphabetical order.", "response": "def get_pipeline_names():\n \"\"\"Returns the class paths of all Pipelines defined in alphabetical order.\"\"\"\n class_path_set = set()\n for cls in _PipelineMeta._all_classes:\n if cls.class_path is not None:\n class_path_set.add(cls.class_path)\n return sorted(class_path_set)"}
{"SOURCE": "codesearchnet", "instruction": "Can you create a Python 3 function that\nreturns a list of Pipelines with the given class_path and cursor.", "response": "def get_root_list(class_path=None, cursor=None, count=50):\n \"\"\"Gets a list root Pipelines.\n\n Args:\n class_path: Optional. If supplied, only return root Pipelines with the\n given class_path. By default all root pipelines are returned.\n cursor: Optional. When supplied, the cursor returned from the last call to\n get_root_list which indicates where to pick up.\n count: How many pipeline returns to return.\n\n Returns:\n Dictionary with the keys:\n pipelines: The list of Pipeline records in the same format as\n returned by get_status_tree, but with only the roots listed.\n cursor: Cursor to pass back to this function to resume the query. Will\n only be present if there is another page of results.\n\n Raises:\n PipelineStatusError if any input is bad.\n \"\"\"\n query = _PipelineRecord.all(cursor=cursor)\n if class_path:\n query.filter('class_path =', class_path)\n query.filter('is_root_pipeline =', True)\n query.order('-start_time')\n\n root_list = query.fetch(count)\n\n fetch_list = []\n for pipeline_record in root_list:\n fetch_list.append(db.Key(pipeline_record.params['output_slots']['default']))\n fetch_list.append(db.Key.from_path(\n _BarrierRecord.kind(), _BarrierRecord.FINALIZE,\n parent=pipeline_record.key()))\n fetch_list.append(db.Key.from_path(\n _StatusRecord.kind(), pipeline_record.key().name()))\n\n pipeline_dict = dict((stage.key(), stage) for stage in root_list)\n slot_dict = {}\n barrier_dict = {}\n status_dict = {}\n for entity in db.get(fetch_list):\n if isinstance(entity, _BarrierRecord):\n barrier_dict[entity.key()] = entity\n elif isinstance(entity, _SlotRecord):\n slot_dict[entity.key()] = entity\n elif isinstance(entity, _StatusRecord):\n status_dict[entity.key()] = entity\n\n results = []\n for pipeline_record in root_list:\n try:\n output = _get_internal_status(\n pipeline_record.key(),\n pipeline_dict=pipeline_dict,\n slot_dict=slot_dict,\n barrier_dict=barrier_dict,\n status_dict=status_dict)\n output['pipelineId'] = pipeline_record.key().name()\n results.append(output)\n except PipelineStatusError, e:\n output = {'status': e.message}\n output['classPath'] = ''\n output['pipelineId'] = pipeline_record.key().name()\n results.append(output)\n\n result_dict = {}\n cursor = query.cursor()\n query.with_cursor(cursor)\n if query.get(keys_only=True):\n result_dict.update(cursor=cursor)\n result_dict.update(pipelines=results)\n return result_dict"}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef create_handlers_map(prefix='.*'):\n return [\n (prefix + '/output', _BarrierHandler),\n (prefix + '/run', _PipelineHandler),\n (prefix + '/finalized', _PipelineHandler),\n (prefix + '/cleanup', _CleanupHandler),\n (prefix + '/abort', _PipelineHandler),\n (prefix + '/fanout', _FanoutHandler),\n (prefix + '/fanout_abort', _FanoutAbortHandler),\n (prefix + '/callback', _CallbackHandler),\n (prefix + '/rpc/tree', status_ui._TreeStatusHandler),\n (prefix + '/rpc/class_paths', status_ui._ClassPathListHandler),\n (prefix + '/rpc/list', status_ui._RootListHandler),\n (prefix + '(/.+)', status_ui._StatusUiHandler),\n ]", "response": "Create a new handlers map."}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function to\nreturn the current value of this slot.", "response": "def value(self):\n \"\"\"Returns the current value of this slot.\n\n Returns:\n The value of the slot (a serializable Python type).\n\n Raises:\n SlotNotFilledError if the value hasn't been filled yet.\n \"\"\"\n if not self.filled:\n raise SlotNotFilledError('Slot with name \"%s\", key \"%s\" not yet filled.'\n % (self.name, self.key))\n return self._value"}
{"SOURCE": "codesearchnet", "instruction": "Can you write a function in Python 3 where it\nreturns the pipeline ID that filled this slot s value.", "response": "def filler(self):\n \"\"\"Returns the pipeline ID that filled this slot's value.\n\n Returns:\n A string that is the pipeline ID.\n\n Raises:\n SlotNotFilledError if the value hasn't been filled yet.\n \"\"\"\n if not self.filled:\n raise SlotNotFilledError('Slot with name \"%s\", key \"%s\" not yet filled.'\n % (self.name, self.key))\n return self._filler_pipeline_key.name()"}
{"SOURCE": "codesearchnet", "instruction": "Implement a Python 3 function for\nreturning when the slot was filled.", "response": "def fill_datetime(self):\n \"\"\"Returns when the slot was filled.\n\n Returns:\n A datetime.datetime.\n\n Raises:\n SlotNotFilledError if the value hasn't been filled yet.\n \"\"\"\n if not self.filled:\n raise SlotNotFilledError('Slot with name \"%s\", key \"%s\" not yet filled.'\n % (self.name, self.key))\n return self._fill_datetime"}
{"SOURCE": "codesearchnet", "instruction": "Can you write a function in Python 3 where it\nsets the value of this slot based on its corresponding _SlotRecord.", "response": "def _set_value(self, slot_record):\n \"\"\"Sets the value of this slot based on its corresponding _SlotRecord.\n\n Does nothing if the slot has not yet been filled.\n\n Args:\n slot_record: The _SlotRecord containing this Slot's value.\n \"\"\"\n if slot_record.status == _SlotRecord.FILLED:\n self.filled = True\n self._filler_pipeline_key = _SlotRecord.filler.get_value_for_datastore(\n slot_record)\n self._fill_datetime = slot_record.fill_time\n self._value = slot_record.value"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef _inherit_outputs(self,\n pipeline_name,\n already_defined,\n resolve_outputs=False):\n \"\"\"Inherits outputs from a calling Pipeline.\n\n Args:\n pipeline_name: The Pipeline class name (used for debugging).\n already_defined: Maps output name to stringified db.Key (of _SlotRecords)\n of any exiting output slots to be inherited by this future.\n resolve_outputs: When True, this method will dereference all output slots\n before returning back to the caller, making those output slots' values\n available.\n\n Raises:\n UnexpectedPipelineError when resolve_outputs is True and any of the output\n slots could not be retrived from the Datastore.\n \"\"\"\n for name, slot_key in already_defined.iteritems():\n if not isinstance(slot_key, db.Key):\n slot_key = db.Key(slot_key)\n\n slot = self._output_dict.get(name)\n if slot is None:\n if self._strict:\n raise UnexpectedPipelineError(\n 'Inherited output named \"%s\" must be filled but '\n 'not declared for pipeline class \"%s\"' % (name, pipeline_name))\n else:\n self._output_dict[name] = Slot(name=name, slot_key=slot_key)\n else:\n slot.key = slot_key\n slot._exists = True\n\n if resolve_outputs:\n slot_key_dict = dict((s.key, s) for s in self._output_dict.itervalues())\n all_slots = db.get(slot_key_dict.keys())\n for slot, slot_record in zip(slot_key_dict.itervalues(), all_slots):\n if slot_record is None:\n raise UnexpectedPipelineError(\n 'Inherited output named \"%s\" for pipeline class \"%s\" is '\n 'missing its Slot in the datastore: \"%s\"' %\n (slot.name, pipeline_name, slot.key))\n slot = slot_key_dict[slot_record.key()]\n slot._set_value(slot_record)", "response": "Inherits outputs from a calling Pipeline."}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef from_id(cls, pipeline_id, resolve_outputs=True, _pipeline_record=None):\n pipeline_record = _pipeline_record\n\n # Support pipeline IDs and idempotence_keys that are not unicode.\n if not isinstance(pipeline_id, unicode):\n try:\n pipeline_id = pipeline_id.encode('utf-8')\n except UnicodeDecodeError:\n pipeline_id = hashlib.sha1(pipeline_id).hexdigest()\n\n pipeline_key = db.Key.from_path(_PipelineRecord.kind(), pipeline_id)\n\n if pipeline_record is None:\n pipeline_record = db.get(pipeline_key)\n if pipeline_record is None:\n return None\n\n try:\n pipeline_func_class = mr_util.for_name(pipeline_record.class_path)\n except ImportError, e:\n logging.warning('Tried to find Pipeline %s#%s, but class could '\n 'not be found. Using default Pipeline class instead.',\n pipeline_record.class_path, pipeline_id)\n pipeline_func_class = cls\n\n params = pipeline_record.params\n arg_list, kwarg_dict = _dereference_args(\n pipeline_record.class_path, params['args'], params['kwargs'])\n outputs = PipelineFuture(pipeline_func_class.output_names)\n outputs._inherit_outputs(\n pipeline_record.class_path,\n params['output_slots'],\n resolve_outputs=resolve_outputs)\n\n stage = pipeline_func_class(*arg_list, **kwarg_dict)\n stage.backoff_seconds = params['backoff_seconds']\n stage.backoff_factor = params['backoff_factor']\n stage.max_attempts = params['max_attempts']\n stage.task_retry = params['task_retry']\n stage.target = params.get('target') # May not be defined for old Pipelines\n stage._current_attempt = pipeline_record.current_attempt\n stage._set_values_internal(\n _PipelineContext('', params['queue_name'], params['base_path']),\n pipeline_key,\n _PipelineRecord.root_pipeline.get_value_for_datastore(pipeline_record),\n outputs,\n pipeline_record.status)\n return stage", "response": "Returns an instance corresponding to a Pipeline with the given ID."}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef start(self,\n idempotence_key='',\n queue_name='default',\n base_path='/_ah/pipeline',\n return_task=False,\n countdown=None,\n eta=None):\n \"\"\"Starts a new instance of this pipeline.\n\n Args:\n idempotence_key: The ID to use for this Pipeline and throughout its\n asynchronous workflow to ensure the operations are idempotent. If\n empty a starting key will be automatically assigned.\n queue_name: What queue this Pipeline's workflow should execute on.\n base_path: The relative URL path to where the Pipeline API is\n mounted for access by the taskqueue API or external requests.\n return_task: When True, a task to start this pipeline will be returned\n instead of submitted, allowing the caller to start off this pipeline\n as part of a separate transaction (potentially leaving this newly\n allocated pipeline's datastore entities in place if that separate\n transaction fails for any reason).\n countdown: Time in seconds into the future that this Task should execute.\n Defaults to zero.\n eta: A datetime.datetime specifying the absolute time at which the task\n should be executed. Must not be specified if 'countdown' is specified.\n This may be timezone-aware or timezone-naive. If None, defaults to now.\n For pull tasks, no worker will be able to lease this task before the\n time indicated by eta.\n\n Returns:\n A taskqueue.Task instance if return_task was True. This task will *not*\n have a name, thus to ensure reliable execution of your pipeline you\n should add() this task as part of a separate Datastore transaction.\n\n Raises:\n PipelineExistsError if the pipeline with the given idempotence key exists.\n PipelineSetupError if the pipeline could not start for any other reason.\n \"\"\"\n if not idempotence_key:\n idempotence_key = uuid.uuid4().hex\n elif not isinstance(idempotence_key, unicode):\n try:\n idempotence_key.encode('utf-8')\n except UnicodeDecodeError:\n idempotence_key = hashlib.sha1(idempotence_key).hexdigest()\n\n pipeline_key = db.Key.from_path(_PipelineRecord.kind(), idempotence_key)\n context = _PipelineContext('', queue_name, base_path)\n future = PipelineFuture(self.output_names, force_strict=True)\n try:\n self._set_values_internal(\n context, pipeline_key, pipeline_key, future, _PipelineRecord.WAITING)\n return context.start(\n self, return_task=return_task, countdown=countdown, eta=eta)\n except Error:\n # Pass through exceptions that originate in this module.\n raise\n except Exception, e:\n # Re-type any exceptions that were raised in dependent methods.\n raise PipelineSetupError('Error starting %s#%s: %s' % (\n self, idempotence_key, str(e)))", "response": "Starts a new taskqueue. Task instance for this pipeline."}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef retry(self, retry_message=''):\n if not self.async:\n raise UnexpectedPipelineError(\n 'May only call retry() method for asynchronous pipelines.')\n if self.try_cancel():\n self._context.transition_retry(self._pipeline_key, retry_message)\n return True\n else:\n return False", "response": "Forces a currently running asynchronous pipeline to retry."}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef abort(self, abort_message=''):\n # TODO: Use thread-local variable to enforce that this is not called\n # while a pipeline is executing in the current thread.\n if (self.async and self._root_pipeline_key == self._pipeline_key and\n not self.try_cancel()):\n # Handle the special case where the root pipeline is async and thus\n # cannot be aborted outright.\n return False\n else:\n return self._context.begin_abort(\n self._root_pipeline_key, abort_message=abort_message)", "response": "Mark the entire pipeline up to the root as aborted."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function that can\nfill an output slot required by this Pipeline.", "response": "def fill(self, name_or_slot, value):\n \"\"\"Fills an output slot required by this Pipeline.\n\n Args:\n name_or_slot: The name of the slot (a string) or Slot record to fill.\n value: The serializable value to assign to this slot.\n\n Raises:\n UnexpectedPipelineError if the Slot no longer exists. SlotNotDeclaredError\n if trying to output to a slot that was not declared ahead of time.\n \"\"\"\n if isinstance(name_or_slot, basestring):\n slot = getattr(self.outputs, name_or_slot)\n elif isinstance(name_or_slot, Slot):\n slot = name_or_slot\n else:\n raise UnexpectedPipelineError(\n 'Could not fill invalid output name: %r' % name_or_slot)\n\n if not slot._exists:\n raise SlotNotDeclaredError(\n 'Cannot fill output with name \"%s\" that was just '\n 'declared within the Pipeline context.' % slot.name)\n\n self._context.fill_slot(self._pipeline_key, slot, value)"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function that can\nset the current status of this pipeline.", "response": "def set_status(self, message=None, console_url=None, status_links=None):\n \"\"\"Sets the current status of this pipeline.\n\n This method is purposefully non-transactional. Updates are written to the\n datastore immediately and overwrite all existing statuses.\n\n Args:\n message: (optional) Overall status message.\n console_url: (optional) Relative URL to use for the \"console\" of this\n pipeline that displays current progress. When None, no console will\n be displayed.\n status_links: (optional) Dictionary of readable link names to relative\n URLs that should be associated with this pipeline as it runs. These links\n provide convenient access to other dashboards, consoles, etc associated\n with the pipeline.\n\n Raises:\n PipelineRuntimeError if the status could not be set for any reason.\n \"\"\"\n if _TEST_MODE:\n logging.info(\n 'New status for %s#%s: message=%r, console_url=%r, status_links=%r',\n self, self.pipeline_id, message, console_url, status_links)\n return\n\n status_key = db.Key.from_path(_StatusRecord.kind(), self.pipeline_id)\n root_pipeline_key = db.Key.from_path(\n _PipelineRecord.kind(), self.root_pipeline_id)\n status_record = _StatusRecord(\n key=status_key, root_pipeline=root_pipeline_key)\n\n try:\n if message:\n status_record.message = message\n if console_url:\n status_record.console_url = console_url\n if status_links:\n # Alphabeticalize the list.\n status_record.link_names = sorted(\n db.Text(s) for s in status_links.iterkeys())\n status_record.link_urls = [\n db.Text(status_links[name]) for name in status_record.link_names]\n\n status_record.status_time = datetime.datetime.utcnow()\n\n status_record.put()\n except Exception, e:\n raise PipelineRuntimeError('Could not set status for %s#%s: %s' %\n (self, self.pipeline_id, str(e)))"}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function to\nmark this asynchronous Pipeline as complete.", "response": "def complete(self, default_output=None):\n \"\"\"Marks this asynchronous Pipeline as complete.\n\n Args:\n default_output: What value the 'default' output slot should be assigned.\n\n Raises:\n UnexpectedPipelineError if the slot no longer exists or this method was\n called for a pipeline that is not async.\n \"\"\"\n # TODO: Enforce that all outputs expected by this async pipeline were\n # filled before this complete() function was called. May required all\n # async functions to declare their outputs upfront.\n if not self.async:\n raise UnexpectedPipelineError(\n 'May only call complete() method for asynchronous pipelines.')\n self._context.fill_slot(\n self._pipeline_key, self.outputs.default, default_output)"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef get_callback_url(self, **kwargs):\n # TODO: Support positional parameters.\n if not self.async:\n raise UnexpectedPipelineError(\n 'May only call get_callback_url() method for asynchronous pipelines.')\n kwargs['pipeline_id'] = self._pipeline_key.name()\n params = urllib.urlencode(sorted(kwargs.items()))\n return '%s/callback?%s' % (self.base_path, params)", "response": "Returns a relative URL for invoking this Pipeline s callback method."}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function to\nreturn a task that will be executed when this Pipeline is executed.", "response": "def get_callback_task(self, *args, **kwargs):\n \"\"\"Returns a task for calling back this Pipeline.\n\n Args:\n params: Keyword argument containing a dictionary of key/value pairs\n that will be passed to the callback when it is executed.\n args, kwargs: Passed to the taskqueue.Task constructor. Use these\n arguments to set the task name (for idempotence), etc.\n\n Returns:\n A taskqueue.Task instance that must be enqueued by the caller.\n \"\"\"\n if not self.async:\n raise UnexpectedPipelineError(\n 'May only call get_callback_task() method for asynchronous pipelines.')\n\n params = kwargs.get('params', {})\n kwargs['params'] = params\n params['pipeline_id'] = self._pipeline_key.name()\n kwargs['url'] = self.base_path + '/callback'\n kwargs['method'] = 'POST'\n return taskqueue.Task(*args, **kwargs)"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function that can\nsend an email to admins that the pipeline has completed.", "response": "def send_result_email(self, sender=None):\n \"\"\"Sends an email to admins indicating this Pipeline has completed.\n\n For developer convenience. Automatically called from finalized for root\n Pipelines that do not override the default action.\n\n Args:\n sender: (optional) Override the sender's email address.\n \"\"\"\n status = 'successful'\n if self.was_aborted:\n status = 'aborted'\n\n app_id = os.environ['APPLICATION_ID']\n shard_index = app_id.find('~')\n if shard_index != -1:\n app_id = app_id[shard_index+1:]\n\n param_dict = {\n 'status': status,\n 'app_id': app_id,\n 'class_path': self._class_path,\n 'pipeline_id': self.root_pipeline_id,\n 'base_path': '%s.appspot.com%s' % (app_id, self.base_path),\n }\n subject = (\n 'Pipeline %(status)s: App \"%(app_id)s\", %(class_path)s'\n '#%(pipeline_id)s' % param_dict)\n body = \"\"\"View the pipeline results here:\n\nhttp://%(base_path)s/status?root=%(pipeline_id)s\n\nThanks,\n\nThe Pipeline API\n\"\"\" % param_dict\n\n html = \"\"\"
View the pipeline results here:
\n\nhttp://%(base_path)s/status?root=%(pipeline_id)s
\n\n\nThanks,\n
\nThe Pipeline API\n
%s' % (\n cgi.escape(openid_url), )\n self.render(msg, css_class='error', form_contents=openid_url)\n else:\n # Then, ask the library to begin the authorization.\n # Here we find out the identity server that will verify the\n # user's identity, and get a token that allows us to\n # communicate securely with the identity server.\n if use_sreg:\n self.requestRegistrationData(request)\n\n if use_pape:\n self.requestPAPEDetails(request)\n\n trust_root = self.server.base_url\n return_to = self.buildURL('process')\n if request.shouldSendRedirect():\n redirect_url = request.redirectURL(\n trust_root, return_to, immediate=immediate)\n self.send_response(302)\n self.send_header('Location', redirect_url)\n self.writeUserHeader()\n self.end_headers()\n else:\n form_html = request.htmlMarkup(\n trust_root,\n return_to,\n form_tag_attrs={'id': 'openid_message'},\n immediate=immediate)\n\n self.wfile.write(bytes(form_html, 'utf-8'))", "response": "This method is called by the OpenID server when the user is authorized to verify the user s identity."}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef buildURL(self, action, **query):\n base = urllib.parse.urljoin(self.server.base_url, action)\n return appendArgs(base, query)", "response": "Build a URL relative to the server base_url with the given action and query parameters added."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef answer(self, assoc):\n response = OpenIDResponse(self)\n response.fields.updateArgs(OPENID_NS, {\n 'expires_in': str(assoc.expiresIn),\n 'assoc_type': self.assoc_type,\n 'assoc_handle': assoc.handle,\n })\n response.fields.updateArgs(OPENID_NS,\n self.session.answer(assoc.secret))\n\n if not (self.session.session_type == 'no-encryption' and\n self.message.isOpenID1()):\n # The session type \"no-encryption\" did not have a name\n # in OpenID v1, it was just omitted.\n response.fields.setArg(OPENID_NS, 'session_type',\n self.session.session_type)\n\n return response", "response": "Respond to this request with an X { association."}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef whichEncoding(self):\n if self.request.mode in BROWSER_REQUEST_MODES:\n if self.fields.getOpenIDNamespace() == OPENID2_NS and \\\n len(self.encodeToURL()) > OPENID1_URL_LIMIT:\n return ENCODE_HTML_FORM\n else:\n return ENCODE_URL\n else:\n return ENCODE_KVFORM", "response": "How should I be encoded?"}
{"SOURCE": "codesearchnet", "instruction": "How would you implement a function in Python 3 that\ngenerates an unused auth level alias", "response": "def _generateAlias(self):\n \"\"\"Return an unused auth level alias\"\"\"\n for i in range(1000):\n alias = 'cust%d' % (i, )\n if alias not in self.auth_level_aliases:\n return alias\n\n raise RuntimeError('Could not find an unused alias (tried 1000!)')"}
{"SOURCE": "codesearchnet", "instruction": "How would you implement a function in Python 3 that\nreturns the alias for the specified auth level URI.", "response": "def _getAlias(self, auth_level_uri):\n \"\"\"Return the alias for the specified auth level URI.\n\n @raises KeyError: if no alias is defined\n \"\"\"\n for (alias, existing_uri) in self.auth_level_aliases.items():\n if auth_level_uri == existing_uri:\n return alias\n\n raise KeyError(auth_level_uri)"}
{"SOURCE": "codesearchnet", "instruction": "How would you implement a function in Python 3 that\ncreates a compound filter out of a list of filter - like things Used by mkFilter", "response": "def mkCompoundFilter(parts):\n \"\"\"Create a filter out of a list of filter-like things\n\n Used by mkFilter\n\n @param parts: list of filter, endpoint, callable or list of any of these\n \"\"\"\n # Separate into a list of callables and a list of filter objects\n transformers = []\n filters = []\n for subfilter in parts:\n try:\n subfilter = list(subfilter)\n except TypeError:\n # If it's not an iterable\n if hasattr(subfilter, 'getServiceEndpoints'):\n # It's a full filter\n filters.append(subfilter)\n elif hasattr(subfilter, 'fromBasicServiceEndpoint'):\n # It's an endpoint object, so put its endpoint\n # conversion attribute into the list of endpoint\n # transformers\n transformers.append(subfilter.fromBasicServiceEndpoint)\n elif isinstance(subfilter, collections.Callable):\n # It's a simple callable, so add it to the list of\n # endpoint transformers\n transformers.append(subfilter)\n else:\n raise filter_type_error\n else:\n filters.append(mkCompoundFilter(subfilter))\n\n if transformers:\n filters.append(TransformFilterMaker(transformers))\n\n if len(filters) == 1:\n return filters[0]\n else:\n return CompoundFilter(filters)"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef cron(cronline, venusian_category='irc3.plugins.cron'):\n def wrapper(func):\n def callback(context, name, ob):\n obj = context.context\n crons = obj.get_plugin(Crons)\n if info.scope == 'class':\n callback = getattr(\n obj.get_plugin(ob),\n func.__name__)\n else:\n callback = irc3.utils.wraps_with_context(func, obj)\n crons.add_cron(cronline, callback)\n info = venusian.attach(func, callback, category=venusian_category)\n return func\n return wrapper", "response": "cronline is a string that can be used to add a cronline to the current object"}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function for\ndetermining mimetype to response based on Accept header.", "response": "def _response_mimetype_based_on_accept_header(self):\n \"\"\"Determines mimetype to response based on Accept header.\n\n If mimetype is not found, it returns ``None``.\n\n \"\"\"\n response_mimetype = None\n\n if not request.accept_mimetypes:\n response_mimetype = self.default_mimetype\n else:\n all_media_types_wildcard = '*/*'\n\n for mimetype, q in request.accept_mimetypes:\n if mimetype == all_media_types_wildcard:\n response_mimetype = self.default_mimetype\n break\n if mimetype in self.response_formatters:\n response_mimetype = mimetype\n break\n\n return response_mimetype"}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef make_response(self, rv):\n status = headers = None\n if isinstance(rv, tuple):\n rv, status, headers = rv + (None,) * (3 - len(rv))\n\n response_mimetype = self._response_mimetype_based_on_accept_header()\n if response_mimetype is None:\n # Return 406, list of available mimetypes in default format.\n default_formatter = self.response_formatters.get(\n self.default_mimetype\n )\n available_mimetypes = default_formatter(\n mimetypes=list(self.response_formatters)\n )\n\n rv = self.response_class(\n response=available_mimetypes,\n status=406,\n mimetype=self.default_mimetype,\n )\n elif isinstance(rv, dict):\n formatter = self.response_formatters.get(response_mimetype)\n rv = self.response_class(\n response=formatter(**rv),\n mimetype=response_mimetype,\n )\n\n return super(ResponsiveFlask, self).make_response(\n rv=(rv, status, headers)\n )", "response": "Returns a response based on Accept header."}
{"SOURCE": "codesearchnet", "instruction": "Can you create a Python 3 function that\nworks like event but occurs during DCC CHATs", "response": "def dcc_event(regexp, callback=None, iotype='in',\n venusian_category='irc3.dcc'):\n \"\"\"Work like :class:`~irc3.dec.event` but occurs during DCC CHATs\"\"\"\n return event(regexp, callback=callback, iotype='dcc_' + iotype,\n venusian_category=venusian_category)"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef extend(func):\n def callback(context, name, ob):\n obj = context.context\n if info.scope == 'class':\n f = getattr(obj.get_plugin(ob), func.__name__)\n else:\n f = func\n setattr(obj, f.__name__, f.__get__(obj, obj.__class__))\n info = venusian.attach(func, callback, category='irc3.extend')\n return func", "response": "Allow to extend a bot"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef notice(self, client, message):\n if client and message:\n messages = utils.split_message(message, self.config.max_length)\n for msg in messages:\n client.fwrite(':{c.srv} NOTICE {c.nick} :{msg}', msg=msg)", "response": "send a notice to client"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef client_key_loader(self, f):\n @wraps(f)\n def wrapped_f(client_id):\n client_key = f(client_id)\n return {\n 'id': client_id,\n 'key': client_key,\n 'algorithm': current_app.config['HAWK_ALGORITHM']\n }\n\n self._client_key_loader_func = wrapped_f\n return wrapped_f", "response": "Registers a function to be called to find a client key."}
{"SOURCE": "codesearchnet", "instruction": "Implement a function in Python 3 to\nsign a response if it s possible.", "response": "def _sign_response(self, response):\n \"\"\"Signs a response if it's possible.\"\"\"\n if 'Authorization' not in request.headers:\n return response\n\n try:\n mohawk_receiver = mohawk.Receiver(\n credentials_map=self._client_key_loader_func,\n request_header=request.headers['Authorization'],\n url=request.url,\n method=request.method,\n content=request.get_data(),\n content_type=request.mimetype,\n accept_untrusted_content=current_app.config['HAWK_ACCEPT_UNTRUSTED_CONTENT'],\n localtime_offset_in_seconds=current_app.config['HAWK_LOCALTIME_OFFSET_IN_SECONDS'],\n timestamp_skew_in_seconds=current_app.config['HAWK_TIMESTAMP_SKEW_IN_SECONDS']\n )\n except mohawk.exc.HawkFail:\n return response\n\n response.headers['Server-Authorization'] = mohawk_receiver.respond(\n content=response.data,\n content_type=response.mimetype\n )\n return response"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef create(self, name_or_class, mask, filepath=None, **kwargs):\n if isinstance(name_or_class, type):\n name = name_or_class.type\n protocol = name_or_class\n else:\n name = name_or_class\n protocol = self.protocols[name]\n assert name in DCC_TYPES\n if filepath:\n kwargs.setdefault('limit_rate',\n self.config['send_limit_rate'])\n kwargs['filepath'] = filepath\n if protocol.type == DCCSend.type:\n kwargs.setdefault('offset', 0)\n kwargs.update(\n filename_safe=slugify(os.path.basename(filepath)),\n filesize=os.path.getsize(filepath),\n )\n elif protocol.type == DCCGet.type:\n try:\n offset = os.path.getsize(filepath)\n except OSError:\n offset = 0\n kwargs.setdefault('offset', offset)\n kwargs.setdefault('resume', False)\n kwargs.setdefault('port', None)\n f = protocol(\n mask=mask, ip=int(self.bot.ip),\n bot=self.bot, loop=self.loop, **kwargs)\n\n if kwargs['port']:\n if self.bot.config.get('dcc_sock_factory'):\n sock_factory = maybedotted(self.bot.config.dcc_sock_factory)\n args = dict(sock=sock_factory(self.bot, f.host, f.port))\n else:\n args = dict(host=f.host, port=f.port)\n task = self.bot.create_task(\n self.loop.create_connection(f.factory, **args))\n task.add_done_callback(partial(self.created, f))\n else:\n task = self.bot.create_task(\n self.loop.create_server(\n f.factory, '0.0.0.0', 0, backlog=1))\n task.add_done_callback(partial(self.created, f))\n return f", "response": "Create a new DCC connection."}
{"SOURCE": "codesearchnet", "instruction": "Implement a Python 3 function for\nresuming a DCC send", "response": "def resume(self, mask, filename, port, pos):\n \"\"\"Resume a DCC send\"\"\"\n self.connections['send']['masks'][mask][port].offset = pos\n message = 'DCC ACCEPT %s %d %d' % (filename, port, pos)\n self.bot.ctcp(mask, message)"}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef is_allowed(self, name_or_class, mask): # pragma: no cover\n if isinstance(name_or_class, type):\n name = name_or_class.type\n else:\n name = name_or_class\n info = self.connections[name]\n limit = self.config[name + '_limit']\n if limit and info['total'] >= limit:\n msg = (\n \"Sorry, there is too much DCC %s active. Please try again \"\n \"later.\") % name.upper()\n self.bot.notice(mask, msg)\n return False\n if mask not in info['masks']:\n return True\n limit = self.config[name + '_user_limit']\n if limit and info['masks'][mask] >= limit:\n msg = (\n \"Sorry, you have too many DCC %s active. Close the other \"\n \"connection(s) or wait a few seconds and try again.\"\n ) % name.upper()\n self.bot.notice(mask, msg)\n return False\n return True", "response": "Return True is a new connection is allowed"}
{"SOURCE": "codesearchnet", "instruction": "Can you create a Python 3 function that\nreturns all keys with the same prefix without the prefix", "response": "def extract_config(config, prefix):\n \"\"\"return all keys with the same prefix without the prefix\"\"\"\n prefix = prefix.strip('.') + '.'\n plen = len(prefix)\n value = {}\n for k, v in config.items():\n if k.startswith(prefix):\n value[k[plen:]] = v\n return value"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef as_list(value):\n if isinstance(value, (list, tuple)):\n return value\n if not value:\n return []\n for c in '\\n ':\n if c in value:\n value = value.split(c)\n return [v.strip() for v in value if v.strip()]\n return [value]", "response": "clever string spliting:\n\n .. code-block:: python\n\n >>> print(as_list('value'))\n ['value']\n >>> print(as_list('v1 v2'))\n ['v1', 'v2']\n >>> print(as_list(None))\n []\n >>> print(as_list(['v1']))\n ['v1']"}
{"SOURCE": "codesearchnet", "instruction": "How would you implement a function in Python 3 that\nparses the list of modes into a list of lists.", "response": "def parse_modes(modes, targets=None, noargs=''):\n \"\"\"Parse channel modes:\n\n .. code-block:: python\n\n >>> parse_modes('+c-n', noargs='cn')\n [('+', 'c', None), ('-', 'n', None)]\n >>> parse_modes('+c-v', ['gawel'], noargs='c')\n [('+', 'c', None), ('-', 'v', 'gawel')]\n \"\"\"\n if not targets:\n targets = []\n cleaned = []\n for mode in modes:\n if mode in '-+':\n char = mode\n continue\n target = targets.pop(0) if mode not in noargs else None\n cleaned.append((char, mode, target))\n return cleaned"}
{"SOURCE": "codesearchnet", "instruction": "How would you implement a function in Python 3 that\nreturns a wrapped partial func with context context.", "response": "def wraps_with_context(func, context):\n \"\"\"Return a wrapped partial(func, context)\"\"\"\n wrapped = functools.partial(func, context)\n wrapped = functools.wraps(func)(wrapped)\n if asyncio.iscoroutinefunction(func):\n wrapped = asyncio.coroutine(wrapped)\n return wrapped"}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function to\nresolve dotted names: .. code-block:: python >>> maybedotted('irc3.config') | / | |||
|---|---|---|---|
| ... | `\n # or new (b) `... | `\n col = column.find(\"strong\")\n if col:\n # (a) `... | `\n col_text = col.text\n else:\n # (b) `... | `\n col_text = column.text\n # end if\n found_columns.append(col_text)\n # end def\n\n # if TABLE is func\n for test_columns in func_fields:\n if found_columns == test_columns:\n table_header = test_columns\n table_type = 'func'\n break\n # end if\n # end for\n\n # if TABLE is class\n if not table_header: # only check if we don't have a result yet\n # search class now\n for test_columns in class_fields:\n if found_columns == test_columns:\n if table_header is not None:\n raise AssertionError(\"Table detected as func and class: {!r}\".format(found_columns))\n table_header = test_columns\n table_type = 'class'\n break\n # end if\n # end for\n # end if\n\n # TABLE is none of the above\n if not table_header: # we don't have a result yet\n raise AssertionError(\"Unknown table, {!r}\".format(found_columns))\n # end if\n\n # TABLE BODY\n\n for tds in tbodys:\n string = \"\\t\".join([col.text for col in tds])\n logger.debug(\"t: \" + string)\n param_strings.append(string)\n pass\n # end for row\n return table_type, param_strings", "response": "Parses the table and returns tuple of type class or func and list of param strings."} {"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function to\nreceive a list of results (type :class:`Clazz` or :class:`Function`), and put them into the right files in :var:`folder` :param folder: Where the files should be in. :type folder: str :param results: A list of :class:`Clazz` or :class:`Function` objects, which will be used to calculate the source code. :type results: Union(Clazz, Function)", "response": "def safe_to_file(folder, results):\n \"\"\"\n Receives a list of results (type :class:`Clazz` or :class:`Function`), and put them into the right files in :var:`folder`\n\n :param folder: Where the files should be in.\n :type folder: str\n\n :param results: A list of :class:`Clazz` or :class:`Function` objects, which will be used to calculate the source code.\n :type results: Union(Clazz, Function)\n\n \"\"\"\n functions = []\n message_send_functions = []\n clazzes = {} # \"filepath\": [Class, Class, ...]\n\n # split results into functions and classes\n for result in results:\n assert isinstance(result, (Clazz, Function))\n if isinstance(result, Clazz):\n import_path = get_type_path(result.clazz)\n import_path = import_path.rstrip(\".\")\n file_path = calc_path_and_create_folders(folder, import_path)\n result.filepath = file_path\n if file_path not in clazzes:\n clazzes[file_path] = []\n clazzes[file_path].append(result)\n else:\n assert isinstance(result, Function)\n import_path = \"pytgbot.bot.\"\n file_path = calc_path_and_create_folders(folder, import_path)\n result.filepath = file_path\n functions.append(result)\n\n if result.name.startswith('send_'):\n import_path = \"teleflask_messages.\"\n file_path = calc_path_and_create_folders(folder, import_path)\n result2 = safe_eval(repr(result), SAVE_VALUES) # serialize + unserialize = deepcopy\n result2.filepath = file_path\n message_send_functions.append(result2)\n # end if\n # end if\n # end for\n\n bot_template = get_template(\"bot.template\")\n clazzfile_template = get_template(\"classfile.template\")\n teleflask_messages_template = get_template(\"teleflask_messages_file.template\")\n for path, clazz_list in clazzes.items():\n clazz_imports = set()\n for clazz_ in clazz_list:\n assert isinstance(clazz_, Clazz)\n assert isinstance(clazz_.parent_clazz, Type)\n clazz_imports.add(clazz_.parent_clazz.as_import)\n # end for\n clazz_imports = list(clazz_imports)\n clazz_imports.sort()\n is_sendable = (\"sendable\" in path)\n try:\n with open(path, \"w\") as f:\n result = clazzfile_template.render(clazzes=clazz_list, imports=clazz_imports, is_sendable=is_sendable)\n result = result.replace(\"\\t\", \" \")\n f.write(result)\n # end with\n except IOError:\n raise # lol\n # end try\n # end for classes\n if functions:\n txt = bot_template.render(functions=functions)\n with open(functions[0].filepath, \"w\") as f:\n f.write(txt)\n # end with\n # end if\n if message_send_functions:\n txt = teleflask_messages_template.render(functions=message_send_functions)\n with open(message_send_functions[0].filepath, \"w\") as f:\n f.write(txt)"} {"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef calc_path_and_create_folders(folder, import_path):\n file_path = abspath(path_join(folder, import_path[:import_path.rfind(\".\")].replace(\".\", folder_seperator) + \".py\"))\n mkdir_p(dirname(file_path))\n return file_path", "response": "calculate the path and create the needed folders"} {"SOURCE": "codesearchnet", "instruction": "How would you implement a function in Python 3 that\nreads a file to string buffer", "response": "def read_file_to_buffer(filename):\n \"\"\"\n Reads a file to string buffer\n :param filename: \n :return: \n \"\"\"\n f = open(filename, \"r\")\n buf = BytesIO(f.read())\n f.close()\n return buf"} {"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function that can\nparse the arguments of a nova tree structure.", "response": "def parse_args(string):\n \"\"\"\n `\"yada hoa\" yupi yeah 12 \"\" None \"None\"` -> `[\"yada hoa\", \"yupi\", \"yeah\", 12, \"\", None, \"None\"]`\n :param str:\n :return:\n \"\"\"\n import ast\n is_quoted = False\n result_parts = []\n current_str = \"\"\n while len(string) > 0:\n if string[0] == \"\\\"\":\n is_quoted = not is_quoted\n current_str += string[0]\n elif string[0].isspace():\n if is_quoted:\n current_str += string[0]\n else:\n result_parts.append(current_str)\n current_str = \"\"\n # end if\n else:\n current_str += string[0]\n # end if\n string = string[1:]\n # end while\n if current_str: # last part of the array\n result_parts.append(current_str)\n # end if\n for i in range(len(result_parts)):\n # Will try for each element if it is something pythonic. Parsed type will replace original list element.\n try:\n part = ast.literal_eval(result_parts[i])\n result_parts[i] = part # write it back.\n except ValueError:\n # could not parse -> is string\n pass # because already is str.\n # end try\n # end for\n return result_parts"} {"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef overwrite_color(self, string, color, prefix=False, reset=False):\n if isinstance(color, int):\n color = self.prepare_color(color)\n # end if\n prefix = color if prefix else \"\"\n if isinstance(reset, int):\n reset = self.prepare_color(reset)\n elif isinstance(reset, bool):\n reset = self.formatter.color_off if reset else \"\"\n # end if\n return (\n prefix +\n string.replace(self.formatter.color_off, self.formatter.color_off+color).replace(self.formatter.all_off, self.formatter.all_off + color) +\n reset\n )", "response": "Overwrites the color of the input string with the new color."} {"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script to\nprint the peer to the terminal.", "response": "def print_peer(self, peer, show_id=True, id_prefix=\"\", reply=True):\n \"\"\"\n :param id_prefix: Prefix of the #id thing. Set a string, or true to have it generated.\n :type id_prefix: str|bool\n \"\"\"\n if isinstance(id_prefix, bool):\n if id_prefix: # True\n if isinstance(peer, User):\n id_prefix = \"user\"\n elif isinstance(peer, Chat):\n id_prefix = peer.type\n else:\n id_prefix = \"unknown\"\n # end if\n else: # False\n id_prefix = \"\"\n # end if\n # end if\n peer_string = self.peer_to_string(peer)\n if show_id and \"id\" in peer:\n peer_string += \" ({color_lightblue}{id_prefix}#{id}{color_off})\".format(id_prefix=id_prefix, id=peer.id, **self.color.formatter)\n return peer_string"} {"SOURCE": "codesearchnet", "instruction": "Implement a function in Python 3 to\nconvert a textual representation of MRS from one source format to another.", "response": "def convert(txt, src_fmt, tgt_fmt, single=True, **kwargs):\n \"\"\"\n Convert a textual representation of \\*MRS from one the src_fmt\n representation to the tgt_fmt representation. By default, only\n read and convert a single \\*MRS object (e.g. for `mrx` this\n starts at