{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef assert_json_type(value: JsonValue, expected_type: JsonCheckType) -> None:\n\n def type_name(t: Union[JsonCheckType, Type[None]]) -> str:\n if t is None:\n return \"None\"\n if isinstance(t, JList):\n return \"list\"\n return t.__name__\n\n if expected_type is None:\n if value is None:\n return\n elif expected_type == float:\n if isinstance(value, float) or isinstance(value, int):\n return\n elif expected_type in [str, int, bool, list, dict]:\n if isinstance(value, expected_type): # type: ignore\n return\n elif isinstance(expected_type, JList):\n if isinstance(value, list):\n for v in value:\n assert_json_type(v, expected_type.value_type)\n return\n else:\n raise TypeError(\"unsupported type\")\n raise TypeError(\"wrong JSON type {} != {}\".format(\n type_name(expected_type), type_name(type(value))))", "response": "Check that a value has a certain JSON type."}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function for\ngetting a JSON value by path optionally checking its type.", "response": "def json_get(json: JsonValue, path: str, expected_type: Any = ANY) -> Any:\n \"\"\"Get a JSON value by path, optionally checking its type.\n\n >>> j = {\"foo\": {\"num\": 3.4, \"s\": \"Text\"}, \"arr\": [10, 20, 30]}\n >>> json_get(j, \"/foo/num\")\n 3.4\n >>> json_get(j, \"/arr[1]\")\n 20\n\n Raise ValueError if the path is not found:\n\n >>> json_get(j, \"/foo/unknown\")\n Traceback (most recent call last):\n ...\n ValueError: JSON path '/foo/unknown' not found\n\n Raise TypeError if the path contains a non-object element:\n\n >>> json_get(j, \"/foo/num/bar\")\n Traceback (most recent call last):\n ...\n TypeError: JSON path '/foo/num' is not an object\n\n Or a non-array element:\n\n >>> json_get(j, \"/foo[2]\")\n Traceback (most recent call last):\n ...\n TypeError: JSON path '/foo' is not an array\n\n Raise an IndexError if the array index is out of bounds:\n\n >>> json_get(j, \"/arr[10]\")\n Traceback (most recent call last):\n ...\n IndexError: JSON array '/arr' too small (3 <= 10)\n\n Recognized types are: str, int, float, bool, list, dict, and None.\n TypeError is raised if the type does not match.\n\n >>> json_get(j, \"/foo/num\", str)\n Traceback (most recent call last):\n ...\n TypeError: wrong JSON type str != float\n\n float will match any number, int will only match numbers without a\n fractional part.\n\n >>> json_get(j, \"/foo/num\", float)\n 3.4\n >>> json_get(j, \"/foo/num\", int)\n Traceback (most recent call last):\n ...\n TypeError: wrong JSON type int != float\n \"\"\"\n\n elements = _parse_json_path(path)\n\n current = json\n current_path = \"\"\n for i, element in enumerate(elements):\n if isinstance(element, str):\n if not isinstance(current, dict):\n msg = \"JSON path '{}' is not an object\".format(current_path)\n raise TypeError(msg) from None\n if element not in current:\n raise ValueError(\"JSON path '{}' not found\".format(path))\n current_path += \"/\" + element\n current = current[element]\n else:\n if not isinstance(current, list):\n msg = \"JSON path '{}' is not an array\".format(current_path)\n raise TypeError(msg) from None\n if element >= len(current):\n msg = \"JSON array '{}' too small ({} <= {})\".format(\n current_path, len(current), element)\n raise IndexError(msg)\n current_path += \"[{}]\".format(i)\n current = current[element]\n if expected_type != ANY:\n assert_json_type(current, cast(JsonType, expected_type))\n return current"}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef json_get_default(json: JsonValue, path: str,\n default: Any, expected_type: Any = ANY) -> Any:\n \"\"\"Get a JSON value by path, optionally checking its type.\n\n This works exactly like json_get(), but instead of raising\n ValueError or IndexError when a path part is not found, return\n the provided default value:\n\n >>> json_get_default({}, \"/foo\", \"I am a default value\")\n 'I am a default value'\n\n TypeErrors will be raised as in json_get() if an expected_type\n is provided:\n\n >>> json_get_default({\"foo\": \"bar\"}, \"/foo\", 123, int)\n Traceback (most recent call last):\n ...\n TypeError: wrong JSON type int != str\n \"\"\"\n try:\n return json_get(json, path, expected_type)\n except (ValueError, IndexError):\n return default", "response": "Get a JSON value by path optionally checking its type."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef load(cls, fh):\n dat = fh.read()\n try:\n ret = cls.from_json(dat)\n except:\n ret = cls.from_yaml(dat)\n return ret", "response": "Load a new object from a file handle."}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef from_json(cls, fh):\n if isinstance(fh, str):\n return cls(json.loads(fh))\n else:\n return cls(json.load(fh))", "response": "Load a new object from a json file handle."}
{"SOURCE": "codesearchnet", "instruction": "Implement a Python 3 function for\nreturning the intersection of two items in the composite object.", "response": "def intersection(self, other, recursive=True):\n \"\"\"\n Recursively compute intersection of data. For dictionaries, items\n for specific keys will be reduced to unique items. For lists, items\n will be reduced to unique items. This method is meant to be analogous\n to set.intersection for composite objects.\n\n Args:\n other (composite): Other composite object to intersect with.\n recursive (bool): Whether or not to perform the operation recursively,\n for all nested composite objects.\n \"\"\"\n if not isinstance(other, composite):\n raise AssertionError('Cannot intersect composite and {} types'.format(type(other)))\n \n if self.meta_type != other.meta_type:\n return composite({})\n\n if self.meta_type == 'list':\n keep = []\n for item in self._list:\n if item in other._list:\n if recursive and isinstance(item, composite):\n keep.extend(item.intersection(other.index(item), recursive=True))\n else:\n keep.append(item)\n return composite(keep)\n elif self.meta_type == 'dict':\n keep = {}\n for key in self._dict:\n item = self._dict[key]\n if key in other._dict:\n if recursive and \\\n isinstance(item, composite) and \\\n isinstance(other.get(key), composite):\n keep[key] = item.intersection(other.get(key), recursive=True)\n elif item == other[key]:\n keep[key] = item\n return composite(keep)\n return"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function that can\nreturn a new object with the union of the two items.", "response": "def union(self, other, recursive=True, overwrite=False):\n \"\"\"\n Recursively compute union of data. For dictionaries, items\n for specific keys will be combined into a list, depending on the\n status of the overwrite= parameter. For lists, items will be appended\n and reduced to unique items. This method is meant to be analogous\n to set.union for composite objects.\n\n Args:\n other (composite): Other composite object to union with.\n recursive (bool): Whether or not to perform the operation recursively,\n for all nested composite objects.\n overwrite (bool): Whether or not to overwrite entries with the same\n key in a nested dictionary. \n \"\"\"\n if not isinstance(other, composite):\n raise AssertionError('Cannot union composite and {} types'.format(type(other)))\n \n if self.meta_type != other.meta_type:\n return composite([self, other])\n\n if self.meta_type == 'list':\n keep = []\n for item in self._list:\n keep.append(item)\n for item in other._list:\n if item not in self._list:\n keep.append(item)\n return composite(keep)\n elif self.meta_type == 'dict':\n keep = {}\n for key in list(set(list(self._dict.keys()) + list(other._dict.keys()))):\n left = self._dict.get(key)\n right = other._dict.get(key)\n if recursive and \\\n isinstance(left, composite) and \\\n isinstance(right, composite):\n keep[key] = left.union(right, recursive=recursive, overwrite=overwrite)\n elif left == right:\n keep[key] = left\n elif left is None:\n keep[key] = right\n elif right is None:\n keep[key] = left\n elif overwrite:\n keep[key] = right\n else:\n keep[key] = composite([left, right])\n return composite(keep)\n return"}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function for\nupdating internal dictionary object.", "response": "def update(self, other):\n \"\"\"\n Update internal dictionary object. This is meant to be an\n analog for dict.update().\n \"\"\"\n if self.meta_type == 'list':\n raise AssertionError('Cannot update object of `list` base type!')\n elif self.meta_type == 'dict':\n self._dict = dict(self + composite(other))\n return"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef items(self):\n if self.meta_type == 'list':\n return self._list\n elif self.meta_type == 'dict':\n return self._dict.items()", "response": "Return a list of keys for object."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef values(self):\n if self.meta_type == 'list':\n return self._list\n elif self.meta_type == 'dict':\n return self._dict.values()", "response": "Return a list of all the keys for the object."}
{"SOURCE": "codesearchnet", "instruction": "Implement a Python 3 function for\nappending to object if object is list.", "response": "def append(self, item):\n \"\"\"\n Append to object, if object is list.\n \"\"\"\n if self.meta_type == 'dict':\n raise AssertionError('Cannot append to object of `dict` base type!')\n if self.meta_type == 'list':\n self._list.append(item)\n return"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script to\nextend list from object.", "response": "def extend(self, item):\n \"\"\"\n Extend list from object, if object is list.\n \"\"\"\n if self.meta_type == 'dict':\n raise AssertionError('Cannot extend to object of `dict` base type!')\n if self.meta_type == 'list':\n self._list.extend(item)\n return"}
{"SOURCE": "codesearchnet", "instruction": "How would you code a function in Python 3 to\nreturn JSON representation of object.", "response": "def json(self):\n \"\"\"\n Return JSON representation of object.\n \"\"\"\n if self.meta_type == 'list':\n ret = []\n for dat in self._list:\n if not isinstance(dat, composite):\n ret.append(dat)\n else:\n ret.append(dat.json())\n return ret\n\n elif self.meta_type == 'dict':\n ret = {}\n for key in self._dict:\n if not isinstance(self._dict[key], composite):\n ret[key] = self._dict[key]\n else:\n ret[key] = self._dict[key].json()\n return ret"}
{"SOURCE": "codesearchnet", "instruction": "Can you create a Python 3 function that\nwrites composite object to file handle in JSON format.", "response": "def write_json(self, fh, pretty=True):\n \"\"\"\n Write composite object to file handle in JSON format.\n\n Args:\n fh (file): File handle to write to.\n pretty (bool): Sort keys and indent in output.\n \"\"\"\n sjson = json.JSONEncoder().encode(self.json())\n if pretty:\n json.dump(json.loads(sjson), fh, sort_keys=True, indent=4)\n else:\n json.dump(json.loads(sjson), fh)\n return"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script to\nwrite the current set of keys to fh.", "response": "def write(self, fh, pretty=True):\n \"\"\"\n API niceness defaulting to composite.write_json().\n \"\"\"\n return self.write_json(fh, pretty=pretty)"}
{"SOURCE": "codesearchnet", "instruction": "How would you code a function in Python 3 to\nreturn JSON representation of object.", "response": "def json(self):\n \"\"\"\n Return JSON representation of object.\n \"\"\"\n data = {}\n for item in self._data:\n if isinstance(self._data[item], filetree):\n data[item] = self._data[item].json()\n else:\n data[item] = self._data[item]\n return data"}
{"SOURCE": "codesearchnet", "instruction": "Can you write a function in Python 3 where it\nreturns a list of files in filetree.", "response": "def filelist(self):\n \"\"\"\n Return list of files in filetree.\n \"\"\"\n if len(self._filelist) == 0:\n for item in self._data:\n if isinstance(self._data[item], filetree):\n self._filelist.extend(self._data[item].filelist())\n else:\n self._filelist.append(self._data[item])\n return self._filelist"}
{"SOURCE": "codesearchnet", "instruction": "Implement a function in Python 3 to\nprune leaves of the filetree according to specified regular expression.", "response": "def prune(self, regex=r\".*\"):\n \"\"\"\n Prune leaves of filetree according to specified\n regular expression.\n\n Args:\n regex (str): Regular expression to use in pruning tree.\n \"\"\"\n return filetree(self.root, ignore=self.ignore, regex=regex)"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef deref(self, ctx):\n if self in ctx.call_nodes:\n raise CyclicReferenceError(ctx, self)\n\n if self in ctx.cached_results:\n return ctx.cached_results[self]\n\n try:\n ctx.call_nodes.add(self)\n ctx.call_stack.append(self)\n\n result = self.evaluate(ctx)\n ctx.cached_results[self] = result\n return result\n except:\n if ctx.exception_call_stack is None:\n ctx.exception_call_stack = list(ctx.call_stack)\n raise\n finally:\n ctx.call_stack.pop()\n ctx.call_nodes.remove(self)", "response": "Returns the value of this reference pointing to."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef getModel(self):\n\t\t'''\n\t\t\tgetModel - get the IndexedRedisModel associated with this list. If one was not provided in constructor,\n\t\t\t it will be inferred from the first item in the list (if present)\n\n\t\t\t @return ``, for example) tags around a single\n paragraph of content. That filter does not affect content that\n consists of multiple blocks (several paragraphs, or lists, for\n example). Default is `False`.\n\n For example, **without** this filter Pandoc will convert\n the string ``\"Title text\"`` to ``\" Title text ``, for example) tags around a single\n paragraph of content. That filter does not affect content that\n consists of multiple blocks (several paragraphs, or lists, for\n example). Default is `False`.\n\n For example, **without** this filter Pandoc will convert\n the string ``\"Title text\"`` to ``\" Title text - Single element list, id of saved object (if successful)\n\t\t'''\n\t\tsaver = IndexedRedisSave(self.__class__)\n\t\treturn saver.save(self, cascadeSave=cascadeSave)", "response": "save - Save this object.\n\t\t\t\n\t\t\tWill perform an \"insert\" if this object had not been saved before,\n\t\t\t otherwise will update JUST the fields changed on THIS INSTANCE of the model.\n\n\t\t\t i.e. If you have two processes fetch the same object and change different fields, they will not overwrite\n\t\t\t eachother, but only save the ones each process changed.\n\n\t\t\tIf you want to save multiple objects of type MyModel in a single transaction,\n\t\t\tand you have those objects in a list, myObjs, you can do the following:\n\n\t\t\t\tMyModel.saver.save(myObjs)\n\n\t\t\t@param cascadeSave
- Single element list, id of saved object (if successful)"}
{"SOURCE": "codesearchnet", "instruction": "Can you create a Python 3 function that\nresets - Remove all stored data associated with this model (i.e. all objects of this type), and then save all the provided objects in #newObjs , all in one atomic transaction. Use this method to move from one complete set of objects to another, where any querying applications will only see the complete before or complete after. @param newObjs list
``, using your own templating\n system.\n\n **With** this filter, Pandoc will convert the string ``\"Title text\"``\n to ``\"Title text\"`` in HTML.\n\n mathjax : `bool`, optional\n If `True` then Pandoc will markup output content to work with MathJax.\n Default is False.\n\n smart : `bool`, optional\n If `True` (default) then ascii characters will be converted to unicode\n characters like smart quotes and em dashes.\n\n extra_args : `list`, optional\n Sequence of Pandoc arguments command line arguments (such as\n ``'--normalize'``). The ``deparagraph``, ``mathjax``, and ``smart``\n arguments are convenience arguments that are equivalent to items\n in ``extra_args``.\n\n Returns\n -------\n output : `str`\n Content in the output (``to_fmt``) format.\n\n Notes\n -----\n This function will automatically install Pandoc if it is not available.\n See `ensure_pandoc`.\n \"\"\"\n logger = logging.getLogger(__name__)\n\n if extra_args is not None:\n extra_args = list(extra_args)\n else:\n extra_args = []\n\n if mathjax:\n extra_args.append('--mathjax')\n\n if smart:\n extra_args.append('--smart')\n\n if deparagraph:\n extra_args.append('--filter=lsstprojectmeta-deparagraph')\n\n extra_args.append('--wrap=none')\n\n # de-dupe extra args\n extra_args = set(extra_args)\n\n logger.debug('Running pandoc from %s to %s with extra_args %s',\n from_fmt, to_fmt, extra_args)\n\n output = pypandoc.convert_text(content, to_fmt, format=from_fmt,\n extra_args=extra_args)\n return output", "response": "Convert text from one markup format to another using pandoc. convert_text."}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef convert_lsstdoc_tex(\n content, to_fmt, deparagraph=False, mathjax=False,\n smart=True, extra_args=None):\n \"\"\"Convert lsstdoc-class LaTeX to another markup format.\n\n This function is a thin wrapper around `convert_text` that automatically\n includes common lsstdoc LaTeX macros.\n\n Parameters\n ----------\n content : `str`\n Original content.\n\n to_fmt : `str`\n Output format for the content (see https://pandoc.org/MANUAL.html).\n For example, 'html5'.\n\n deparagraph : `bool`, optional\n If `True`, then the\n `lsstprojectmeta.pandoc.filters.deparagraph.deparagraph` filter is\n used to remove paragraph (``
``, using your own templating\n system.\n\n **With** this filter, Pandoc will convert the string ``\"Title text\"``\n to ``\"Title text\"`` in HTML.\n\n mathjax : `bool`, optional\n If `True` then Pandoc will markup output content to work with MathJax.\n Default is False.\n\n smart : `bool`, optional\n If `True` (default) then ascii characters will be converted to unicode\n characters like smart quotes and em dashes.\n\n extra_args : `list`, optional\n Sequence of Pandoc arguments command line arguments (such as\n ``'--normalize'``). The ``deparagraph``, ``mathjax``, and ``smart``\n arguments are convenience arguments that are equivalent to items\n in ``extra_args``.\n\n Returns\n -------\n output : `str`\n Content in the output (``to_fmt``) format.\n\n Notes\n -----\n This function will automatically install Pandoc if it is not available.\n See `ensure_pandoc`.\n \"\"\"\n augmented_content = '\\n'.join((LSSTDOC_MACROS, content))\n return convert_text(\n augmented_content, 'latex', to_fmt,\n deparagraph=deparagraph, mathjax=mathjax,\n smart=smart, extra_args=extra_args)", "response": "Convert lsstdoc LaTeX to another markup format."}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function to\ndecode a JSON - LD dataset including decoding datetime strings into datetime. datetime objects.", "response": "def decode_jsonld(jsonld_text):\n \"\"\"Decode a JSON-LD dataset, including decoding datetime\n strings into `datetime.datetime` objects.\n\n Parameters\n ----------\n encoded_dataset : `str`\n The JSON-LD dataset encoded as a string.\n\n Returns\n -------\n jsonld_dataset : `dict`\n A JSON-LD dataset.\n\n Examples\n --------\n\n >>> doc = '{\"dt\": \"2018-01-01T12:00:00Z\"}'\n >>> decode_jsonld(doc)\n {'dt': datetime.datetime(2018, 1, 1, 12, 0, tzinfo=datetime.timezone.utc)}\n \"\"\"\n decoder = json.JSONDecoder(object_pairs_hook=_decode_object_pairs)\n return decoder.decode(jsonld_text)"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function that can\nencode values as JSON strings.", "response": "def default(self, obj):\n \"\"\"Encode values as JSON strings.\n\n This method overrides the default implementation from\n `json.JSONEncoder`.\n \"\"\"\n if isinstance(obj, datetime.datetime):\n return self._encode_datetime(obj)\n\n # Fallback to the default encoding\n return json.JSONEncoder.default(self, obj)"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function for\nencoding a datetime in the format '%Y-%m-%dT%H:%M:%SZ.", "response": "def _encode_datetime(self, dt):\n \"\"\"Encode a datetime in the format '%Y-%m-%dT%H:%M:%SZ'.\n\n The datetime can be naieve (doesn't have timezone info) or aware\n (it does have a tzinfo attribute set). Regardless, the datetime\n is transformed into UTC.\n \"\"\"\n if dt.tzinfo is None:\n # Force it to be a UTC datetime\n dt = dt.replace(tzinfo=datetime.timezone.utc)\n\n # Convert to UTC (no matter what)\n dt = dt.astimezone(datetime.timezone.utc)\n\n return dt.strftime('%Y-%m-%dT%H:%M:%SZ')"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script for\ngetting all git repositories within this environment", "response": "def find_repos(self, depth=10):\n '''Get all git repositories within this environment'''\n\n repos = []\n\n for root, subdirs, files in walk_dn(self.root, depth=depth):\n if 'modules' in root:\n continue\n if '.git' in subdirs:\n repos.append(root)\n\n return repos"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef clone(self, repo_path, destination, branch=None):\n '''Clone a repository to a destination relative to envrionment root'''\n\n logger.debug('Installing ' + repo_path)\n if not destination.startswith(self.env_path):\n destination = unipath(self.env_path, destination)\n\n if branch:\n return shell.run('git', 'clone', repo_path, '--branch', branch,\n '--single-branch', '--recursive', destination)\n\n return shell.run('git', 'clone', '--recursive', repo_path, destination)", "response": "Clone a repository to a destination relative to envrionment root"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script to\nclone a repository to a destination relative to envrionment root", "response": "def pull(self, repo_path, *args):\n '''Clone a repository to a destination relative to envrionment root'''\n\n logger.debug('Pulling ' + repo_path)\n if not repo_path.startswith(self.env_path):\n repo_path = unipath(self.env_path, repo_path)\n\n return shell.run('git', 'pull', *args, **{'cwd': repo_path})"}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef install(self, package):\n '''Install a python package using pip'''\n\n logger.debug('Installing ' + package)\n shell.run(self.pip_path, 'install', package)", "response": "Install a python package using pip"}
{"SOURCE": "codesearchnet", "instruction": "Implement a Python 3 function for\nupdating a python package using pip", "response": "def upgrade(self, package):\n '''Update a python package using pip'''\n\n logger.debug('Upgrading ' + package)\n shell.run(self.pip_path, 'install', '--upgrade', '--no-deps', package)\n shell.run(self.pip_path, 'install', package)"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function that can\nreturn the nb quantiles for datas in a dataframe", "response": "def df_quantile(df, nb=100):\n \"\"\"Returns the nb quantiles for datas in a dataframe\n \"\"\"\n quantiles = np.linspace(0, 1., nb)\n res = pd.DataFrame()\n for q in quantiles:\n res = res.append(df.quantile(q), ignore_index=True)\n return res"}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function for\ncomputing the average along a 1D array like ma. mean but with a representativity coefficient", "response": "def mean(a, rep=0.75, **kwargs):\n \"\"\"Compute the average along a 1D array like ma.mean,\n but with a representativity coefficient : if ma.count(a)/ma.size(a)>=rep,\n then the result is a masked value\n \"\"\"\n return rfunc(a, ma.mean, rep, **kwargs)"}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function to\ncompute the max along a 1D array like ma. mean and a representativity coefficient coefficient.", "response": "def max(a, rep=0.75, **kwargs):\n \"\"\"Compute the max along a 1D array like ma.mean,\n but with a representativity coefficient : if ma.count(a)/ma.size(a)>=rep,\n then the result is a masked value\n \"\"\"\n return rfunc(a, ma.max, rep, **kwargs)"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef min(a, rep=0.75, **kwargs):\n return rfunc(a, ma.min, rep, **kwargs)", "response": "Compute the minimum value along a 1D array like ma. mean but with a representativity coefficient coefficient."}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef rfunc(a, rfunc=None, rep=0.75, **kwargs):\n if float(ma.count(a)) / ma.size(a) < rep:\n return ma.masked\n else:\n if rfunc is None:\n return a\n return rfunc(a, **kwargs)", "response": "Applies func on a if a comes with a representativity coefficient rep returns a masked array\n i. e. ma. count ( a ) > rep."}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef rmse(a, b):\n return np.sqrt(np.square(a - b).mean())", "response": "Returns the root mean square error betwwen a and b\n "}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef nmse(a, b):\n return np.square(a - b).mean() / (a.mean() * b.mean())", "response": "Returns the normalized mean square error of a and b"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef mfbe(a, b):\n return 2 * bias(a, b) / (a.mean() + b.mean())", "response": "Returns the mean fractionalized bias error between two data sets."}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef fa(a, b, alpha=2):\n return np.sum((a > b / alpha) & (a < b * alpha), dtype=float) / len(a) * 100", "response": "Returns the factor of alpha when a > b"}
{"SOURCE": "codesearchnet", "instruction": "How would you implement a function in Python 3 that\nreturns the factor of exceedance", "response": "def foex(a, b):\n \"\"\"Returns the factor of exceedance\n \"\"\"\n return (np.sum(a > b, dtype=float) / len(a) - 0.5) * 100"}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef correlation(a, b):\n diff1 = a - a.mean()\n diff2 = b - b.mean()\n return (diff1 * diff2).mean() / (np.sqrt(np.square(diff1).mean() * np.square(diff2).mean()))", "response": "Computes the correlation between a and b says the Pearson s correlation\n coefficient R\n "}
{"SOURCE": "codesearchnet", "instruction": "How would you code a function in Python 3 to\nfigure of merit in time", "response": "def fmt(a, b):\n \"\"\"Figure of merit in time\n \"\"\"\n return 100 * np.min([a, b], axis=0).sum() / np.max([a, b], axis=0).sum()"}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef fullStats(a, b):\n\n stats = [\n ['bias', 'Bias', bias(a, b)],\n ['stderr', 'Standard Deviation Error', stderr(a, b)],\n ['mae', 'Mean Absolute Error', mae(a, b)],\n ['rmse', 'Root Mean Square Error', rmse(a, b)],\n ['nmse', 'Normalized Mean Square Error', nmse(a, b)],\n ['mfbe', 'Mean Fractionalized bias Error', mfbe(a, b)],\n ['fa2', 'Factor of Two', fa(a, b, 2)],\n ['foex', 'Factor of Exceedance', foex(a, b)],\n ['correlation', 'Correlation R', correlation(a, b)],\n ['determination', 'Coefficient of Determination r2', determination(a, b)],\n ['gmb', 'Geometric Mean Bias', gmb(a, b)],\n ['gmv', 'Geometric Mean Variance', gmv(a, b)],\n ['fmt', 'Figure of Merit in Time', fmt(a, b)]\n ]\n rec = np.rec.fromrecords(stats, names=('stat', 'description', 'result'))\n df = pd.DataFrame.from_records(rec, index='stat')\n return df", "response": "Performs several stats on a against b typically a is the predictions array and b is the observations array and a is the observations array and b is the observations array"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef site_path(self):\n '''Path to environments site-packages'''\n\n if platform == 'win':\n return unipath(self.path, 'Lib', 'site-packages')\n\n py_ver = 'python{0}'.format(sys.version[:3])\n return unipath(self.path, 'lib', py_ver, 'site-packages')", "response": "Path to site - packages"}
{"SOURCE": "codesearchnet", "instruction": "Can you create a Python 3 function that\nactivates the current python environment.", "response": "def _activate(self):\n '''\n Do some serious mangling to the current python environment...\n This is necessary to activate an environment via python.\n '''\n\n old_syspath = set(sys.path)\n site.addsitedir(self.site_path)\n site.addsitedir(self.bin_path)\n new_syspaths = set(sys.path) - old_syspath\n for path in new_syspaths:\n sys.path.remove(path)\n sys.path.insert(1, path)\n\n if not hasattr(sys, 'real_prefix'):\n sys.real_prefix = sys.prefix\n\n sys.prefix = self.path"}
{"SOURCE": "codesearchnet", "instruction": "Can you write a function in Python 3 where it\nremoves this environment and all of its children.", "response": "def remove(self):\n '''\n Remove this environment\n '''\n self.run_hook('preremove')\n utils.rmtree(self.path)\n self.run_hook('postremove')"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef command(self):\n '''Command used to launch this application module'''\n\n cmd = self.config.get('command', None)\n if cmd is None:\n return\n\n cmd = cmd[platform]\n return cmd['path'], cmd['args']", "response": "Command used to launch this application module"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script to\ncreate a virtual environment.", "response": "def create(name_or_path=None, config=None):\n '''Create a virtual environment. You can pass either the name of a new\n environment to create in your CPENV_HOME directory OR specify a full path\n to create an environment outisde your CPENV_HOME.\n\n Create an environment in CPENV_HOME::\n\n >>> cpenv.create('myenv')\n\n Create an environment elsewhere::\n\n >>> cpenv.create('~/custom_location/myenv')\n\n :param name_or_path: Name or full path of environment\n :param config: Environment configuration including dependencies etc...\n '''\n\n # Get the real path of the environment\n if utils.is_system_path(name_or_path):\n path = unipath(name_or_path)\n else:\n path = unipath(get_home_path(), name_or_path)\n\n if os.path.exists(path):\n raise OSError('{} already exists'.format(path))\n\n env = VirtualEnvironment(path)\n utils.ensure_path_exists(env.path)\n\n if config:\n if utils.is_git_repo(config):\n Git('').clone(config, env.path)\n else:\n shutil.copy2(config, env.config_path)\n else:\n with open(env.config_path, 'w') as f:\n f.write(defaults.environment_config)\n\n utils.ensure_path_exists(env.hook_path)\n utils.ensure_path_exists(env.modules_path)\n\n env.run_hook('precreate')\n\n virtualenv.create_environment(env.path)\n if not utils.is_home_environment(env.path):\n EnvironmentCache.add(env)\n EnvironmentCache.save()\n\n try:\n env.update()\n except:\n utils.rmtree(path)\n logger.debug('Failed to update, rolling back...')\n raise\n else:\n env.run_hook('postcreate')\n\n return env"}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function for\nremoving an environment or module", "response": "def remove(name_or_path):\n '''Remove an environment or module\n\n :param name_or_path: name or path to environment or module\n '''\n\n r = resolve(name_or_path)\n r.resolved[0].remove()\n\n EnvironmentCache.discard(r.resolved[0])\n EnvironmentCache.save()"}
{"SOURCE": "codesearchnet", "instruction": "Implement a Python 3 function for\nactivating and launches a module", "response": "def launch(module_name, *args, **kwargs):\n '''Activates and launches a module\n\n :param module_name: name of module to launch\n '''\n\n r = resolve(module_name)\n r.activate()\n mod = r.resolved[0]\n mod.launch(*args, **kwargs)"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function that can\ndeactivate an environment by restoring all env vars to a clean state stored prior to activating environments", "response": "def deactivate():\n '''Deactivates an environment by restoring all env vars to a clean state\n stored prior to activating environments\n '''\n\n if 'CPENV_ACTIVE' not in os.environ or 'CPENV_CLEAN_ENV' not in os.environ:\n raise EnvironmentError('Can not deactivate environment...')\n\n utils.restore_env_from_file(os.environ['CPENV_CLEAN_ENV'])"}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function for\nreturning your home path... CPENV_HOME env var OR ~/.cpenv", "response": "def get_home_path():\n ''':returns: your home path...CPENV_HOME env var OR ~/.cpenv'''\n\n home = unipath(os.environ.get('CPENV_HOME', '~/.cpenv'))\n home_modules = unipath(home, 'modules')\n if not os.path.exists(home):\n os.makedirs(home)\n if not os.path.exists(home_modules):\n os.makedirs(home_modules)\n return home"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script for\nreturning a list of paths in CPENV_MODULES env var and CPENV_HOME / modules", "response": "def get_module_paths():\n ''':returns: paths in CPENV_MODULES env var and CPENV_HOME/modules'''\n\n module_paths = []\n\n cpenv_modules_path = os.environ.get('CPENV_MODULES', None)\n if cpenv_modules_path:\n module_paths.extend(cpenv_modules_path.split(os.pathsep))\n\n module_paths.append(unipath(get_home_path(), 'modules'))\n\n return module_paths"}
{"SOURCE": "codesearchnet", "instruction": "Can you write a function in Python 3 where it\nreturns a list of all known virtual environments as . This includes those in CPENV_HOME and any others that are cached. This includes those in CPENV_HOME and any others that are not cached.", "response": "def get_environments():\n '''Returns a list of all known virtual environments as\n :class:`VirtualEnvironment` instances. This includes those in CPENV_HOME\n and any others that are cached(created by the current user or activated\n once by full path.)\n '''\n\n environments = set()\n\n cwd = os.getcwd()\n for d in os.listdir(cwd):\n\n if d == 'environment.yml':\n environments.add(VirtualEnvironment(cwd))\n continue\n\n path = unipath(cwd, d)\n if utils.is_environment(path):\n environments.add(VirtualEnvironment(path))\n\n home = get_home_path()\n for d in os.listdir(home):\n\n path = unipath(home, d)\n if utils.is_environment(path):\n environments.add(VirtualEnvironment(path))\n\n for env in EnvironmentCache:\n environments.add(env)\n\n return sorted(list(environments), key=lambda x: x.name)"}
{"SOURCE": "codesearchnet", "instruction": "Implement a Python 3 function for\nreturning a list of available modules.", "response": "def get_modules():\n '''Returns a list of available modules.'''\n\n modules = set()\n\n cwd = os.getcwd()\n for d in os.listdir(cwd):\n\n if d == 'module.yml':\n modules.add(Module(cwd))\n\n path = unipath(cwd, d)\n if utils.is_module(path):\n modules.add(Module(cwd))\n\n module_paths = get_module_paths()\n for module_path in module_paths:\n for d in os.listdir(module_path):\n\n path = unipath(module_path, d)\n if utils.is_module(path):\n modules.add(Module(path))\n\n return sorted(list(modules), key=lambda x: x.name)"}
{"SOURCE": "codesearchnet", "instruction": "Can you implement a function in Python 3 that\nreturns a list of active : class:`Module` s or [ ]", "response": "def get_active_modules():\n ''':returns: a list of active :class:`Module` s or []'''\n\n modules = os.environ.get('CPENV_ACTIVE_MODULES', None)\n if modules:\n modules = modules.split(os.pathsep)\n return [Module(module) for module in modules]\n\n return []"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function that can\nadd a module to CPENV_ACTIVE_MODULES environment variable", "response": "def add_active_module(module):\n '''Add a module to CPENV_ACTIVE_MODULES environment variable'''\n\n modules = set(get_active_modules())\n modules.add(module)\n new_modules_path = os.pathsep.join([m.path for m in modules])\n os.environ['CPENV_ACTIVE_MODULES'] = str(new_modules_path)"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function for\nremoving a module from CPENV_ACTIVE_MODULES environment variable", "response": "def rem_active_module(module):\n '''Remove a module from CPENV_ACTIVE_MODULES environment variable'''\n\n modules = set(get_active_modules())\n modules.discard(module)\n new_modules_path = os.pathsep.join([m.path for m in modules])\n os.environ['CPENV_ACTIVE_MODULES'] = str(new_modules_path)"}
{"SOURCE": "codesearchnet", "instruction": "Can you create a Python 3 function that\nformats a list of environments and modules for terminal output", "response": "def format_objects(objects, children=False, columns=None, header=True):\n '''Format a list of environments and modules for terminal output'''\n\n columns = columns or ('NAME', 'TYPE', 'PATH')\n objects = sorted(objects, key=_type_and_name)\n data = []\n for obj in objects:\n if isinstance(obj, cpenv.VirtualEnvironment):\n data.append(get_info(obj))\n modules = obj.get_modules()\n if children and modules:\n for mod in modules:\n data.append(get_info(mod, indent=2, root=obj.path))\n else:\n data.append(get_info(obj))\n\n maxes = [len(max(col, key=len)) for col in zip(*data)]\n tmpl = '{:%d} {:%d} {:%d}' % tuple(maxes)\n lines = []\n if header:\n lines.append('\\n' + bold_blue(tmpl.format(*columns)))\n\n for obj_data in data:\n lines.append(tmpl.format(*obj_data))\n\n return '\\n'.join(lines)"}
{"SOURCE": "codesearchnet", "instruction": "Can you create a Python 3 function that\nlists available environments and modules", "response": "def list_():\n '''List available environments and modules'''\n\n environments = cpenv.get_environments()\n modules = cpenv.get_modules()\n click.echo(format_objects(environments + modules, children=True))"}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef create(name_or_path, config):\n '''Create a new environment.'''\n\n if not name_or_path:\n ctx = click.get_current_context()\n click.echo(ctx.get_help())\n examples = (\n '\\nExamples:\\n'\n ' cpenv create my_env\\n'\n ' cpenv create ./relative/path/to/my_env\\n'\n ' cpenv create my_env --config ./relative/path/to/config\\n'\n ' cpenv create my_env --config git@github.com:user/config.git\\n'\n )\n click.echo(examples)\n return\n\n click.echo(\n blue('Creating a new virtual environment ' + name_or_path)\n )\n try:\n env = cpenv.create(name_or_path, config)\n except Exception as e:\n click.echo(bold_red('FAILED TO CREATE ENVIRONMENT!'))\n click.echo(e)\n else:\n click.echo(bold_green('Successfully created environment!'))\n click.echo(blue('Launching subshell'))\n\n cpenv.activate(env)\n shell.launch(env.name)", "response": "Create a new virtual environment."}
{"SOURCE": "codesearchnet", "instruction": "Implement a Python 3 function for\nlisting available environments and modules", "response": "def list_():\n '''List available environments and modules'''\n\n click.echo('Cached Environments')\n\n environments = list(EnvironmentCache)\n click.echo(format_objects(environments, children=False))"}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef add(path):\n '''Add an environment to the cache. Allows you to activate the environment\n by name instead of by full path'''\n\n click.echo('\\nAdding {} to cache......'.format(path), nl=False)\n try:\n r = cpenv.resolve(path)\n except Exception as e:\n click.echo(bold_red('FAILED'))\n click.echo(e)\n return\n\n if isinstance(r.resolved[0], cpenv.VirtualEnvironment):\n EnvironmentCache.add(r.resolved[0])\n EnvironmentCache.save()\n click.echo(bold_green('OK!'))", "response": "Add an environment to the cache. Allows you to activate the environment by name instead of by full path."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function that can\nremove a cached environment.", "response": "def remove(path):\n '''Remove a cached environment. Removed paths will no longer be able to\n be activated by name'''\n\n r = cpenv.resolve(path)\n if isinstance(r.resolved[0], cpenv.VirtualEnvironment):\n EnvironmentCache.discard(r.resolved[0])\n EnvironmentCache.save()"}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef create(name_or_path, config):\n '''Create a new template module.\n\n You can also specify a filesystem path like \"./modules/new_module\"\n '''\n\n click.echo('Creating module {}...'.format(name_or_path), nl=False)\n try:\n module = cpenv.create_module(name_or_path, config)\n except Exception as e:\n click.echo(bold_red('FAILED'))\n raise\n else:\n click.echo(bold_green('OK!'))\n click.echo('Browse to your new module and make some changes.')\n click.echo(\"When you're ready add the module to an environment:\")\n click.echo(' cpenv module add my_module ./path/to/my_module')\n click.echo('Or track your module on git and add it directly from the repo:')\n click.echo(' cpenv module add my_module git@github.com:user/my_module.git')", "response": "Create a new template module."}
{"SOURCE": "codesearchnet", "instruction": "Can you create a Python 3 function that\nadds a module to an environment. PATH can be a git repository path or a filesystem path. branch can be a git repository path or a filesystem path. type can be local or shared", "response": "def add(name, path, branch, type):\n '''Add a module to an environment. PATH can be a git repository path or\n a filesystem path. '''\n\n if not name and not path:\n ctx = click.get_current_context()\n click.echo(ctx.get_help())\n examples = (\n '\\nExamples:\\n'\n ' cpenv module add my_module ./path/to/my_module\\n'\n ' cpenv module add my_module git@github.com:user/my_module.git'\n ' cpenv module add my_module git@github.com:user/my_module.git --branch=master --type=shared'\n )\n click.echo(examples)\n return\n\n if not name:\n click.echo('Missing required argument: name')\n return\n\n if not path:\n click.echo('Missing required argument: path')\n\n env = cpenv.get_active_env()\n if type=='local':\n if not env:\n click.echo('\\nActivate an environment to add a local module.\\n')\n return\n\n if click.confirm('\\nAdd {} to active env {}?'.format(name, env.name)):\n click.echo('Adding module...', nl=False)\n try:\n env.add_module(name, path, branch)\n except:\n click.echo(bold_red('FAILED'))\n raise\n else:\n click.echo(bold_green('OK!'))\n\n return\n\n module_paths = cpenv.get_module_paths()\n click.echo('\\nAvailable module paths:\\n')\n for i, mod_path in enumerate(module_paths):\n click.echo(' {}. {}'.format(i, mod_path))\n choice = click.prompt(\n 'Where do you want to add your module?',\n type=int,\n default=0\n )\n module_root = module_paths[choice]\n module_path = utils.unipath(module_root, name)\n click.echo('Creating module {}...'.format(module_path), nl=False)\n try:\n cpenv.create_module(module_path, path, branch)\n except:\n click.echo(bold_red('FAILED'))\n raise\n else:\n click.echo(bold_green('OK!'))"}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef remove(name, local):\n '''Remove a module named NAME. Will remove the first resolved module named NAME. You can also specify a full path to a module. Use the --local option\n to ensure removal of modules local to the currently active environment.'''\n\n click.echo()\n if not local: # Use resolver to find module\n try:\n r = cpenv.resolve(name)\n except cpenv.ResolveError as e:\n click.echo(e)\n return\n\n obj = r.resolved[0]\n else: # Try to find module in active environment\n env = cpenv.get_active_env()\n if not env:\n click.echo('You must activate an env to remove local modules')\n return\n\n mod = env.get_module(name)\n if not mod:\n click.echo('Failed to resolve module: ' + name)\n return\n\n obj = mod\n\n if isinstance(obj, cpenv.VirtualEnvironment):\n click.echo('{} is an environment. Use `cpenv remove` instead.')\n return\n\n click.echo(format_objects([obj]))\n click.echo()\n\n user_confirmed = click.confirm(\n red('Are you sure you want to remove this module?')\n )\n if user_confirmed:\n click.echo('Attempting to remove...', nl=False)\n\n try:\n obj.remove()\n except Exception as e:\n click.echo(bold_red('FAILED'))\n click.echo(e)\n else:\n click.echo(bold_green('OK!'))", "response": "Remove a module named NAME. Will remove the first resolved module named NAME."}
{"SOURCE": "codesearchnet", "instruction": "Can you implement a function in Python 3 that\ncopies a global module to the active environment.", "response": "def localize(name):\n '''Copy a global module to the active environment.'''\n\n env = cpenv.get_active_env()\n if not env:\n click.echo('You need to activate an environment first.')\n return\n\n try:\n r = cpenv.resolve(name)\n except cpenv.ResolveError as e:\n click.echo('\\n' + str(e))\n\n module = r.resolved[0]\n if isinstance(module, cpenv.VirtualEnvironment):\n click.echo('\\nCan only localize a module not an environment')\n return\n\n active_modules = cpenv.get_active_modules()\n if module in active_modules:\n click.echo('\\nCan not localize an active module.')\n return\n\n if module in env.get_modules():\n click.echo('\\n{} is already local to {}'.format(module.name, env.name))\n return\n\n if click.confirm('\\nAdd {} to env {}?'.format(module.name, env.name)):\n click.echo('Adding module...', nl=False)\n try:\n module = env.add_module(module.name, module.path)\n except:\n click.echo(bold_red('FAILED'))\n raise\n else:\n click.echo(bold_green('OK!'))\n\n click.echo('\\nActivate the localize module:')\n click.echo(' cpenv activate {} {}'.format(env.name, module.name))"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function for\nresolving VirtualEnvironments with a relative or absolute path", "response": "def path_resolver(resolver, path):\n '''Resolves VirtualEnvironments with a relative or absolute path'''\n\n path = unipath(path)\n\n if is_environment(path):\n return VirtualEnvironment(path)\n\n raise ResolveError"}
{"SOURCE": "codesearchnet", "instruction": "Can you implement a function in Python 3 that\nresolves VirtualEnvironments in CPENV_HOME", "response": "def home_resolver(resolver, path):\n '''Resolves VirtualEnvironments in CPENV_HOME'''\n\n from .api import get_home_path\n\n path = unipath(get_home_path(), path)\n\n if is_environment(path):\n return VirtualEnvironment(path)\n\n raise ResolveError"}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function to\nresolve VirtualEnvironments in EnvironmentCache", "response": "def cache_resolver(resolver, path):\n '''Resolves VirtualEnvironments in EnvironmentCache'''\n\n env = resolver.cache.find(path)\n if env:\n return env\n\n raise ResolveError"}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef module_resolver(resolver, path):\n '''Resolves module in previously resolved environment.'''\n\n if resolver.resolved:\n\n if isinstance(resolver.resolved[0], VirtualEnvironment):\n env = resolver.resolved[0]\n mod = env.get_module(path)\n\n if mod:\n return mod\n\n raise ResolveError", "response": "Resolves module in previously resolved environment."}
{"SOURCE": "codesearchnet", "instruction": "Can you write a function in Python 3 where it\nresolves modules in CPENV_MODULES path and CPENV_HOME / modules", "response": "def modules_path_resolver(resolver, path):\n '''Resolves modules in CPENV_MODULES path and CPENV_HOME/modules'''\n\n from .api import get_module_paths\n\n for module_dir in get_module_paths():\n mod_path = unipath(module_dir, path)\n\n if is_module(mod_path):\n return Module(mod_path)\n\n raise ResolveError"}
{"SOURCE": "codesearchnet", "instruction": "How would you code a function in Python 3 to\nresolve modules in currently active environment.", "response": "def active_env_module_resolver(resolver, path):\n '''Resolves modules in currently active environment.'''\n\n from .api import get_active_env\n\n env = get_active_env()\n if not env:\n raise ResolveError\n\n mod = env.get_module(path)\n if not mod:\n raise ResolveError\n\n return mod"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef redirect_resolver(resolver, path):\n '''Resolves environment from .cpenv file...recursively walks up the tree\n in attempt to find a .cpenv file'''\n\n if not os.path.exists(path):\n raise ResolveError\n\n if os.path.isfile(path):\n path = os.path.dirname(path)\n\n for root, _, _ in walk_up(path):\n if is_redirecting(root):\n env_paths = redirect_to_env_paths(unipath(root, '.cpenv'))\n r = Resolver(*env_paths)\n return r.resolve()\n\n raise ResolveError", "response": "Resolves environment from. cpenv file... recursively walks up the tree\n in attempt to find a. cpenv file and returns a dict of environment paths to the environment paths that were redirected."}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef _engine_affinity(obj):\n from distob import engine\n this_engine = engine.eid\n if isinstance(obj, numbers.Number) or obj is None:\n return (this_engine, 0)\n elif hasattr(obj, '__engine_affinity__'):\n # This case includes Remote subclasses and DistArray\n return obj.__engine_affinity__\n else:\n return (this_engine, _rough_size(obj))", "response": "Which engine or engines are preferred for processing this object\n "}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script to\nmove an input to a new location.", "response": "def _ufunc_move_input(obj, location, bshape):\n \"\"\"Copy ufunc input `obj` to new engine location(s) unless obj is scalar.\n\n If the input is requested to be distributed to multiple engines, this\n function will also take care of broadcasting along the distributed axis.\n\n If the input obj is a scalar, it will be passed through unchanged.\n\n Args:\n obj (array_like or scalar): one of the inputs to a ufunc\n location (integer or tuple): If an integer, this specifies a single\n engine id to which an array input should be moved. If it is a tuple,\n location[0] is a list of engine ids for distributing the array input\n and location[1] an integer indicating which axis should be distributed.\n bshape (tuple): The shape to which the input will ultimately be broadcast\n\n Returns:\n array_like or RemoteArray or DistArray or scalar\n \"\"\"\n if (not hasattr(type(obj), '__array_interface__') and\n not isinstance(obj, Remote) and\n (isinstance(obj, string_types) or\n not isinstance(obj, Sequence))):\n # then treat it as a scalar\n return obj\n from distob import engine\n this_engine = engine.eid\n if location == this_engine:\n # move obj to the local host, if not already here\n if isinstance(obj, Remote) or isinstance(obj, DistArray):\n return gather(obj)\n else:\n return obj\n elif isinstance(location, numbers.Integral):\n # move obj to a single remote engine\n if isinstance(obj, Remote) and obj._ref.id.engine == location:\n #print('no data movement needed!')\n return obj\n obj = gather(obj)\n return _directed_scatter(obj, axis=None, destination=location)\n else:\n # location is a tuple (list of engine ids, distaxis) indicating that\n # obj should be distributed.\n engine_ids, distaxis = location\n if not isinstance(obj, DistArray):\n gather(obj)\n if isinstance(obj, Sequence):\n obj = np.array(obj)\n if obj.ndim < len(bshape):\n ix = (np.newaxis,)*(len(bshape)-obj.ndim) + (slice(None),)*obj.ndim\n obj = obj[ix]\n if (isinstance(obj, DistArray) and distaxis == obj._distaxis and\n engine_ids == [ra._ref.id.engine for ra in obj._subarrays]):\n #print('no data movement needed!')\n return obj\n obj = gather(obj)\n if obj.shape[distaxis] == 1:\n # broadcast this axis across engines\n subarrays = [_directed_scatter(obj, None, m) for m in engine_ids]\n return DistArray(subarrays, distaxis)\n else:\n return _directed_scatter(obj, distaxis, destination=engine_ids)"}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef _ufunc_dispatch(ufunc, method, i, inputs, **kwargs):\n #__print_ufunc(ufunc, method, i, inputs, **kwargs)\n if 'out' in kwargs and kwargs['out'] is not None:\n raise Error('for distributed ufuncs `out=` is not yet implemented')\n nin = 2 if ufunc is np.dot else ufunc.nin\n if nin is 1 and method == '__call__':\n return vectorize(ufunc.__call__)(inputs[0], **kwargs)\n elif nin is 2 and method == '__call__':\n from distob import engine\n here = engine.eid\n # Choose best location for the computation, possibly distributed:\n locs, weights = zip(*[_engine_affinity(a) for a in inputs])\n # for DistArrays, adjust preferred distaxis to account for broadcasting\n bshape = _broadcast_shape(*inputs)\n locs = list(locs)\n for i, loc in enumerate(locs):\n if isinstance(loc, _TupleType):\n num_new_axes = len(bshape) - inputs[i].ndim\n if num_new_axes > 0:\n locs[i] = (locs[i][0], locs[i][1] + num_new_axes)\n if ufunc is np.dot:\n locs = [here if isinstance(m, _TupleType) else m for m in locs]\n if locs[0] == locs[1]:\n location = locs[0]\n else:\n # TODO: More accurately penalize the increased data movement if we\n # choose to distribute an axis that requires broadcasting.\n smallest = 0 if weights[0] <= weights[1] else 1\n largest = 1 - smallest\n if locs[0] is here or locs[1] is here:\n location = here if weights[0] == weights[1] else locs[largest]\n else:\n # Both inputs are on remote engines. With the current\n # implementation, data on one remote engine can only be moved\n # to another remote engine via the client. Cost accordingly:\n if weights[smallest]*2 < weights[largest] + weights[smallest]:\n location = locs[largest]\n else:\n location = here\n # Move both inputs to the chosen location:\n inputs = [_ufunc_move_input(a, location, bshape) for a in inputs]\n # Execute computation:\n if location is here:\n return ufunc.__call__(inputs[0], inputs[1], **kwargs)\n else:\n if isinstance(location, numbers.Integral):\n # location is a single remote engine\n return call(ufunc.__call__, inputs[0], inputs[1], **kwargs)\n else:\n # location is a tuple (list of engine ids, distaxis) implying\n # that the moved inputs are now distributed arrays (or scalar)\n engine_ids, distaxis = location\n n = len(engine_ids)\n is_dist = tuple(isinstance(a, DistArray) for a in inputs)\n assert(is_dist[0] or is_dist[1])\n for i in 0, 1:\n if is_dist[i]:\n ndim = inputs[i].ndim\n assert(inputs[i]._distaxis == distaxis)\n assert(inputs[i]._n == n)\n def _remote_ucall(inputs, **kwargs):\n \"\"\"(Executed on a remote or local engine) call the ufunc\"\"\"\n return ufunc.__call__(inputs[0], inputs[1], **kwargs)\n results = []\n kwargs = kwargs.copy()\n kwargs['block'] = False\n kwargs['prefer_local'] = False\n for j in range(n):\n subinputs = tuple(inputs[i]._subarrays[j] if \n is_dist[i] else inputs[i] for i in (0, 1))\n results.append(call(_remote_ucall, subinputs, **kwargs))\n results = [convert_result(ar) for ar in results]\n return DistArray(results, distaxis)\n elif ufunc.nin > 2:\n raise Error(u'Distributing ufuncs with >2 inputs is not yet supported')\n else:\n raise Error(u'Distributed ufunc.%s() is not yet implemented' % method)", "response": "Dispatches a ufunc to the local host or remote engine."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef transpose(a, axes=None):\n if isinstance(a, np.ndarray):\n return np.transpose(a, axes)\n elif isinstance(a, RemoteArray):\n return a.transpose(*axes)\n elif isinstance(a, Remote):\n return _remote_to_array(a).transpose(*axes)\n elif isinstance(a, DistArray):\n if axes is None:\n axes = range(a.ndim - 1, -1, -1)\n axes = list(axes)\n if len(set(axes)) < len(axes):\n raise ValueError(\"repeated axis in transpose\")\n if sorted(axes) != list(range(a.ndim)):\n raise ValueError(\"axes don't match array\")\n distaxis = a._distaxis\n new_distaxis = axes.index(distaxis)\n new_subarrays = [ra.transpose(*axes) for ra in a._subarrays]\n return DistArray(new_subarrays, new_distaxis)\n else:\n return np.transpose(a, axes)", "response": "Returns a view of the array with axes transposed."}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef rollaxis(a, axis, start=0):\n if isinstance(a, np.ndarray):\n return np.rollaxis(a, axis, start)\n if axis not in range(a.ndim):\n raise ValueError(\n 'rollaxis: axis (%d) must be >=0 and < %d' % (axis, a.ndim))\n if start not in range(a.ndim + 1):\n raise ValueError(\n 'rollaxis: start (%d) must be >=0 and < %d' % (axis, a.ndim+1))\n axes = list(range(a.ndim))\n axes.remove(axis)\n axes.insert(start, axis)\n return transpose(a, axes)", "response": "Roll the specified axis backwards until it lies in a given position."}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function to\ninsert a new axis corresponding to a given position in the array shape", "response": "def expand_dims(a, axis):\n \"\"\"Insert a new axis, corresponding to a given position in the array shape\n\n Args:\n a (array_like): Input array.\n axis (int): Position (amongst axes) where new axis is to be inserted.\n \"\"\"\n if hasattr(a, 'expand_dims') and hasattr(type(a), '__array_interface__'):\n return a.expand_dims(axis)\n else:\n return np.expand_dims(a, axis)"}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function for\nconcatenating a sequence of arrays together.", "response": "def concatenate(tup, axis=0):\n \"\"\"Join a sequence of arrays together. \n Will aim to join `ndarray`, `RemoteArray`, and `DistArray` without moving \n their data, if they happen to be on different engines.\n\n Args:\n tup (sequence of array_like): Arrays to be concatenated. They must have\n the same shape, except in the dimension corresponding to `axis`.\n axis (int, optional): The axis along which the arrays will be joined.\n\n Returns: \n res: `ndarray`, if inputs were all local\n `RemoteArray`, if inputs were all on the same remote engine\n `DistArray`, if inputs were already scattered on different engines\n \"\"\"\n from distob import engine\n if len(tup) is 0:\n raise ValueError('need at least one array to concatenate')\n first = tup[0]\n others = tup[1:]\n # allow subclasses to provide their own implementations of concatenate:\n if (hasattr(first, 'concatenate') and \n hasattr(type(first), '__array_interface__')):\n return first.concatenate(others, axis)\n # convert all arguments to arrays/RemoteArrays if they are not already:\n arrays = []\n for ar in tup:\n if isinstance(ar, DistArray):\n if axis == ar._distaxis:\n arrays.extend(ar._subarrays)\n else:\n # Since not yet implemented arrays distributed on more than\n # one axis, will fetch and re-scatter on the new axis:\n arrays.append(gather(ar))\n elif isinstance(ar, RemoteArray):\n arrays.append(ar)\n elif isinstance(ar, Remote):\n arrays.append(_remote_to_array(ar))\n elif hasattr(type(ar), '__array_interface__'):\n # then treat as a local ndarray\n arrays.append(ar)\n else:\n arrays.append(np.array(ar))\n if all(isinstance(ar, np.ndarray) for ar in arrays):\n return np.concatenate(arrays, axis)\n total_length = 0\n # validate dimensions are same, except for axis of concatenation:\n commonshape = list(arrays[0].shape)\n commonshape[axis] = None # ignore this axis for shape comparison\n for ar in arrays:\n total_length += ar.shape[axis]\n shp = list(ar.shape)\n shp[axis] = None\n if shp != commonshape:\n raise ValueError('incompatible shapes for concatenation')\n # set sensible target block size if splitting subarrays further:\n blocksize = ((total_length - 1) // engine.nengines) + 1\n rarrays = []\n for ar in arrays:\n if isinstance(ar, DistArray):\n rarrays.extend(ar._subarrays)\n elif isinstance(ar, RemoteArray):\n rarrays.append(ar)\n else:\n da = _scatter_ndarray(ar, axis, blocksize)\n for ra in da._subarrays:\n rarrays.append(ra)\n del da\n del arrays\n # At this point rarrays is a list of RemoteArray to be concatenated\n eid = rarrays[0]._id.engine\n if all(ra._id.engine == eid for ra in rarrays):\n # Arrays to be joined are all on the same engine\n if eid == engine.eid:\n # Arrays are all local\n return concatenate([gather(r) for r in rarrays], axis)\n else:\n return call(concatenate, rarrays, axis)\n else:\n # Arrays to be joined are on different engines.\n # TODO: consolidate any consecutive arrays already on same engine\n return DistArray(rarrays, axis)"}
{"SOURCE": "codesearchnet", "instruction": "How would you code a function in Python 3 to\nstack arrays in sequence vertically ( row wise ) handling RemoteArray and DistArray without moving data.", "response": "def vstack(tup):\n \"\"\"Stack arrays in sequence vertically (row wise), \n handling ``RemoteArray`` and ``DistArray`` without moving data.\n\n Args:\n tup (sequence of array_like)\n\n Returns: \n res: `ndarray`, if inputs were all local\n `RemoteArray`, if inputs were all on the same remote engine\n `DistArray`, if inputs were already scattered on different engines\n \"\"\"\n # Follow numpy.vstack behavior for 1D arrays:\n arrays = list(tup)\n for i in range(len(arrays)):\n if arrays[i].ndim is 1:\n arrays[i] = arrays[i][np.newaxis, :]\n return concatenate(tup, axis=0)"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script for\nstacking arrays in sequence horizontally ( column wise ) handling RemoteArray and DistArray without moving data.", "response": "def hstack(tup):\n \"\"\"Stack arrays in sequence horizontally (column wise), \n handling ``RemoteArray`` and ``DistArray`` without moving data.\n\n Args:\n tup (sequence of array_like)\n\n Returns: \n res: `ndarray`, if inputs were all local\n `RemoteArray`, if inputs were all on the same remote engine\n `DistArray`, if inputs were already scattered on different engines\n \"\"\"\n # Follow numpy.hstack behavior for 1D arrays:\n if all(ar.ndim is 1 for ar in tup):\n return concatenate(tup, axis=0)\n else:\n return concatenate(tup, axis=1)"}
{"SOURCE": "codesearchnet", "instruction": "Can you create a Python 3 function that\nstacks arrays in sequence depth wise.", "response": "def dstack(tup):\n \"\"\"Stack arrays in sequence depth wise (along third dimension), \n handling ``RemoteArray`` and ``DistArray`` without moving data.\n\n Args:\n tup (sequence of array_like)\n\n Returns: \n res: `ndarray`, if inputs were all local\n `RemoteArray`, if inputs were all on the same remote engine\n `DistArray`, if inputs were already scattered on different engines\n \"\"\"\n # Follow numpy.dstack behavior for 1D and 2D arrays:\n arrays = list(tup)\n for i in range(len(arrays)):\n if arrays[i].ndim is 1:\n arrays[i] = arrays[i][np.newaxis, :]\n if arrays[i].ndim is 2:\n arrays[i] = arrays[i][:, :, np.newaxis]\n return concatenate(arrays, axis=2)"}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef _broadcast_shape(*args):\n #TODO: currently incorrect result if a Sequence is provided as an input\n shapes = [a.shape if hasattr(type(a), '__array_interface__')\n else () for a in args]\n ndim = max(len(sh) for sh in shapes) # new common ndim after broadcasting\n for i, sh in enumerate(shapes):\n if len(sh) < ndim:\n shapes[i] = (1,)*(ndim - len(sh)) + sh\n return tuple(max(sh[ax] for sh in shapes) for ax in range(ndim))", "response": "Return the shape that would result from broadcasting the inputs"}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef mean(a, axis=None, dtype=None, out=None, keepdims=False):\n if (isinstance(a, np.ndarray) or\n isinstance(a, RemoteArray) or\n isinstance(a, DistArray)):\n return a.mean(axis=axis, dtype=dtype, out=out, keepdims=keepdims)\n else:\n return np.mean(a, axis=axis, dtype=dtype, out=out, keepdims=keepdims)", "response": "Compute the arithmetic mean along the specified axis."}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function to\nforce update of a local cached copy of the real object", "response": "def _fetch(self):\n \"\"\"forces update of a local cached copy of the real object\n (regardless of the preference setting self.cache)\"\"\"\n if not self._obcache_current:\n from distob import engine\n ax = self._distaxis\n self._obcache = concatenate([ra._ob for ra in self._subarrays], ax)\n # let subarray obcaches and main obcache be views on same memory:\n for i in range(self._n):\n ix = [slice(None)] * self.ndim\n ix[ax] = slice(self._si[i], self._si[i+1])\n self._subarrays[i]._obcache = self._obcache[tuple(ix)]\n self._obcache_current = True\n # now prefer local processing:\n self.__engine_affinity__ = (\n engine.eid, self.__engine_affinity__[1])"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef _tosubslices(self, sl):\n N = self.shape[self._distaxis]\n start, stop, step = sl.start, sl.stop, sl.step\n if step is None:\n step = 1\n ss = []\n ms = []\n if step > 0:\n if start is None:\n start = 0\n if stop is None:\n stop = N\n subs = range(0, self._n)\n for s in subs:\n low = self._si[s]\n high = self._si[s + 1]\n first = low + ((low - start) % step)\n last = high + ((high - start) % step)\n if start < high and stop > low and first < high:\n ss.append(s)\n substart = max(first, start) - low\n substop = min(last, stop) - low\n ms.append(slice(substart, substop, step))\n elif step < 0:\n if start is None:\n start = N - 1\n if stop is None:\n stop = -1\n subs = range(self._n - 1, -1, -1)\n for s in subs:\n low = self._si[s]\n high = self._si[s + 1]\n first = high + step + ((high - start) % step)\n last = low + step + ((low - start) % step)\n if start >= low and stop < high and first >= low:\n ss.append(s)\n substart = min(first, start) - low\n substop = max(last + step, stop) - low\n if substop < 0:\n substop = None\n ms.append(slice(substart, substop, step))\n else:\n raise ValueError('slice step cannot be zero')\n return ss, ms", "response": "Maps a slice object for whole array to slice objects for subarrays."}
{"SOURCE": "codesearchnet", "instruction": "Can you create a Python 3 function that\nchecks if the given shapes are all the same when ignoring axis ax.", "response": "def _valid_distaxis(shapes, ax):\n \"\"\"`ax` is a valid candidate for a distributed axis if the given\n subarray shapes are all the same when ignoring axis `ax`\"\"\"\n compare_shapes = np.vstack(shapes)\n if ax < compare_shapes.shape[1]:\n compare_shapes[:, ax] = -1\n return np.count_nonzero(compare_shapes - compare_shapes[0]) == 0"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function that can\nreturn a new DistArray with the same shape as self but with the same dimensions.", "response": "def expand_dims(self, axis):\n \"\"\"Insert a new axis, at a given position in the array shape\n Args:\n axis (int): Position (amongst axes) where new axis is to be inserted.\n \"\"\"\n if axis == -1:\n axis = self.ndim\n if axis <= self._distaxis:\n subaxis = axis\n new_distaxis = self._distaxis + 1\n else:\n subaxis = axis - 1\n new_distaxis = self._distaxis\n new_subarrays = [expand_dims(ra, subaxis) for ra in self._subarrays]\n return DistArray(new_subarrays, new_distaxis)"}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef mean(self, axis=None, dtype=None, out=None, keepdims=False):\n if axis == -1:\n axis = self.ndim\n if axis is None:\n results = vectorize(mean)(self, axis, dtype, keepdims=False)\n weights = self._sublengths\n res = np.average(results, axis=None, weights=weights)\n if keepdims:\n for i in range(self.ndim):\n res = expand_dims(res, res.ndim)\n elif axis == self._distaxis:\n results = vectorize(mean)(self, axis, dtype, keepdims=True)\n results = gather(results)\n # Average manually (np.average doesn't preserve ndarray subclasses)\n weights = (np.array(self._sublengths, dtype=np.float64) /\n sum(self._sublengths))\n ix = [slice(None)] * self.ndim\n ix[axis] = 0\n res = results[ix] * weights[0]\n for i in range(1, self._n):\n ix[axis] = i\n res = res + results[ix] * weights[i]\n if keepdims:\n res = expand_dims(res, axis)\n else:\n res = vectorize(mean)(self, axis, dtype, keepdims=False)\n if keepdims:\n res = expand_dims(res, axis)\n if out is not None:\n out[:] = res\n return res", "response": "Compute the arithmetic mean along the specified axis."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function that can\nreturn True if successful False if failure", "response": "def run(*args, **kwargs):\n '''Returns True if successful, False if failure'''\n\n kwargs.setdefault('env', os.environ)\n kwargs.setdefault('shell', True)\n\n try:\n subprocess.check_call(' '.join(args), **kwargs)\n return True\n except subprocess.CalledProcessError:\n logger.debug('Error running: {}'.format(args))\n return False"}
{"SOURCE": "codesearchnet", "instruction": "Implement a Python 3 function for\nreturning a command to launch a subshell", "response": "def cmd():\n '''Return a command to launch a subshell'''\n\n if platform == 'win':\n return ['cmd.exe', '/K']\n\n elif platform == 'linux':\n ppid = os.getppid()\n ppid_cmdline_file = '/proc/{0}/cmdline'.format(ppid)\n try:\n with open(ppid_cmdline_file) as f:\n cmd = f.read()\n if cmd.endswith('\\x00'):\n cmd = cmd[:-1]\n cmd = cmd.split('\\x00')\n return cmd + [binpath('subshell.sh')]\n except:\n cmd = 'bash'\n\n else:\n cmd = 'bash'\n\n return [cmd, binpath('subshell.sh')]"}
{"SOURCE": "codesearchnet", "instruction": "Implement a function in Python 3 to\ngenerate a prompt with a given prefix", "response": "def prompt(prefix=None, colored=True):\n '''Generate a prompt with a given prefix\n\n linux/osx: [prefix] user@host cwd $\n win: [prefix] cwd:\n '''\n\n if platform == 'win':\n return '[{0}] $P$G'.format(prefix)\n else:\n if colored:\n return (\n '[{0}] ' # White prefix\n '\\\\[\\\\033[01;32m\\\\]\\\\u@\\\\h\\\\[\\\\033[00m\\\\] ' # Green user@host\n '\\\\[\\\\033[01;34m\\\\]\\\\w $ \\\\[\\\\033[00m\\\\]' # Blue cwd $\n ).format(prefix)\n return '[{0}] \\\\u@\\\\h \\\\w $ '.format(prefix)"}
{"SOURCE": "codesearchnet", "instruction": "Can you implement a function in Python 3 that\nadds a file to the file repository.", "response": "def add_file(self, file, **kwargs):\n \"\"\"Append a file to file repository.\n\n For file monitoring, monitor instance needs file.\n Please put the name of file to `file` argument.\n\n :param file: the name of file you want monitor.\n\n \"\"\"\n\n if os.access(file, os.F_OK):\n\n if file in self.f_repository:\n raise DuplicationError(\"file already added.\")\n\n self.f_repository.append(file)\n\n else:\n raise IOError(\"file not found.\")"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef add_files(self, filelist, **kwargs):\n\n # check filelist is list type\n if not isinstance(filelist, list):\n raise TypeError(\"request the list type.\")\n\n for file in filelist:\n self.add_file(file)", "response": "Append files to the repository using this."}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef monitor(self, sleep=5):\n\n\n manager = FileModificationObjectManager()\n\n timestamps = {}\n filebodies = {}\n\n # register original timestamp and filebody to dict\n for file in self.f_repository:\n timestamps[file] = self._get_mtime(file)\n filebodies[file] = open(file).read()\n\n\n while True:\n\n for file in self.f_repository:\n\n mtime = timestamps[file]\n fbody = filebodies[file]\n\n modified = self._check_modify(file, mtime, fbody)\n\n # file not modify -> continue\n if not modified:\n continue\n\n # file modifies -> create the modification object\n\n new_mtime = self._get_mtime(file)\n new_fbody = open(file).read()\n\n obj = FileModificationObject(\n file,\n (mtime, new_mtime),\n (fbody, new_fbody) )\n\n # overwrite new timestamp and filebody\n timestamps[file] = new_mtime\n filebodies[file] = new_fbody\n\n\n # append file modification object to manager\n manager.add_object(obj)\n\n # return new modification object\n yield obj\n\n time.sleep(sleep)", "response": "Monitor file modification using timestamp and file body data and yield a FileModificationObject."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script for\ninitializing a Flask application for use with this extension.", "response": "def init_app(self, app):\n \"\"\"Initialize a :class:`~flask.Flask` application for use with\n this extension.\n \"\"\"\n self._jobs = []\n\n if not hasattr(app, 'extensions'):\n app.extensions = {}\n\n app.extensions['restpoints'] = self\n app.restpoints_instance = self\n app.add_url_rule('/ping', 'ping', ping)\n app.add_url_rule('/time', 'time', time)\n app.add_url_rule('/status', 'status', status(self._jobs))"}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef add_status_job(self, job_func, name=None, timeout=3):\n job_name = job_func.__name__ if name is None else name\n job = (job_name, timeout, job_func)\n self._jobs.append(job)", "response": "Adds a job to be included during status requests to the status endpoint."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef _pipepager(text, cmd, color):\n import subprocess\n env = dict(os.environ)\n\n # If we're piping to less we might support colors under the\n # condition that\n cmd_detail = cmd.rsplit('/', 1)[-1].split()\n if color is None and cmd_detail[0] == 'less':\n less_flags = os.environ.get('LESS', '') + ' '.join(cmd_detail[1:])\n if not less_flags:\n env['LESS'] = '-R'\n color = True\n elif 'r' in less_flags or 'R' in less_flags:\n color = True\n\n if not color:\n text = strip_ansi(text)\n\n c = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE,\n env=env)\n encoding = get_best_encoding(c.stdin)\n try:\n c.stdin.write(text.encode(encoding, 'replace'))\n c.stdin.close()\n except (IOError, KeyboardInterrupt):\n pass\n\n # Less doesn't respect ^C, but catches it for its own UI purposes (aborting\n # search or other commands inside less).\n #\n # That means when the user hits ^C, the parent process (click) terminates,\n # but less is still alive, paging the output and messing up the terminal.\n #\n # If the user wants to make the pager exit on ^C, they should set\n # `LESS='-K'`. It's not our decision to make.\n while True:\n try:\n c.wait()\n except KeyboardInterrupt:\n pass\n else:\n break", "response": "Page through text by feeding it to another program."}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef _get_funky(func):\n\n if isinstance(func, str):\n try:\n func = getattr(np, func)\n except:\n raise NameError(\"Nom de fonction non comprise\")\n return func", "response": "Renvoie un nom pass\u00e9 en param\u00e8tre un nom pass\u00e9 un param\u00e8tre un nom pass\u00e9 un param\u00e8tre un nom pass\u00e9 un param\u00e8tre un nom pass\u00e9 un param\u00e8tre"}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef profil_journalier(df, func='mean'):\n\n func = _get_funky(func)\n res = df.groupby(lambda x: x.hour).aggregate(func)\n return res", "response": "Calculates du profil journalier un tableau un tableau de donn\u00e9es"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef profil_hebdo(df, func='mean'):\n\n func = _get_funky(func)\n res = df.groupby(lambda x: x.weekday).aggregate(func)\n # On met des noms de jour \u00e0 la place des num\u00e9ros dans l'index\n res.index = [cal.day_name[i] for i in range(0,7)]\n return res", "response": "A helper function to calculate a list of unique calendars in a DataFrame."}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef profil_annuel(df, func='mean'):\n\n func = _get_funky(func)\n res = df.groupby(lambda x: x.month).aggregate(func)\n # On met des noms de mois \u00e0 la place des num\u00e9ros dans l'index\n res.index = [cal.month_name[i] for i in range(1,13)]\n return res", "response": "A helper function to calculate un annuelle s\u00e9rie temporelle\n "}
{"SOURCE": "codesearchnet", "instruction": "Can you implement a function in Python 3 that\nformats un donn\u00e9e du donn\u00e9e du donn\u00e9e et get_*.", "response": "def _format(noms):\n \"\"\"\n Formate une donn\u00e9e d'entr\u00e9e pour \u00eatre exploitable dans les fonctions liste_*\n et get_*.\n\n Param\u00e8tres:\n noms: cha\u00eene de caract\u00e8re, liste ou tuples de cha\u00eenes de caract\u00e8res ou\n pandas.Series de cha\u00eenes de caract\u00e8res.\n\n Retourne:\n Une cha\u00eenes de caract\u00e8res dont chaque \u00e9l\u00e9ment est s\u00e9par\u00e9 du suivant par les\n caract\u00e8res ',' (simples quotes comprises)\n\n \"\"\"\n if isinstance(noms, (list, tuple, pd.Series)):\n noms = ','.join(noms)\n noms = noms.replace(\",\", \"','\")\n return noms"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef date_range(debut, fin, freq):\n\n debut_dt = debut.replace(hour=0, minute=0, second=0, microsecond=0)\n fin_dt = fin.replace(hour=23, minute=59, second=0, microsecond=0)\n if freq in ('M', 'A'): # Calle la fr\u00e9quence sur le d\u00e9but de mois/ann\u00e9e\n freq += 'S'\n debut_dt = debut_dt.replace(day=1, minute=0, second=0, microsecond=0)\n fin_dt = fin_dt.replace(day=1, minute=0, second=0, microsecond=0)\n dates_completes = pd.date_range(start=debut_dt, end=fin_dt, freq=freq)\n return dates_completes", "response": "Return a list of dates in the order of the given date."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script for\nconnecting to the XAIR server.", "response": "def _connect(self):\n \"\"\"\n Connexion \u00e0 la base XAIR\n \"\"\"\n\n try:\n # On passe par Oracle Instant Client avec le TNS ORA_FULL\n self.conn = cx_Oracle.connect(self._ORA_FULL)\n self.cursor = self.conn.cursor()\n print('XAIR: Connexion \u00e9tablie')\n except cx_Oracle.Error as e:\n print(\"Erreur: %s\" % (e))\n raise cx_Oracle.Error('Echec de connexion')"}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef liste_parametres(self, parametre=None):\n condition = \"\"\n if parametre:\n condition = \"WHERE CCHIM='%s'\" % parametre\n _sql = \"\"\"SELECT CCHIM AS PARAMETRE,\n NCON AS LIBELLE,\n NOPOL AS CODE\n FROM NOM_MESURE %s ORDER BY CCHIM\"\"\" % condition\n return psql.read_sql(_sql, self.conn)", "response": "Liste des parametres de la lista de la classe."}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef liste_campagnes(self, campagne=None):\n\n condition = \"\"\n if campagne:\n condition = \"WHERE NOM_COURT_CM='%s' \"\"\" % campagne\n _sql = \"\"\"SELECT\n NOM_COURT_CM AS CAMPAGNE,\n IDENTIFIANT AS STATION,\n LIBELLE AS LIBELLE_CM,\n DATEDEB AS DEBUT,\n DATEFIN AS FIN\n FROM CAMPMES\n INNER JOIN CAMPMES_STATION USING (NOM_COURT_CM)\n INNER JOIN STATION USING (NOM_COURT_SIT)\n %s ORDER BY DATEDEB DESC\"\"\" % condition\n return psql.read_sql(_sql, self.conn)", "response": "Liste des campagnes de mesure et des stations associ\u00e9es campagne. Si d\u00e9finie liste des stations associ\u00e9es campagne."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef get_mesures(self, mes, debut=None, fin=None, freq='H', format=None,\n dayfirst=False, brut=False):\n \"\"\"\n R\u00e9cup\u00e9ration des donn\u00e9es de mesure.\n\n Param\u00e8tres:\n mes: Un nom de mesure ou plusieurs s\u00e9par\u00e9es par des virgules, une liste\n (list, tuple, pandas.Series) de noms\n debut: Chaine de caract\u00e8re ou objet datetime d\u00e9crivant la date de d\u00e9but.\n D\u00e9faut=date du jour\n fin: Chaine de caract\u00e8re ou objet datetime d\u00e9crivant la date de fin.\n D\u00e9faut=date de d\u00e9but\n freq: fr\u00e9quence de temps. '15T' | 'H' | 'D' | 'M' | 'A' (15T pour quart-horaire)\n format: chaine de caract\u00e8re d\u00e9crivant le format des dates (ex:\"%Y-%m-%d\"\n pour debut/fin=\"2013-01-28\"). Appeler pyair.date.strtime_help() pour\n obtenir la liste des codes possibles.\n Defaut=\"%Y-%m-%d\"\n dayfirst: Si aucun format n'est fourni et que les dates sont des chaines\n de caract\u00e8res, aide le d\u00e9crypteur \u00e0 transformer la date en objet datetime\n en sp\u00e9cifiant que les dates commencent par le jour (ex:11/09/2012\n pourrait \u00eatre interpret\u00e9 comme le 09 novembre si dayfirst=False)\n brut: si oui ou non renvoyer le dataframe brut, non invalid\u00e9, et les\n codes d'\u00e9tat des mesures\n Defaut=False\n\n Retourne:\n Un dataframe contenant toutes les mesures demand\u00e9es.\n Si brut=True, renvoie le dataframe des mesures brutes non invalid\u00e9es et\n le dataframe des codes d'\u00e9tats.\n Le dataframe valide (net) peut \u00eatre alors recalcul\u00e9 en faisant:\n brut, etats = xr.get_mesure(..., brut=True)\n invalides = etats_to_invalid(etats)\n net = brut.mask(invalides)\n\n \"\"\"\n\n def create_index(index, freq):\n \"\"\"\n Nouvel index [id, date] avec date format\u00e9 suivant le pas de temps voulu\n index: index de l'ancien dataframe, tel que [date \u00e0 minuit, date \u00e0 ajouter]\n\n \"\"\"\n decalage = 1 # sert \u00e0 compenser l'aberration des temps qui veut qu'on marque sur la fin d'une p\u00e9riode (ex: \u00e0 24h, la pollution de 23 \u00e0 minuit)\n if freq == 'T' or freq == '15T':\n f = pd.tseries.offsets.Minute\n decalage = 15\n if freq == 'H':\n f = pd.tseries.offsets.Hour\n if freq == 'D':\n f = pd.tseries.offsets.Day\n if freq == 'M':\n f = pd.tseries.offsets.MonthBegin\n if freq == 'A':\n f = pd.tseries.offsets.YearBegin\n else:\n f = pd.tseries.offsets.Hour\n new_index = [date + f(int(delta) - decalage) for date, delta in index]\n return new_index\n\n # Reformatage du champ des noms de mesure\n mes = _format(mes)\n\n # Analyse des champs dates\n debut = to_date(debut, dayfirst, format)\n if not fin:\n fin = debut\n else:\n fin = to_date(fin, dayfirst, format)\n\n\n # La freq de temps Q n'existe pas, on passe d'abord par une fr\u00e9quence 15 minutes\n if freq in ('Q', 'T'):\n freq = '15T'\n\n # S\u00e9lection des champs et de la table en fonctions de la fr\u00e9quence de temps souhait\u00e9e\n if freq == '15T':\n diviseur = 96\n champ_val = ','.join(['Q_M%02i AS \"%i\"' % (x, x * 15) for x in range(1, diviseur + 1)])\n champ_code = 'Q_ETATV'\n table = 'JOURNALIER'\n elif freq == 'H':\n diviseur = 24\n champ_val = ','.join(['H_M%02i AS \"%i\"' % (x, x) for x in range(1, diviseur + 1)])\n champ_code = 'H_ETAT'\n table = 'JOURNALIER'\n elif freq == 'D':\n diviseur = 1\n champ_val = 'J_M01 AS \"1\"'\n champ_code = 'J_ETAT'\n table = 'JOURNALIER'\n elif freq == 'M':\n diviseur = 12\n champ_val = ','.join(['M_M%02i AS \"%i\"' % (x, x) for x in range(1, diviseur + 1)])\n champ_code = 'M_ETAT'\n table = 'MOIS'\n elif freq == 'A':\n diviseur = 1\n champ_val = 'A_M01 AS \"1\"'\n champ_code = 'A_ETAT'\n table = 'MOIS'\n else:\n raise ValueError(\"freq doit \u00eatre T, H, D, M ou A\")\n\n if table == 'JOURNALIER':\n champ_date = 'J_DATE'\n debut_db = debut\n fin_db = fin\n else:\n champ_date = 'M_DATE'\n # Pour les freq='M' et 'A', la table contient toutes les valeurs sur une\n # ann\u00e9e enti\u00e8re. Pour ne pas perturber la r\u00e9cup\u00e9ration si on passait des\n # dates en milieu d'ann\u00e9e, on transforme les dates pour \u00eatre cal\u00e9es en d\u00e9but\n # et en fin d'ann\u00e9e. Le recadrage se fera plus loin dans le code, lors du reindex\n debut_db = debut.replace(month=1, day=1, hour=0, minute=0)\n fin_db = fin.replace(month=12, day=31, hour=23, minute=0)\n\n debut_db = debut_db.strftime(\"%Y-%m-%d\")\n fin_db = fin_db.strftime(\"%Y-%m-%d\")\n\n # R\u00e9cup\u00e9ration des valeurs et codes d'\u00e9tats associ\u00e9s\n _sql = \"\"\"SELECT\n IDENTIFIANT as \"id\",\n {champ_date} as \"date\",\n {champ_code} as \"etat\",\n {champ_val}\n FROM {table}\n INNER JOIN MESURE USING (NOM_COURT_MES)\n WHERE IDENTIFIANT IN ('{mes}')\n AND {champ_date} BETWEEN TO_DATE('{debut}', 'YYYY-MM-DD') AND TO_DATE('{fin}', 'YYYY-MM-DD')\n ORDER BY IDENTIFIANT, {champ_date} ASC\"\"\".format(champ_date=champ_date,\n table=table,\n champ_code=champ_code,\n mes=mes,\n champ_val=champ_val,\n debut=debut_db,\n fin=fin_db)\n ## TODO : A essayer quand la base sera en version 11g\n # _sql = \"\"\"SELECT *\n # FROM ({selection})\n # UNPIVOT (IDENTIFIANT FOR VAL IN ({champ_as}))\"\"\".format(selection=_sql,\n # champ_date=champ_date,\n # champ_as=champ_as)\n\n # On recupere les valeurs depuis la freq dans une dataframe\n rep = psql.read_sql(_sql, self.conn)\n\n # On cr\u00e9ait un multiindex pour manipuler plus facilement le dataframe\n df = rep.set_index(['id', 'date'])\n\n # Stack le dataframe pour mettre les colonnes en lignes, en supprimant la colonne des \u00e9tats\n # puis on unstack suivant l'id pour avoir les polluants en colonnes\n etats = df['etat']\n df = df.drop('etat', axis=1)\n df_stack = df.stack(dropna=False)\n df = df_stack.unstack('id')\n\n # Calcul d'un nouvel index avec les bonnes dates. L'index du df est\n # form\u00e9 du champ date \u00e0 minuit, et des noms des champs de valeurs\n # qui sont aliass\u00e9s de 1 \u00e0 24 pour les heures, ... voir champ_val.\n # On aggr\u00e8ve alors ces 2 valeurs pour avoir des dates align\u00e9es qu'on utilise alors comme index final\n index = create_index(df.index, freq)\n df.reset_index(inplace=True, drop=True)\n df['date'] = index\n df = df.set_index(['date'])\n # Traitement des codes d'\u00e9tat\n # On concat\u00e8ne les codes d'\u00e9tat pour chaque polluant\n # etats = etats.sum(level=0)\n # etats = pd.DataFrame(zip(*etats.apply(list)))\n etats = etats.unstack('id')\n etats.fillna(value=MISSING_CODE * diviseur, inplace=True)\n etats = etats.sum(axis=0)\n etats = pd.DataFrame(list(zip(*etats.apply(list))))\n etats.index = df.index\n etats.columns = df.columns\n\n # Remplacement des valeurs aux dates manquantes par des NaN\n dates_completes = date_range(debut, fin, freq)\n df = df.reindex(dates_completes)\n etats = etats.reindex(dates_completes)\n\n # Invalidation par codes d'\u00e9tat\n # Pour chaque code d'\u00e9tat, regarde si oui ou non il est invalidant en le remplacant par un bool\u00e9en\n invalid = etats_to_invalid(etats)\n\n if not brut:\n # dans le dataframe, masque toute valeur invalide par NaN\n dfn = df.mask(invalid) # DataFrame net\n return dfn\n else:\n return df, etats", "response": "Return a list of all the mesures in the current state."}
{"SOURCE": "codesearchnet", "instruction": "How would you code a function in Python 3 to\nreturn a list of manuelles of a specific site.", "response": "def get_manuelles(self, site, code_parametre, debut, fin, court=False):\n \"\"\"\n Recup\u00e9ration des mesures manuelles (labo) pour un site\n\n site: num\u00e9ro du site (voir fonction liste_sites_prelevement)\n code_parametre: code ISO du param\u00e8tre \u00e0 rechercher (C6H6=V4)\n debut: date de d\u00e9but du premier pr\u00e9l\u00e8vement\n fin: date de fin du dernier pr\u00e9l\u00e8vement\n court: Renvoie un tableau au format court ou long (colonnes)\n\n \"\"\"\n\n condition = \"WHERE MESLA.NOPOL='%s' \" % code_parametre\n condition += \"AND SITMETH.NSIT=%s \" % site\n condition += \"AND PRELEV.DATE_DEB>=TO_DATE('%s', 'YYYY-MM-DD') \" % debut\n condition += \"AND PRELEV.DATE_FIN<=TO_DATE('%s', 'YYYY-MM-DD') \" % fin\n if court == False:\n select = \"\"\"SELECT\n MESLA.LIBELLE AS MESURE,\n METH.LIBELLE AS METHODE,\n ANA.VALEUR AS VALEUR,\n MESLA.UNITE AS UNITE,\n ANA.CODE_QUALITE AS CODE_QUALITE,\n ANA.DATE_ANA AS DATE_ANALYSE,\n ANA.ID_LABO AS LABO,\n PRELEV.DATE_DEB AS DEBUT,\n PRELEV.DATE_FIN AS FIN,\n ANA.COMMENTAIRE AS COMMENTAIRE,\n SITE.LIBELLE AS SITE,\n SITE.AXE AS ADRESSE,\n COM.NOM_COMMUNE AS COMMUNE\"\"\"\n else:\n select = \"\"\"SELECT\n MESLA.LIBELLE AS MESURE,\n ANA.VALEUR AS VALEUR,\n MESLA.UNITE AS UNITE,\n ANA.CODE_QUALITE AS CODE_QUALITE,\n PRELEV.DATE_DEB AS DEBUT,\n PRELEV.DATE_FIN AS FIN,\n SITE.AXE AS ADRESSE,\n COM.NOM_COMMUNE AS COMMUNE\"\"\"\n _sql = \"\"\"%s\n FROM ANALYSE ANA\n INNER JOIN PRELEVEMENT PRELEV ON (ANA.CODE_PRELEV=PRELEV.CODE_PRELEV AND ANA.CODE_SMP=PRELEV.CODE_SMP)\n INNER JOIN MESURE_LABO MESLA ON (ANA.CODE_MES_LABO=MESLA.CODE_MES_LABO AND ANA.CODE_SMP=MESLA.CODE_SMP)\n INNER JOIN SITE_METH_PRELEV SITMETH ON (ANA.CODE_SMP=SITMETH.CODE_SMP)\n INNER JOIN METH_PRELEVEMENT METH ON (SITMETH.CODE_METH_P=METH.CODE_METH_P)\n INNER JOIN SITE_PRELEVEMENT SITE ON (SITE.NSIT=SITMETH.NSIT)\n INNER JOIN COMMUNE COM ON (COM.NINSEE=SITE.NINSEE)\n %s\n ORDER BY MESLA.NOPOL,MESLA.LIBELLE,PRELEV.DATE_DEB\"\"\" % (select, condition)\n return psql.read_sql(_sql, self.conn)"}
{"SOURCE": "codesearchnet", "instruction": "Can you create a Python 3 function that\nreturns a pandas. DataFrame with the indices of the entries in the result set.", "response": "def get_indices(self, res, debut, fin):\n \"\"\"\n R\u00e9cup\u00e9ration des indices ATMO pour un r\u00e9seau donn\u00e9.\n\n Param\u00e8tres:\n res : Nom du ou des r\u00e9seaux \u00e0 chercher (str, list, pandas.Series)\n debut: date de d\u00e9but, format YYYY-MM-JJ (str)\n fin: Date de fin, format YYYY-MM-JJ (str)\n\n \"\"\"\n res = _format(res)\n\n _sql = \"\"\"SELECT\n J_DATE AS \"date\",\n NOM_AGGLO AS \"reseau\",\n C_IND_CALCULE AS \"indice\"\n FROM RESULTAT_INDICE\n INNER JOIN GROUPE_ATMO USING (NOM_COURT_GRP)\n WHERE NOM_AGGLO IN ('%s')\n AND J_DATE BETWEEN TO_DATE('%s', 'YYYY-MM-DD') AND TO_DATE('%s', 'YYYY-MM-DD') \"\"\" % (res, debut, fin)\n rep = psql.read_sql(_sql, self.conn)\n df = rep.set_index(['reseau', 'date'])\n df = df['indice']\n df = df.unstack('reseau')\n dates_completes = date_range(to_date(debut), to_date(fin), freq='D')\n df = df.reindex(dates_completes)\n return df"}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef get_indices_et_ssi(self, reseau, debut, fin, complet=True):\n if complet:\n i_str = \"c_ind_diffuse\"\n ssi_str = \"c_ss_indice\"\n else:\n i_str = \"p_ind_diffuse\"\n ssi_str = \"p_ss_indice\"\n\n _sql = \"\"\"SELECT\n g.nom_agglo as \"reseau\",\n i.j_date as \"date\",\n max(case when i.{0}>0 then i.{0} else 0 end) indice,\n max(case when n.cchim='NO2' then ssi.{1} else 0 end) no2,\n max(case when n.cchim='PM10' then ssi.{1} else 0 end) pm10,\n max(case when n.cchim='O3' then ssi.{1} else 0 end) o3,\n max(case when n.cchim='SO2' then ssi.{1} else 0 end) so2\n FROM resultat_indice i\n INNER JOIN resultat_ss_indice ssi ON (i.nom_court_grp=ssi.nom_court_grp AND i.j_date=ssi.j_date)\n INNER JOIN groupe_atmo g ON (i.nom_court_grp=g.nom_court_grp)\n INNER JOIN nom_mesure n ON (ssi.nopol=n.nopol)\n WHERE g.nom_agglo='{2}'\n AND i.j_date BETWEEN\n TO_DATE('{3}', 'YYYY-MM-DD') AND\n TO_DATE('{4}', 'YYYY-MM-DD')\n GROUP BY\n g.nom_agglo,\n i.j_date\n ORDER BY i.j_date\"\"\".format(i_str, ssi_str, reseau, debut, fin)\n df = psql.read_sql(_sql, self.conn)\n df = df.set_index(['reseau', 'date'])\n return df", "response": "Renvoie l indice et les sous_indices\n "}
{"SOURCE": "codesearchnet", "instruction": "How would you implement a function in Python 3 that\nattempts to run a global hook by name with args", "response": "def run_global_hook(hook_name, *args):\n '''Attempt to run a global hook by name with args'''\n\n hook_finder = HookFinder(get_global_hook_path())\n hook = hook_finder(hook_name)\n if hook:\n hook.run(*args)"}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef status(jobs):\n def status_handler():\n endpoints = []\n stats = {\"endpoints\": None}\n\n executor = concurrent.futures.ThreadPoolExecutor(max_workers=5)\n # This is basically calling the below within the executor:\n #\n # >>> timeit(job[2], number=1)\n #\n # job is a tuple of (name, timeout, func) so the above is really:\n # >>> timeit(func, number=1)\n #\n #gen = ((job, executor.submit(timeit, job[2], number=1)) for job in jobs)\n #for job, future in gen:\n for job, future in [(job, executor.submit(timeit, job[2], number=1)) for job in jobs]:\n name, timeout, _ = job\n endpoint = {\"endpoint\": name}\n try:\n data = future.result(timeout=timeout)\n endpoint[\"duration\"] = data\n except concurrent.futures.TimeoutError:\n endpoint[\"error\"] = \"timeout exceeded\"\n except Exception as ex:\n endpoint[\"error\"] = str(ex)\n endpoints.append(endpoint)\n\n if len(endpoints) > 0:\n stats[\"endpoints\"] = endpoints\n\n executor.shutdown(wait=False)\n return jsonify(**stats)\n # TODO: Look into potentially cleaning up jobs that have timed-out.\n #\n # This could be done by changing jobs from a func to an object\n # that implements `def interrupt(self):` which would be used\n # to interrupt/stop/close/cleanup any resources.\n return status_handler", "response": "Handler that calls each status job in a worker pool attempting to timeout."}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef moyennes_glissantes(df, sur=8, rep=0.75):\n return pd.rolling_mean(df, window=sur, min_periods=rep * sur)", "response": "Calculates the rolling mean of moyennes glissantes"}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef nombre_depassement(df, valeur, freq=None):\n\n dep = depassement(df, valeur)\n if freq is not None:\n dep = dep.resample(freq, how='sum')\n return dep.count()", "response": "Return the nombre de d\u00e9passement d un valeur."}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef aot40_vegetation(df, nb_an):\n\n return _aot(df.tshift(1), nb_an=nb_an, limite=80, mois_debut=5, mois_fin=7,\n heure_debut=8, heure_fin=19)", "response": "Aot - 40 de la souce un AOT - 40 de la souce de la souce de la souce de la souce de la souce de la souce de la souce de la souce de la souce de la souce de la souce de la souce de la souce de la souce de la souce de la souce de la sou"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef no2(df):\n\n polluant = \"NO2\"\n\n # Le DataFrame doit \u00eatre en heure\n if not isinstance(df.index.freq, pdoffset.Hour):\n raise FreqException(\"df doit \u00eatre en heure.\")\n\n res = {\"Seuil de RI en moyenne H: 200u\": depassement(df, valeur=200),\n \"Seuil d'Alerte sur 3H cons\u00e9cutives: 400u\": consecutive(df, valeur=400, sur=3),\n \"Seuil d'Alerte sur 3J cons\u00e9cutifs: 200u\": consecutive(df.resample('D', how='max'), valeur=200, sur=3),\n \"Valeur limite pour la sant\u00e9 humaine 18H/A: 200u\": depassement(df, valeur=200),\n \"Valeur limite pour la sant\u00e9 humaine en moyenne A: 40u\": depassement(df.resample('A', how='mean'),\n valeur=40),\n \"Objectif de qualit\u00e9 en moyenne A: 40u\": depassement(df.resample('A', how='mean'), valeur=40),\n \"Protection de la v\u00e9g\u00e9tation en moyenne A: 30u\": depassement(df.resample('A', how='mean'), valeur=30),\n }\n\n return polluant, res", "response": "A helper function for calculating the non - no2 sans un terme d un no2 sans un no2 sans un no2 sans un no2 sans un no2 sans un no2 sans un no2 sans un no2 sans un no2 sans un no2 sans un no2 sans un no2 sans un no2 sans un no2 sans un no2 sans un no2 sans un no2 s"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script for\npouring les particules PM10", "response": "def pm10(df):\n \"\"\"\n Calculs r\u00e9glementaires pour les particules PM10\n\n Param\u00e8tres:\n df: DataFrame contenant les mesures, avec un index temporel\n (voir xair.get_mesure)\n\n Retourne:\n Une s\u00e9rie de r\u00e9sultats dans un DataFrame :\n ******\n unit\u00e9 (u): \u00b5g/m3 (microgramme par m\u00e8tre cube)\n\n Seuil de RI en moyenne J: 50u\n Seuil d'Alerte en moyenne J: 80u\n Valeur limite pour la sant\u00e9 humaine 35J/A: 50u\n Valeur limite pour la sant\u00e9 humaine en moyenne A: 40u\n Objectif de qualit\u00e9 en moyenne A: 30u\n\n Les r\u00e9sultats sont donn\u00e9s en terme d'heure de d\u00e9passement\n\n \"\"\"\n\n polluant = 'PM10'\n # Le DataFrame doit \u00eatre en jour\n if not isinstance(df.index.freq, pdoffset.Day):\n raise FreqException(\"df doit \u00eatre en jour.\")\n\n res = {\"Seuil de RI en moyenne J: 50u\": depassement(df, valeur=50),\n \"Seuil d'Alerte en moyenne J: 80u\": depassement(df, valeur=80),\n \"Valeur limite pour la sant\u00e9 humaine 35J/A: 50u\": depassement(df, valeur=50),\n \"Valeur limite pour la sant\u00e9 humaine en moyenne A: 40u\": depassement(df.resample('A', how='mean'),\n valeur=40),\n \"Objectif de qualit\u00e9 en moyenne A: 30u\": depassement(df.resample('A', how='mean'), valeur=30),\n }\n\n return polluant, res"}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef so2(df):\n\n polluant = 'SO2'\n\n # Le DataFrame doit \u00eatre en heure\n if not isinstance(df.index.freq, pdoffset.Hour):\n raise FreqException(\"df doit \u00eatre en heure.\")\n\n res = {\"Seuil de RI en moyenne H: 300u\": depassement(df, valeur=300),\n \"Seuil d'Alerte sur 3H cons\u00e9cutives: 500u\": depassement(df, valeur=500),\n \"Valeur limite pour la sant\u00e9 humaine 24H/A: 350u\": depassement(df, valeur=350),\n \"Valeur limite pour la sant\u00e9 humaine 3J/A: 125u\": depassement(df.resample('D', how='mean'), valeur=125),\n \"Objectif de qualit\u00e9 en moyenne A: 50u\": depassement(df.resample('A', how='mean'), valeur=50),\n \"Protection de la v\u00e9g\u00e9tation en moyenne A: 20u\": depassement(df.resample('A', how='mean'), valeur=20),\n \"Protection de la v\u00e9g\u00e9tation du 01/10 au 31/03: 20u\": depassement(\n df[(df.index.month <= 3) | (df.index.month >= 10)], valeur=20),\n }\n\n return polluant, res", "response": "A helper function for calculating the non - defaul sont donn\u00e9s in a single sont donn\u00e9s."}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef c6h6(df):\n\n polluant = 'C6H6'\n\n # Le DataFrame doit \u00eatre en heure\n if not isinstance(df.index.freq, pdoffset.Hour):\n raise FreqException(\"df doit \u00eatre en heure.\")\n\n res = {\"Objectif de qualit\u00e9 en moyenne A: 2u\": depassement(df.resample('A', how='mean'), valeur=2),\n \"Valeur limite pour la sant\u00e9 humaine en moyenne A: 5u\": depassement(df.resample('A', how='mean'), valeur=5),\n }\n\n return polluant, res", "response": "C6H6 - > C6H6"}
{"SOURCE": "codesearchnet", "instruction": "How would you code a function in Python 3 to\nprint out synthes de la fonction renvoyant les valeurs de la fonction de calcul\u00e9es.", "response": "def print_synthese(fct, df):\n \"\"\"\n Pr\u00e9sente une synth\u00e8se des calculs r\u00e9glementaires en fournissant les valeurs\n calcul\u00e9es suivant les r\u00e9glementations d\u00e9finies dans chaque fonction de calcul\n et un tableau de nombre de d\u00e9passement.\n\n Param\u00e8tres:\n fct: fonction renvoyant les \u00e9l\u00e9ments calcul\u00e9es\n df: DataFrame de valeurs d'entr\u00e9e \u00e0 fournir \u00e0 la fonction\n\n Retourne:\n Imprime sur l'\u00e9cran les valeurs synth\u00e9tis\u00e9es\n\n \"\"\"\n\n res_count = dict()\n\n polluant, res = fct(df)\n print(\"\\nPour le polluant: %s\" % polluant)\n\n print(\"\\nValeurs mesur\u00e9es suivant crit\u00e8res:\")\n for k, v in res.items():\n comp = compresse(v)\n if not comp.empty:\n comp.index.name = k\n print(comp.to_string(na_rep='', float_format=lambda x: \"%.0f\" % x))\n else:\n print(\"\\n%s: aucune valeur en d\u00e9passement\" % k)\n res_count[k] = v.count()\n\n res_count = pd.DataFrame(res_count).T\n print(\"Nombre de d\u00e9passements des crit\u00e8res:\\n\")\n print(res_count)"}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef html_synthese(fct, df):\n\n html = str()\n res_count = dict()\n buf = StringIO()\n polluant, res = fct(df)\n html += '
Pour le polluant: {}
\")\n comp = compresse(v)\n if not comp.empty:\n comp.index.name = k\n comp.to_html(buf=buf,\n sparsify=True,\n na_rep=\"\")\n else:\n buf.write(\n '
| {} | Aucun d\u00e9passement |
|---|
\"\n html += res_count.to_html(sparsify=True)\n html += \"
\"\n\n html += buf.getvalue()\n\n return html", "response": "A helper function to format html synthese un synthant de un synthant."} {"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function that can\nshow the max value of the max value of the last date in a DataFrame.", "response": "def show_max(df):\n \"\"\"Pour chaque serie (colonne) d'un DataFrame, va rechercher la (les) valeur(s)\n et la (les) date(s) du (des) max.\n\n Param\u00e8tres:\n df: DataFrame de valeurs \u00e0 calculer\n\n Retourne:\n Un DataFrame montrant pour chaque serie (colonne), les valeurs maxs aux dates\n d'apparition.\n \"\"\"\n df = df.astype(pd.np.float)\n res = list()\n for c in df.columns:\n serie = df[c]\n res.append(serie.where(cond=serie == serie.max(), other=pd.np.nan).dropna())\n return pd.DataFrame(res).T"} {"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef taux_de_representativite(df):\n return (df.count().astype(pd.np.float) / df.shape[0] * 100).round(1)", "response": "Calculate le taux de representativite"} {"SOURCE": "codesearchnet", "instruction": "Can you implement a function in Python 3 that\nvalidates all the entries in the environment cache.", "response": "def validate(self):\n '''Validate all the entries in the environment cache.'''\n\n for env in list(self):\n if not env.exists:\n self.remove(env)"} {"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef load(self):\n '''Load the environment cache from disk.'''\n\n if not os.path.exists(self.path):\n return\n\n with open(self.path, 'r') as f:\n env_data = yaml.load(f.read())\n\n if env_data:\n for env in env_data:\n self.add(VirtualEnvironment(env['root']))", "response": "Load the environment cache from disk."} {"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef save(self):\n '''Save the environment cache to disk.'''\n\n env_data = [dict(name=env.name, root=env.path) for env in self]\n encode = yaml.safe_dump(env_data, default_flow_style=False)\n\n with open(self.path, 'w') as f:\n f.write(encode)", "response": "Save the environment cache to disk."} {"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef prompt(text, default=None, hide_input=False,\n confirmation_prompt=False, type=None,\n value_proc=None, prompt_suffix=': ',\n show_default=True, err=False):\n \"\"\"Prompts a user for input. This is a convenience function that can\n be used to prompt a user for input later.\n\n If the user aborts the input by sending a interrupt signal, this\n function will catch it and raise a :exc:`Abort` exception.\n\n .. versionadded:: 6.0\n Added unicode support for cmd.exe on Windows.\n\n .. versionadded:: 4.0\n Added the `err` parameter.\n\n :param text: the text to show for the prompt.\n :param default: the default value to use if no input happens. If this\n is not given it will prompt until it's aborted.\n :param hide_input: if this is set to true then the input value will\n be hidden.\n :param confirmation_prompt: asks for confirmation for the value.\n :param type: the type to use to check the value against.\n :param value_proc: if this parameter is provided it's a function that\n is invoked instead of the type conversion to\n convert a value.\n :param prompt_suffix: a suffix that should be added to the prompt.\n :param show_default: shows or hides the default value in the prompt.\n :param err: if set to true the file defaults to ``stderr`` instead of\n ``stdout``, the same as with echo.\n \"\"\"\n result = None\n\n def prompt_func(text):\n f = hide_input and hidden_prompt_func or visible_prompt_func\n try:\n # Write the prompt separately so that we get nice\n # coloring through colorama on Windows\n echo(text, nl=False, err=err)\n return f('')\n except (KeyboardInterrupt, EOFError):\n # getpass doesn't print a newline if the user aborts input with ^C.\n # Allegedly this behavior is inherited from getpass(3).\n # A doc bug has been filed at https://bugs.python.org/issue24711\n if hide_input:\n echo(None, err=err)\n raise Abort()\n\n if value_proc is None:\n value_proc = convert_type(type, default)\n\n prompt = _build_prompt(text, prompt_suffix, show_default, default)\n\n while 1:\n while 1:\n value = prompt_func(prompt)\n if value:\n break\n # If a default is set and used, then the confirmation\n # prompt is always skipped because that's the only thing\n # that really makes sense.\n elif default is not None:\n return default\n try:\n result = value_proc(value)\n except UsageError as e:\n echo('Error: %s' % e.message, err=err)\n continue\n if not confirmation_prompt:\n return result\n while 1:\n value2 = prompt_func('Repeat for confirmation: ')\n if value2:\n break\n if value == value2:\n return result\n echo('Error: the two entered values do not match', err=err)", "response": "Prompts a user for input."} {"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef _remote_setup_engine(engine_id, nengines):\n if distob.engine is None:\n distob.engine = distob.ObjectEngine(engine_id, nengines)\n # TODO these imports should be unnecessary with improved deserialization\n import numpy as np\n from scipy import stats\n # TODO Using @ipyparallel.interactive still did not import to __main__\n # so will do it this way for now.\n import __main__\n __main__.__dict__['np'] = np\n __main__.__dict__['stats'] = stats", "response": "Create an objectEngine instance and set up the objectengine module."} {"SOURCE": "codesearchnet", "instruction": "Can you implement a function in Python 3 that\nprepares all iPython engines for distributed object processing.", "response": "def setup_engines(client=None):\n \"\"\"Prepare all iPython engines for distributed object processing.\n\n Args:\n client (ipyparallel.Client, optional): If None, will create a client\n using the default ipyparallel profile.\n \"\"\"\n if not client:\n try:\n client = ipyparallel.Client()\n except:\n raise DistobClusterError(\n u\"\"\"Could not connect to an ipyparallel cluster. Make\n sure a cluster is started (e.g. to use the CPUs of a\n single computer, can type 'ipcluster start')\"\"\")\n eids = client.ids\n if not eids:\n raise DistobClusterError(\n u'No ipyparallel compute engines are available')\n nengines = len(eids)\n dv = client[eids]\n dv.use_dill()\n with dv.sync_imports(quiet=True):\n import distob\n # create global ObjectEngine distob.engine on each engine\n ars = []\n for i in eids:\n dv.targets = i\n ars.append(dv.apply_async(_remote_setup_engine, i, nengines))\n dv.wait(ars)\n for ar in ars:\n if not ar.successful():\n raise ar.r\n # create global ObjectHub distob.engine on the client host\n if distob.engine is None:\n distob.engine = ObjectHub(-1, client)"} {"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef _process_args(args, kwargs, prefer_local=True, recurse=True):\n this_engine = distob.engine.eid\n local_args = []\n remote_args = []\n execloc = this_engine # the chosen engine id for execution of the call\n for a in args:\n id = None\n if isinstance(a, Remote):\n id = a._ref.id\n elif isinstance(a, Ref):\n id = a.id\n elif isinstance(a, Id):\n id = a\n if id is not None:\n if id.engine is this_engine:\n local_args.append(distob.engine[id])\n remote_args.append(distob.engine[id])\n else:\n if (prefer_local and isinstance(a, Remote) and \n a._obcache_current):\n local_args.append(a._obcache)\n remote_args.append(id)\n else:\n # will choose remote execution\n if execloc is not this_engine and id.engine is not execloc:\n raise DistobValueError(\n 'two remote arguments are from different engines')\n else:\n execloc = id.engine\n local_args.append(None)\n remote_args.append(id)\n elif (isinstance(a, collections.Sequence) and\n not isinstance(a, string_types) and recurse):\n eid, ls, _ = _process_args(a, {}, prefer_local, recurse=False)\n if eid is not this_engine:\n if execloc is not this_engine and eid is not execloc:\n raise DistobValueError(\n 'two remote arguments are from different engines')\n execloc = eid\n local_args.append(ls)\n remote_args.append(ls)\n else:\n # argument is an ordinary object\n local_args.append(a)\n remote_args.append(a)\n local_kwargs = dict()\n remote_kwargs = dict()\n for k, a in kwargs.items():\n id = None\n if isinstance(a, Remote):\n id = a._ref.id\n elif isinstance(a, Ref):\n id = a.id\n elif isinstance(a, Id):\n id = a\n if id is not None:\n if id.engine is this_engine:\n local_kwargs[k] = distob.engine[id]\n remote_kwargs[k] = distob.engine[id]\n else:\n if (prefer_local and isinstance(a, Remote) and\n a._obcache_current):\n local_kwargs[k] = a._obcache\n remote_kwargs[k] = id\n else:\n # will choose remote execution\n if execloc is not this_engine and id.engine is not execloc:\n raise DistobValueError(\n 'two remote arguments are from different engines')\n else:\n execloc = id.engine\n local_kwargs[k] = None\n remote_kwargs[k] = id\n elif (isinstance(a, collections.Sequence) and\n not isinstance(a, string_types) and recurse):\n eid, ls, _ = _process_args(a, {}, prefer_local, recurse=False)\n if eid is not this_engine:\n if execloc is not this_engine and eid is not execloc:\n raise DistobValueError(\n 'two remote arguments are from different engines')\n execloc = eid\n local_kwargs[k] = ls\n remote_kwargs[k] = ls\n else:\n # argument is an ordinary object \n local_kwargs[k] = a\n remote_kwargs[k] = a\n if execloc is this_engine:\n return execloc, tuple(local_args), local_kwargs\n else:\n return execloc, tuple(remote_args), remote_kwargs", "response": "Process the arguments and kwargs."} {"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef call(f, *args, **kwargs):\n this_engine = distob.engine.eid\n prefer_local = kwargs.pop('prefer_local', True)\n block = kwargs.pop('block', True)\n execloc, args, kwargs = _process_args(args, kwargs, prefer_local)\n if execloc is this_engine:\n r = f(*args, **kwargs)\n else:\n if False and prefer_local:\n # result cache disabled until issue mattja/distob#1 is fixed\n try:\n kwtuple = tuple((k, kwargs[k]) for k in sorted(kwargs.keys()))\n key = (f, args, kwtuple)\n r = _call_cache[key]\n except TypeError as te:\n if te.args[0][:10] == 'unhashable':\n #print(\"unhashable. won't be able to cache\")\n r = _uncached_call(execloc, f, *args, **kwargs)\n else:\n raise\n except KeyError:\n r = _uncached_call(execloc, f, *args, **kwargs)\n if block:\n _call_cache[key] = r.r\n else:\n r = _uncached_call(execloc, f, *args, **kwargs)\n if block:\n return convert_result(r)\n else:\n return r", "response": "Execute a function on the arguments locally or remotely as appropriate."} {"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef convert_result(r):\n if (isinstance(r, collections.Sequence) and\n not isinstance(r, string_types)):\n rs = []\n for subresult in r:\n rs.append(convert_result(subresult))\n return rs\n if isinstance(r, ipyparallel.AsyncResult):\n r = r.r\n if isinstance(r, Ref):\n RemoteClass = distob.engine.proxy_types[r.type]\n r = RemoteClass(r)\n return r", "response": "Waits for and converts any AsyncResults."} {"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef _remote_methodcall(id, method_name, *args, **kwargs):\n obj = distob.engine[id]\n nargs = []\n for a in args:\n if isinstance(a, Id):\n nargs.append(distob.engine[a])\n elif (isinstance(a, collections.Sequence) and\n not isinstance(a, string_types)):\n nargs.append(\n [distob.engine[b] if isinstance(b, Id) else b for b in a])\n else: nargs.append(a)\n for k, a in kwargs.items():\n if isinstance(a, Id):\n kwargs[k] = distob.engine[a]\n elif (isinstance(a, collections.Sequence) and\n not isinstance(a, string_types)):\n kwargs[k] = [\n distob.engine[b] if isinstance(b, Id) else b for b in a]\n result = getattr(obj, method_name)(*nargs, **kwargs)\n if (isinstance(result, collections.Sequence) and\n not isinstance(result, string_types)):\n # We will return any sub-sequences by value, not recurse deeper\n results = []\n for subresult in result:\n if type(subresult) in distob.engine.proxy_types: \n results.append(Ref(subresult))\n else:\n results.append(subresult)\n return results\n elif type(result) in distob.engine.proxy_types:\n return Ref(result)\n else:\n return result", "response": "Internal method to call the remote method on the object with the given id."} {"SOURCE": "codesearchnet", "instruction": "Implement a function in Python 3 to\ncall a method of obj locally or remotely as appropriate.", "response": "def methodcall(obj, method_name, *args, **kwargs):\n \"\"\"Call a method of `obj`, either locally or remotely as appropriate.\n obj may be an ordinary object, or a Remote object (or Ref or object Id)\n If there are multiple remote arguments, they must be on the same engine.\n \n kwargs:\n prefer_local (bool, optional): Whether to return cached local results if\n available, in preference to returning Remote objects. Default is True.\n block (bool, optional): Whether remote calls should be synchronous.\n If False, returned results may be AsyncResults and should be converted\n by the caller using convert_result() before use. Default is True.\n \"\"\"\n this_engine = distob.engine.eid\n args = [obj] + list(args)\n prefer_local = kwargs.pop('prefer_local', None)\n if prefer_local is None:\n if isinstance(obj, Remote):\n prefer_local = obj.prefer_local\n else:\n prefer_local = True\n block = kwargs.pop('block', True)\n execloc, args, kwargs = _process_args(args, kwargs, prefer_local)\n if execloc is this_engine:\n r = getattr(args[0], method_name)(*args[1:], **kwargs)\n else:\n if False and prefer_local:\n # result cache disabled until issue mattja/distob#1 is fixed\n try:\n kwtuple = tuple((k, kwargs[k]) for k in sorted(kwargs.keys()))\n key = (args[0], method_name, args, kwtuple)\n r = _call_cache[key]\n except TypeError as te:\n if te.args[0][:10] == 'unhashable':\n #print(\"unhashable. won't be able to cache\")\n r = _uncached_methodcall(execloc, args[0], method_name,\n *args[1:], **kwargs)\n else:\n raise\n except KeyError:\n r = _uncached_methodcall(execloc, args[0], method_name,\n *args[1:], **kwargs)\n if block:\n _call_cache[key] = r.r\n else:\n r = _uncached_methodcall(execloc, args[0], method_name,\n *args[1:], **kwargs)\n if block:\n return convert_result(r)\n else:\n return r"} {"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script to\nscan an object and return a tuple of method and attribute info.", "response": "def _scan_instance(obj, include_underscore, exclude):\n \"\"\"(Executed on remote or local engine) Examines an object and returns info\n about any instance-specific methods or attributes.\n (For example, any attributes that were set by __init__() )\n\n By default, methods or attributes starting with an underscore are ignored.\n\n Args:\n obj (object): the object to scan. must be on this local engine.\n include_underscore (bool or sequence of str): Should methods or\n attributes that start with an underscore be proxied anyway? If a\n sequence of names is provided then methods or attributes starting with\n an underscore will only be proxied if their names are in the sequence.\n exclude (sequence of str): names of any methods or attributes that should\n not be reported.\n \"\"\"\n from sys import getsizeof\n always_exclude = ('__new__', '__init__', '__getattribute__', '__class__',\n '__reduce__', '__reduce_ex__')\n method_info = []\n attributes_info = []\n if hasattr(obj, '__dict__'):\n for name in obj.__dict__:\n if (name not in exclude and \n name not in always_exclude and\n (name[0] != '_' or \n include_underscore is True or\n name in include_underscore)):\n f = obj.__dict__[name]\n if hasattr(f, '__doc__'):\n doc = f.__doc__\n else:\n doc = None\n if callable(f) and not isinstance(f, type):\n method_info.append((name, doc))\n else:\n attributes_info.append((name, doc))\n return (method_info, attributes_info, getsizeof(obj))"} {"SOURCE": "codesearchnet", "instruction": "Can you create a Python 3 function that\nclasses decorator. Modifies `Remote` subclasses to add proxy methods and attributes that mimic those defined in class `base`. Example: @proxy_methods(Tree) class RemoteTree(Remote, Tree) The decorator registers the new proxy class and specifies which methods and attributes of class `base` should be proxied via a remote call to a real object, and which methods/attributes should not be proxied but instead called directly on the instance of the proxy class. By default all methods and attributes of the class `base` will be proxied except those starting with an underscore. The MRO of the decorated class is respected: Any methods and attributes defined in the decorated class (or in other bases of the decorated class that do not come after `base` in its MRO) will override those added by this decorator, so that `base` is treated like a base class. Args: base (type): The class whose instances should be remotely controlled. include_underscore (bool or sequence of str): Should methods or attributes that start with an underscore be proxied anyway? If a sequence of names is provided then methods or attributes starting with an underscore will only be proxied if their names are in the sequence. exclude (sequence of str): Names of any methods or attributes that should not be proxied. supers (bool): Proxy methods and attributes defined in superclasses of ``base``, in addition to those defined directly in class ``base``", "response": "def proxy_methods(base, include_underscore=None, exclude=None, supers=True):\n \"\"\"class decorator. Modifies `Remote` subclasses to add proxy methods and\n attributes that mimic those defined in class `base`.\n\n Example:\n\n @proxy_methods(Tree)\n class RemoteTree(Remote, Tree)\n\n The decorator registers the new proxy class and specifies which methods\n and attributes of class `base` should be proxied via a remote call to\n a real object, and which methods/attributes should not be proxied but\n instead called directly on the instance of the proxy class.\n\n By default all methods and attributes of the class `base` will be\n proxied except those starting with an underscore.\n\n The MRO of the decorated class is respected:\n Any methods and attributes defined in the decorated class\n (or in other bases of the decorated class that do not come after `base`\n in its MRO) will override those added by this decorator,\n so that `base` is treated like a base class.\n\n Args:\n base (type): The class whose instances should be remotely controlled.\n include_underscore (bool or sequence of str): Should methods or\n attributes that start with an underscore be proxied anyway? If a\n sequence of names is provided then methods or attributes starting with\n an underscore will only be proxied if their names are in the sequence.\n exclude (sequence of str): Names of any methods or attributes that \n should not be proxied.\n supers (bool): Proxy methods and attributes defined in superclasses \n of ``base``, in addition to those defined directly in class ``base``\n \"\"\"\n always_exclude = ('__new__', '__init__', '__getattribute__', '__class__',\n '__reduce__', '__reduce_ex__')\n if isinstance(include_underscore, str):\n include_underscore = (include_underscore,)\n if isinstance(exclude, str):\n exclude = (exclude,)\n if not include_underscore:\n include_underscore = ()\n if not exclude:\n exclude = ()\n def rebuild_class(cls):\n # Identify any bases of cls that do not come after `base` in the list:\n bases_other = list(cls.__bases__)\n if bases_other[-1] is object:\n bases_other.pop()\n if base in bases_other:\n bases_other = bases_other[:bases_other.index(base)]\n if not issubclass(cls.__bases__[0], Remote):\n raise DistobTypeError('First base class must be subclass of Remote')\n if not issubclass(base, object):\n raise DistobTypeError('Only new-style classes currently supported')\n dct = cls.__dict__.copy()\n if cls.__doc__ is None or '\\n' not in cls.__doc__:\n base_doc = base.__doc__\n if base_doc is None:\n base_doc = ''\n dct['__doc__'] = \"\"\"Local object representing a remote %s\n It can be used just like a %s object, but behind the scenes \n all requests are passed to a real %s object on a remote host.\n\n \"\"\" % ((base.__name__,)*3) + base_doc\n newcls = type(cls.__name__, cls.__bases__, dct)\n newcls._include_underscore = include_underscore\n newcls._exclude = exclude\n if supers:\n proxied_classes = base.__mro__[:-1]\n else:\n proxied_classes = (base,)\n for c in proxied_classes:\n for name in c.__dict__:\n #respect MRO: proxy an attribute only if it is not overridden\n if (name not in newcls.__dict__ and\n all(name not in b.__dict__ \n for c in bases_other for b in c.mro()[:-1]) and\n name not in newcls._exclude and\n name not in always_exclude and\n (name[0] != '_' or \n newcls._include_underscore is True or\n name in newcls._include_underscore)):\n f = c.__dict__[name]\n if hasattr(f, '__doc__'):\n doc = f.__doc__\n else:\n doc = None\n if callable(f) and not isinstance(f, type):\n setattr(newcls, name, _make_proxy_method(name, doc))\n else:\n setattr(newcls, name, _make_proxy_property(name, doc))\n newcls.__module__ = '__main__' # cause dill to pickle it whole\n import __main__\n __main__.__dict__[newcls.__name__] = newcls # for dill..\n ObjectHub.register_proxy_type(base, newcls)\n return newcls\n return rebuild_class"} {"SOURCE": "codesearchnet", "instruction": "Can you implement a function in Python 3 that\ndistributes an object or list to remote engines. Returns an async result or lists of nested objects where each of which is a Ref", "response": "def _async_scatter(obj, destination=None):\n \"\"\"Distribute an obj or list to remote engines. \n Return an async result or (possibly nested) lists of async results, \n each of which is a Ref\n \"\"\"\n #TODO Instead of special cases for strings and Remote, should have a\n # list of types that should not be proxied, inc. strings and Remote.\n if (isinstance(obj, Remote) or \n isinstance(obj, numbers.Number) or \n obj is None):\n return obj\n if (isinstance(obj, collections.Sequence) and \n not isinstance(obj, string_types)):\n ars = []\n if destination is not None:\n assert(len(destination) == len(obj))\n for i in range(len(obj)):\n ars.append(_async_scatter(obj[i], destination[i]))\n else:\n for i in range(len(obj)):\n ars.append(_async_scatter(obj[i], destination=None))\n return ars\n else:\n if distob.engine is None:\n setup_engines()\n client = distob.engine._client\n dv = distob.engine._dv\n def remote_put(obj):\n return Ref(obj)\n if destination is not None:\n assert(isinstance(destination, numbers.Integral))\n dv.targets = destination\n else:\n dv.targets = _async_scatter.next_engine\n _async_scatter.next_engine = (\n _async_scatter.next_engine + 1) % len(client)\n ar_ref = dv.apply_async(remote_put, obj)\n dv.targets = client.ids\n return ar_ref"} {"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef _ars_to_proxies(ars):\n if (isinstance(ars, Remote) or\n isinstance(ars, numbers.Number) or\n ars is None):\n return ars\n elif isinstance(ars, collections.Sequence):\n res = []\n for i in range(len(ars)):\n res.append(_ars_to_proxies(ars[i]))\n return res\n elif isinstance(ars, ipyparallel.AsyncResult):\n ref = ars.r\n ObClass = ref.type\n if ObClass in distob.engine.proxy_types:\n RemoteClass = distob.engine.proxy_types[ObClass]\n else:\n RemoteClass = type(\n 'Remote' + ObClass.__name__, (Remote, ObClass), dict())\n RemoteClass = proxy_methods(ObClass)(RemoteClass)\n proxy_obj = RemoteClass(ref)\n return proxy_obj\n else:\n raise DistobTypeError('Unpacking ars: unexpected type %s' % type(ars))", "response": "wait for AsyncResults and return Remote objects"} {"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef _scatter_ndarray(ar, axis=-1, destination=None, blocksize=None):\n from .arrays import DistArray, RemoteArray\n shape = ar.shape\n ndim = len(shape)\n if axis is None:\n return _directed_scatter([ar], destination=[destination],\n blocksize=blocksize)[0]\n if axis < -ndim or axis > ndim - 1:\n raise DistobValueError('axis out of range')\n if axis < 0:\n axis = ndim + axis\n n = shape[axis]\n if n == 1:\n return _directed_scatter([ar], destination=[destination])[0]\n if isinstance(destination, collections.Sequence):\n ne = len(destination) # number of engines to scatter array to\n else:\n if distob.engine is None:\n setup_engines()\n ne = distob.engine.nengines # by default scatter across all engines\n if blocksize is None:\n blocksize = ((n - 1) // ne) + 1\n if blocksize > n:\n blocksize = n\n if isinstance(ar, DistArray):\n if axis == ar._distaxis:\n return ar\n else:\n raise DistobError('Currently can only scatter one axis of array')\n # Currently, if requested to scatter an array that is already Remote and\n # large, first get whole array locally, then scatter. Not really optimal.\n if isinstance(ar, RemoteArray) and n > blocksize:\n ar = ar._ob\n s = slice(None)\n subarrays = []\n low = 0\n for i in range(0, n // blocksize):\n high = low + blocksize\n index = (s,)*axis + (slice(low, high),) + (s,)*(ndim - axis - 1)\n subarrays.append(ar[index])\n low += blocksize\n if n % blocksize != 0:\n high = low + (n % blocksize)\n index = (s,)*axis + (slice(low, high),) + (s,)*(ndim - axis - 1)\n subarrays.append(ar[index])\n subarrays = _directed_scatter(subarrays, destination=destination)\n return DistArray(subarrays, axis)", "response": "Turn a numpy array into a DistArray or RemoteArray with optional destination and blocksize."} {"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef scatter(obj, axis=-1, blocksize=None):\n if hasattr(obj, '__distob_scatter__'):\n return obj.__distob_scatter__(axis, None, blocksize)\n if distob._have_numpy and (isinstance(obj, np.ndarray) or\n hasattr(type(obj), '__array_interface__')):\n return _scatter_ndarray(obj, axis, blocksize)\n elif isinstance(obj, Remote):\n return obj\n ars = _async_scatter(obj)\n proxy_obj = _ars_to_proxies(ars)\n return proxy_obj", "response": "Distribute a python object or list of objects along a given axis."} {"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef gather(obj):\n if hasattr(obj, '__distob_gather__'):\n return obj.__distob_gather__()\n elif (isinstance(obj, collections.Sequence) and \n not isinstance(obj, string_types)):\n return [gather(subobj) for subobj in obj]\n else:\n return obj", "response": "Retrieve objects that have been distributed making them local again"} {"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef vectorize(f):\n def vf(obj, *args, **kwargs):\n # user classes can customize how to vectorize a function:\n if hasattr(obj, '__distob_vectorize__'):\n return obj.__distob_vectorize__(f)(obj, *args, **kwargs)\n if isinstance(obj, Remote):\n return call(f, obj, *args, **kwargs)\n elif distob._have_numpy and (isinstance(obj, np.ndarray) or\n hasattr(type(obj), '__array_interface__')):\n distarray = scatter(obj, axis=-1)\n return vf(distarray, *args, **kwargs)\n elif isinstance(obj, collections.Sequence):\n inputs = scatter(obj)\n dv = distob.engine._client[:]\n kwargs = kwargs.copy()\n kwargs['block'] = False\n results = []\n for obj in inputs:\n results.append(call(f, obj, *args, **kwargs))\n for i in range(len(results)):\n results[i] = convert_result(results[i])\n return results\n if hasattr(f, '__name__'):\n vf.__name__ = 'v' + f.__name__\n f_str = f.__name__ + '()'\n else:\n f_str = 'callable'\n doc = u\"\"\"Apply %s in parallel to a list or array\\n\n Args:\n obj (Sequence of objects or an array)\n other args are the same as for %s\n \"\"\" % (f_str, f_str)\n if hasattr(f, '__doc__') and f.__doc__ is not None:\n doc = doc.rstrip() + (' detailed below:\\n----------\\n' + f.__doc__)\n vf.__doc__ = doc\n return vf", "response": "Upgrade normal function f to act in parallel on distibuted lists or arrays of N + 1 dimensions."} {"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef apply(f, obj, *args, **kwargs):\n return vectorize(f)(obj, *args, **kwargs)", "response": "Apply a function in parallel to each element of the input"} {"SOURCE": "codesearchnet", "instruction": "How would you implement a function in Python 3 that\ncalls a method on each element of a sequence in parallel.", "response": "def call_all(sequence, method_name, *args, **kwargs):\n \"\"\"Call a method on each element of a sequence, in parallel.\n Returns:\n list of results\n \"\"\"\n kwargs = kwargs.copy()\n kwargs['block'] = False\n results = []\n for obj in sequence:\n results.append(methodcall(obj, method_name, *args, **kwargs))\n for i in range(len(results)):\n results[i] = convert_result(results[i])\n return results"} {"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef register_proxy_type(cls, real_type, proxy_type):\n if distob.engine is None:\n cls._initial_proxy_types[real_type] = proxy_type\n elif isinstance(distob.engine, ObjectHub):\n distob.engine._runtime_reg_proxy_type(real_type, proxy_type)\n else:\n # TODO: remove next line after issue #58 in dill is fixed.\n distob.engine._singleeng_reg_proxy_type(real_type, proxy_type)\n pass", "response": "Configure engines so that remote methods returning values of typereal_type will instead return by proxy as type proxy_type"} {"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef _fetch(self):\n if not self.is_local and not self._obcache_current:\n #print('fetching data from %s' % self._ref.id)\n def _remote_fetch(id):\n return distob.engine[id]\n self._obcache = self._dv.apply_sync(_remote_fetch, self._id)\n self._obcache_current = True\n self.__engine_affinity__ = (distob.engine.eid, \n self.__engine_affinity__[1])", "response": "forces update of a local cached copy of the real object"} {"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef extract_json(fileobj, keywords, comment_tags, options):\n data=fileobj.read()\n json_extractor=JsonExtractor(data)\n strings_data=json_extractor.get_lines_data()\n\n for item in strings_data:\n messages = [item['content']]\n if item.get('funcname') == 'ngettext':\n messages.append(item['alt_content'])\n yield item['line_number'],item.get('funcname','gettext'),tuple(messages),[]", "response": "Extract a list of strings from a JSON file."} {"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef get_lines_data(self):\n\n encoding = 'utf-8'\n\n for token in tokenize(self.data.decode(encoding)):\n if token.type == 'operator':\n if token.value == '{':\n self.start_object()\n elif token.value ==':':\n self.with_separator(token)\n elif token.value == '}':\n self.end_object()\n elif token.value == ',':\n self.end_pair()\n\n\n elif token.type=='string':\n if self.state=='key':\n self.current_key=unquote_string(token.value)\n if self.current_key==JSON_GETTEXT_KEYWORD:\n self.gettext_mode=True\n\n #==value not actually used, but if only key was met (like in list) it still will be used. The important part, that key wont be parsed as value, not reversal\n if self.gettext_mode:\n if self.current_key==JSON_GETTEXT_KEY_CONTENT:\n self.token_to_add=token\n elif self.current_key==JSON_GETTEXT_KEY_ALT_CONTENT:\n self.token_params['alt_token']=token\n elif self.current_key==JSON_GETTEXT_KEY_FUNCNAME:\n self.token_params['funcname']=token.value\n else:\n self.token_to_add=token\n\n return self.results", "response": "Returns a list of line numbers for the current line number."} {"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef is_git_repo(path):\n '''Returns True if path is a git repository.'''\n\n if path.startswith('git@') or path.startswith('https://'):\n return True\n\n if os.path.exists(unipath(path, '.git')):\n return True\n\n return False", "response": "Returns True if path is a git repository."} {"SOURCE": "codesearchnet", "instruction": "Implement a function in Python 3 to\nreturn True if path is in the home directory of the environment.", "response": "def is_home_environment(path):\n '''Returns True if path is in CPENV_HOME'''\n\n home = unipath(os.environ.get('CPENV_HOME', '~/.cpenv'))\n path = unipath(path)\n\n return path.startswith(home)"} {"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef is_redirecting(path):\n '''Returns True if path contains a .cpenv file'''\n\n candidate = unipath(path, '.cpenv')\n return os.path.exists(candidate) and os.path.isfile(candidate)", "response": "Returns True if path contains a. cpenv file"} {"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef redirect_to_env_paths(path):\n '''Get environment path from redirect file'''\n\n with open(path, 'r') as f:\n redirected = f.read()\n\n return shlex.split(redirected)", "response": "Get environment paths from redirect file"} {"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef expandpath(path):\n '''Returns an absolute expanded path'''\n\n return os.path.abspath(os.path.expandvars(os.path.expanduser(path)))", "response": "Returns an absolute expanded path"} {"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function for\nliking os. path. join but also expands and normalizes path parts.", "response": "def unipath(*paths):\n '''Like os.path.join but also expands and normalizes path parts.'''\n\n return os.path.normpath(expandpath(os.path.join(*paths)))"} {"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef binpath(*paths):\n '''Like os.path.join but acts relative to this packages bin path.'''\n\n package_root = os.path.dirname(__file__)\n return os.path.normpath(os.path.join(package_root, 'bin', *paths))", "response": "Like os. path. join but acts relative to this packages bin path."} {"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef ensure_path_exists(path, *args):\n '''Like os.makedirs but keeps quiet if path already exists'''\n if os.path.exists(path):\n return\n\n os.makedirs(path, *args)", "response": "Like os. makedirs but keeps quiet if path already exists"} {"SOURCE": "codesearchnet", "instruction": "How would you implement a function in Python 3 that\nwalks down a directory tree. Same as os. walk but allows for a depth limit.", "response": "def walk_dn(start_dir, depth=10):\n '''\n Walk down a directory tree. Same as os.walk but allows for a depth limit\n via depth argument\n '''\n\n start_depth = len(os.path.split(start_dir))\n end_depth = start_depth + depth\n\n for root, subdirs, files in os.walk(start_dir):\n yield root, subdirs, files\n\n if len(os.path.split(root)) >= end_depth:\n break"} {"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function for\nwalking up a directory tree and yield a list of all the files and subdirs.", "response": "def walk_up(start_dir, depth=20):\n '''\n Walk up a directory tree\n '''\n root = start_dir\n\n for i in xrange(depth):\n contents = os.listdir(root)\n subdirs, files = [], []\n for f in contents:\n if os.path.isdir(os.path.join(root, f)):\n subdirs.append(f)\n else:\n files.append(f)\n\n yield root, subdirs, files\n\n parent = os.path.dirname(root)\n if parent and not parent == root:\n root = parent\n else:\n break"} {"SOURCE": "codesearchnet", "instruction": "How would you code a function in Python 3 to\nadd a sequence value to env dict d", "response": "def _join_seq(d, k, v):\n '''Add a sequence value to env dict'''\n\n if k not in d:\n d[k] = list(v)\n\n elif isinstance(d[k], list):\n for item in v:\n if item not in d[k]:\n d[k].insert(0, item)\n\n elif isinstance(d[k], string_types):\n v.append(d[k])\n d[k] = v"} {"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function that can\njoin a bunch of dicts", "response": "def join_dicts(*dicts):\n '''Join a bunch of dicts'''\n\n out_dict = {}\n\n for d in dicts:\n for k, v in d.iteritems():\n\n if not type(v) in JOINERS:\n raise KeyError('Invalid type in dict: {}'.format(type(v)))\n\n JOINERS[type(v)](out_dict, k, v)\n\n return out_dict"} {"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef env_to_dict(env, pathsep=os.pathsep):\n '''\n Convert a dict containing environment variables into a standard dict.\n Variables containing multiple values will be split into a list based on\n the argument passed to pathsep.\n\n :param env: Environment dict like os.environ.data\n :param pathsep: Path separator used to split variables\n '''\n\n out_dict = {}\n\n for k, v in env.iteritems():\n if pathsep in v:\n out_dict[k] = v.split(pathsep)\n else:\n out_dict[k] = v\n\n return out_dict", "response": "Convert a dict containing environment variables into a standard dict."} {"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function that can\nconvert a python dict to an environment dict containing valid environment variable values.", "response": "def dict_to_env(d, pathsep=os.pathsep):\n '''\n Convert a python dict to a dict containing valid environment variable\n values.\n\n :param d: Dict to convert to an env dict\n :param pathsep: Path separator used to join lists(default os.pathsep)\n '''\n\n out_env = {}\n\n for k, v in d.iteritems():\n if isinstance(v, list):\n out_env[k] = pathsep.join(v)\n elif isinstance(v, string_types):\n out_env[k] = v\n else:\n raise TypeError('{} not a valid env var type'.format(type(v)))\n\n return out_env"} {"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef expand_envvars(env):\n '''\n Expand all environment variables in an environment dict\n\n :param env: Environment dict\n '''\n\n out_env = {}\n\n for k, v in env.iteritems():\n out_env[k] = Template(v).safe_substitute(env)\n\n # Expand twice to make sure we expand everything we possibly can\n for k, v in out_env.items():\n out_env[k] = Template(v).safe_substitute(out_env)\n\n return out_env", "response": "Expand all environment variables in an environment dict"} {"SOURCE": "codesearchnet", "instruction": "Can you write a function in Python 3 where it\nreturns an unused random filepath.", "response": "def get_store_env_tmp():\n '''Returns an unused random filepath.'''\n\n tempdir = tempfile.gettempdir()\n temp_name = 'envstore{0:0>3d}'\n temp_path = unipath(tempdir, temp_name.format(random.getrandbits(9)))\n if not os.path.exists(temp_path):\n return temp_path\n else:\n return get_store_env_tmp()"} {"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef store_env(path=None):\n '''Encode current environment as yaml and store in path or a temporary\n file. Return the path to the stored environment.\n '''\n\n path = path or get_store_env_tmp()\n\n env_dict = yaml.safe_dump(os.environ.data, default_flow_style=False)\n\n with open(path, 'w') as f:\n f.write(env_dict)\n\n return path", "response": "Encode current environment as yaml and store in path or a temporary\n file. Return the path to the stored environment."} {"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef restore_env(env_dict):\n '''Set environment variables in the current python process from a dict\n containing envvars and values.'''\n\n if hasattr(sys, 'real_prefix'):\n sys.prefix = sys.real_prefix\n del(sys.real_prefix)\n\n replace_osenviron(expand_envvars(dict_to_env(env_dict)))", "response": "Set environment variables in the current python process from a dict\n containing envvars and values."} {"SOURCE": "codesearchnet", "instruction": "How would you code a function in Python 3 to\nrestore the current environment from an environment stored in a yaml yaml file.", "response": "def restore_env_from_file(env_file):\n '''Restore the current environment from an environment stored in a yaml\n yaml file.\n\n :param env_file: Path to environment yaml file.\n '''\n\n with open(env_file, 'r') as f:\n env_dict = yaml.load(f.read())\n\n restore_env(env_dict)"} {"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script to\nset environment variables in the current python process from a dict containing envvars and values.", "response": "def set_env(*env_dicts):\n '''Set environment variables in the current python process from a dict\n containing envvars and values.'''\n\n old_env_dict = env_to_dict(os.environ.data)\n new_env_dict = join_dicts(old_env_dict, *env_dicts)\n new_env = dict_to_env(new_env_dict)\n replace_osenviron(expand_envvars(new_env))"} {"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function that can\nrestore the current environment from an environment stored in a yaml file.", "response": "def set_env_from_file(env_file):\n '''Restore the current environment from an environment stored in a yaml\n yaml file.\n\n :param env_file: Path to environment yaml file.\n '''\n\n with open(env_file, 'r') as f:\n env_dict = yaml.load(f.read())\n\n if 'environment' in env_dict:\n env_dict = env_dict['environment']\n\n set_env(env_dict)"} {"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script to\nreturn the URL to the upstream data source for the given URI based on configuration", "response": "def upstream_url(self, uri):\n \"Returns the URL to the upstream data source for the given URI based on configuration\"\n return self.application.options.upstream + self.request.uri"} {"SOURCE": "codesearchnet", "instruction": "How would you code a function in Python 3 to\nreturn ( headers body ) from the cache or raise KeyError", "response": "def cache_get(self):\n \"Returns (headers, body) from the cache or raise KeyError\"\n key = self.cache_key()\n (headers, body, expires_ts) = self.application._cache[key]\n if expires_ts < time.now():\n # asset has expired, delete it\n del self.application._cache[key]\n raise KeyError(key)\n\n return (headers, body)"} {"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function to\nreturn request object for calling the upstream", "response": "def make_upstream_request(self):\n \"Return request object for calling the upstream\"\n url = self.upstream_url(self.request.uri)\n return tornado.httpclient.HTTPRequest(url,\n method=self.request.method,\n headers=self.request.headers,\n body=self.request.body if self.request.body else None)"} {"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script for\nreturning the time to live in seconds. 0 means no caching.", "response": "def ttl(self, response):\n \"\"\"Returns time to live in seconds. 0 means no caching.\n\n Criteria:\n - response code 200\n - read-only method (GET, HEAD, OPTIONS)\n Plus http headers:\n - cache-control: option1, option2, ...\n where options are:\n private | public\n no-cache\n no-store\n max-age: seconds\n s-maxage: seconds\n must-revalidate\n proxy-revalidate\n - expires: Thu, 01 Dec 1983 20:00:00 GMT\n - pragma: no-cache (=cache-control: no-cache)\n\n See http://www.mobify.com/blog/beginners-guide-to-http-cache-headers/\n\n TODO: tests\n\n \"\"\"\n if response.code != 200: return 0\n if not self.request.method in ['GET', 'HEAD', 'OPTIONS']: return 0\n\n try:\n pragma = self.request.headers['pragma']\n if pragma == 'no-cache':\n return 0\n except KeyError:\n pass\n\n try:\n cache_control = self.request.headers['cache-control']\n\n # no caching options\n for option in ['private', 'no-cache', 'no-store', 'must-revalidate', 'proxy-revalidate']:\n if cache_control.find(option): return 0\n\n # further parsing to get a ttl\n options = parse_cache_control(cache_control)\n try:\n return int(options['s-maxage'])\n except KeyError:\n pass\n try:\n return int(options['max-age'])\n except KeyError:\n pass\n\n if 's-maxage' in options:\n max_age = options['s-maxage']\n if max_age < ttl: ttl = max_age\n if 'max-age' in options:\n max_age = options['max-age']\n if max_age < ttl: ttl = max_age\n return ttl\n except KeyError:\n pass\n\n try:\n expires = self.request.headers['expires']\n return time.mktime(time.strptime(expires, '%a, %d %b %Y %H:%M:%S')) - time.time()\n except KeyError:\n pass"} {"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef hist2d(x, y, bins=10, labels=None, aspect=\"auto\", plot=True, fig=None, ax=None, interpolation='none', cbar=True, **kwargs):\n h_range = kwargs.pop('range', None)\n h_normed = kwargs.pop('normed', None)\n h_weights = kwargs.pop('weights', None)\n\n h, xe, ye = _np.histogram2d(x, y, bins=bins, range=h_range, normed=h_normed, weights=h_weights)\n extent = [xe[0], xe[-1], ye[0], ye[-1]]\n # fig = plt.figure()\n if plot:\n if ax is None:\n if fig is None:\n fig = _figure('hist2d')\n ax = fig.gca()\n ax.clear()\n\n img = ax.imshow(h.transpose(), extent=extent, interpolation=interpolation, aspect=aspect, **kwargs)\n if cbar:\n _colorbar(ax=ax, im=img)\n\n if labels is not None:\n _addlabel(labels[0], labels[1], labels[2])\n\n # _showfig(fig, aspect)\n return h, extent", "response": "Create a 2 - D histogram of data x y."} {"SOURCE": "codesearchnet", "instruction": "Can you implement a function in Python 3 that\ncalculates the frequency of the plasma density in units of mass.", "response": "def w_p(self):\n \"\"\"\n Plasma frequency :math:`\\\\omega_p` for given plasma density\n \"\"\"\n return _np.sqrt(self.n_p * _np.power(_spc.e, 2) / (_spc.m_e * _spc.epsilon_0))"} {"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef k_ion(self, E):\n return self.n_p * _np.power(_spc.e, 2) / (2*_sltr.GeV2joule(E) * _spc.epsilon_0)", "response": "Geometric focusing force due to ion column for given plasma density"} {"SOURCE": "codesearchnet", "instruction": "Can you write a function in Python 3 where it\nguarantees the existence of a basic MANIFEST. in.", "response": "def manifest():\n \"\"\"Guarantee the existence of a basic MANIFEST.in.\n\n manifest doc: http://docs.python.org/distutils/sourcedist.html#manifest\n\n `options.paved.dist.manifest.include`: set of files (or globs) to include with the `include` directive.\n\n `options.paved.dist.manifest.recursive_include`: set of files (or globs) to include with the `recursive-include` directive.\n\n `options.paved.dist.manifest.prune`: set of files (or globs) to exclude with the `prune` directive.\n\n `options.paved.dist.manifest.include_sphinx_docroot`: True -> sphinx docroot is added as `graft`\n\n `options.paved.dist.manifest.include_sphinx_docroot`: True -> sphinx builddir is added as `prune`\n \"\"\"\n prune = options.paved.dist.manifest.prune\n graft = set()\n\n\n if options.paved.dist.manifest.include_sphinx_docroot:\n docroot = options.get('docroot', 'docs')\n graft.update([docroot])\n\n if options.paved.dist.manifest.exclude_sphinx_builddir:\n builddir = docroot + '/' + options.get(\"builddir\", \".build\")\n prune.update([builddir])\n\n with open(options.paved.cwd / 'MANIFEST.in', 'w') as fo:\n for item in graft:\n fo.write('graft %s\\n' % item)\n for item in options.paved.dist.manifest.include:\n fo.write('include %s\\n' % item)\n for item in options.paved.dist.manifest.recursive_include:\n fo.write('recursive-include %s\\n' % item)\n for item in prune:\n fo.write('prune %s\\n' % item)"} {"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef create_threadpool_executed_func(original_func):\n def wrapped_func(*args, **kwargs):\n try:\n result = original_func(*args, **kwargs)\n return True, result\n except:\n return False, sys.exc_info()\n\n def new_func(*args, **kwargs):\n status, result = gevent.get_hub().threadpool.apply(wrapped_func, args, kwargs)\n if status:\n return result\n else:\n six.reraise(*result)\n new_func.__name__ = original_func.__name__\n new_func.__doc__ = \"(gevent-friendly)\" + (\" \" + original_func.__doc__ if original_func.__doc__ is not None else \"\")\n return new_func", "response": "Creates a function that defers function calls execute inside gevent s threadpool."} {"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef format_pathname(\n pathname,\n max_length):\n \"\"\"\n Format a pathname\n\n :param str pathname: Pathname to format\n :param int max_length: Maximum length of result pathname (> 3)\n :return: Formatted pathname\n :rtype: str\n :raises ValueError: If *max_length* is not larger than 3\n\n This function formats a pathname so it is not longer than *max_length*\n characters. The resulting pathname is returned. It does so by replacing\n characters at the start of the *pathname* with three dots, if necessary.\n The idea is that the end of the *pathname* is the most important part\n to be able to identify the file.\n \"\"\"\n if max_length <= 3:\n raise ValueError(\"max length must be larger than 3\")\n\n if len(pathname) > max_length:\n pathname = \"...{}\".format(pathname[-(max_length-3):])\n\n return pathname", "response": "Formats a pathname so that it is not longer than max_length characters."} {"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef format_time_point(\n time_point_string):\n\n \"\"\"\n :param str time_point_string: String representation of a time point\n to format\n :return: Formatted time point\n :rtype: str\n :raises ValueError: If *time_point_string* is not formatted by\n dateutil.parser.parse\n\n See :py:meth:`datetime.datetime.isoformat` function for supported formats.\n \"\"\"\n time_point = dateutil.parser.parse(time_point_string)\n\n if not is_aware(time_point):\n time_point = make_aware(time_point)\n\n time_point = local_time_point(time_point)\n\n return time_point.strftime(\"%Y-%m-%dT%H:%M:%S\")", "response": "Formats a time point in a cluster node s time series."} {"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef format_uuid(\n uuid,\n max_length=10):\n \"\"\"\n Format a UUID string\n\n :param str uuid: UUID to format\n :param int max_length: Maximum length of result string (> 3)\n :return: Formatted UUID\n :rtype: str\n :raises ValueError: If *max_length* is not larger than 3\n\n This function formats a UUID so it is not longer than *max_length*\n characters. The resulting string is returned. It does so by replacing\n characters at the end of the *uuid* with three dots, if necessary.\n The idea is that the start of the *uuid* is the most important part\n to be able to identify the related entity.\n\n The default *max_length* is 10, which will result in a string\n containing the first 7 characters of the *uuid* passed in. Most of\n the time, such a string is still unique within a collection of UUIDs.\n \"\"\"\n if max_length <= 3:\n raise ValueError(\"max length must be larger than 3\")\n\n if len(uuid) > max_length:\n uuid = \"{}...\".format(uuid[0:max_length-3])\n\n return uuid", "response": "Formats a UUID string for a given locale."} {"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function for\nfinding the reduced chi square difference of observe and expect with a given error and ddof degrees of freedom.", "response": "def chisquare(observe, expect, error, ddof, verbose=True):\n \"\"\"\n Finds the reduced chi square difference of *observe* and *expect* with a given *error* and *ddof* degrees of freedom.\n\n *verbose* flag determines if the reduced chi square is printed to the terminal. \n \"\"\"\n chisq = 0\n error = error.flatten()\n observe = observe.flatten()\n expect = expect.flatten()\n for i, el in enumerate(observe):\n chisq = chisq + _np.power((el - expect[i]) / error[i], 2)\n\n red_chisq = chisq / (len(observe) - ddof)\n if verbose:\n # print 'Chi-Squared is {}.'.format(chisq)\n print('Reduced Chi-Squared is {}.'.format(red_chisq))\n\n return red_chisq"} {"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function that can\nreturn the mantissa and exponent of a number x.", "response": "def frexp10(x):\n \"\"\"\n Finds the mantissa and exponent of a number :math:`x` such that :math:`x = m 10^e`.\n\n Parameters\n ----------\n\n x : float\n Number :math:`x` such that :math:`x = m 10^e`.\n\n Returns\n -------\n\n mantissa : float\n Number :math:`m` such that :math:`x = m 10^e`.\n exponent : float\n Number :math:`e` such that :math:`x = m 10^e`.\n \"\"\"\n expon = _np.int(_np.floor(_np.log10(_np.abs(x))))\n mant = x/_np.power(10, expon)\n return (mant, expon)"} {"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef get_upcoming_events_count(days=14, featured=False):\n from happenings.models import Event\n start_period = today - datetime.timedelta(days=2)\n end_period = today + datetime.timedelta(days=days)\n if featured:\n return Event.objects.filter(\n featured=True,\n start_date__gte=start_period,\n start_date__lte=end_period\n ).count()\n return Event.objects.filter(start_date__gte=start_period, start_date__lte=end_period).count()", "response": "Returns the number of upcoming events for a given number of days"} {"SOURCE": "codesearchnet", "instruction": "Can you implement a function in Python 3 that\ngets upcoming events for a given number of days.", "response": "def get_upcoming_events(num, days, featured=False):\n \"\"\"\n Get upcoming events.\n Allows slicing to a given number,\n picking the number of days to hold them after they've started\n and whether they should be featured or not.\n Usage:\n {% get_upcoming_events 5 14 featured as events %}\n Would return no more than 5 Featured events,\n holding them for 14 days past their start date.\n\n \"\"\"\n from happenings.models import Event\n start_date = today - datetime.timedelta(days=days)\n events = Event.objects.filter(start_date__gt=start_date).order_by('start_date')\n if featured:\n events = events.filter(featured=True)\n events = events[:num]\n return events"} {"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef get_events_by_date_range(days_out, days_hold, max_num=5, featured=False):\n from happenings.models import Event\n range_start = today - datetime.timedelta(days=days_hold)\n range_end = today + datetime.timedelta(days=days_out)\n\n events = Event.objects.filter(\n start_date__gte=range_start,\n start_date__lte=range_end\n ).order_by('start_date')\n if featured:\n events = events.filter(featured=True)\n events = events[:max_num]\n return events", "response": "Get upcoming events for a given number of days out"} {"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function to\nreturn a dict of next and previous on updates", "response": "def paginate_update(update):\n \"\"\"\n attempts to get next and previous on updates\n \"\"\"\n from happenings.models import Update\n time = update.pub_time\n event = update.event\n try:\n next = Update.objects.filter(\n event=event,\n pub_time__gt=time\n ).order_by('pub_time').only('title')[0]\n except:\n next = None\n try:\n previous = Update.objects.filter(\n event=event,\n pub_time__lt=time\n ).order_by('-pub_time').only('title')[0]\n except:\n previous = None\n return {'next': next, 'previous': previous, 'event': event}"} {"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef notify_client(\n notifier_uri,\n client_id,\n status_code,\n message=None):\n \"\"\"\n Notify the client of the result of handling a request\n\n The payload contains two elements:\n\n - client_id\n - result\n\n The *client_id* is the id of the client to notify. It is assumed\n that the notifier service is able to identify the client by this id\n and that it can pass the *result* to it.\n\n The *result* always contains a *status_code* element. In case the\n message passed in is not None, it will also contain a *message*\n element.\n\n In case the notifier service does not exist or returns an error,\n an error message will be logged to *stderr*.\n \"\"\"\n payload = {\n \"client_id\": client_id,\n \"result\": {\n \"response\": {\n \"status_code\": status_code\n }\n }\n }\n\n if message is not None:\n payload[\"result\"][\"response\"][\"message\"] = message\n\n response = requests.post(notifier_uri, json=payload)\n\n if response.status_code != 201:\n sys.stderr.write(\"failed to notify client: {}\\n\".format(payload))\n sys.stderr.flush()", "response": "Notify the client of the result of handling a request."} {"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef consume_message_with_notify(\n notifier_uri_getter):\n \"\"\"\n Decorator for methods handling requests from RabbitMQ\n\n This decorator builds on the :py:func:`consume_message` decorator. It extents\n it by logic for notifying a client of the result of handling the\n request.\n\n The *notifier_uri_getter* argument must be a callable which accepts\n *self* and returns the uri of the notifier service.\n \"\"\"\n\n def consume_message_with_notify_decorator(\n method):\n\n @consume_message\n def wrapper(\n self,\n data):\n\n notifier_uri = notifier_uri_getter(self)\n client_id = data[\"client_id\"]\n\n # Forward the call to the method and notify the client of the\n # result\n try:\n method(self, data)\n notify_client(notifier_uri, client_id, 200)\n except Exception as exception:\n notify_client(notifier_uri, client_id, 400, str(exception))\n raise\n\n return wrapper\n\n return consume_message_with_notify_decorator", "response": "This is a simple decorator for methods handling requests from RabbitMQ and notifies a client of the result of the message."} {"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef get(self, key):\n try:\n value = self._cache[key]\n self._order.push(key)\n self._hits += 1\n return value\n except KeyError, e:\n self._misses += 1\n raise", "response": "Get a key from the cache."} {"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef put(self, key, value):\n self._cache[key] = value\n self._order.push(key)\n self._size += 1", "response": "Add a new entry to the cache."} {"SOURCE": "codesearchnet", "instruction": "Can you write a function in Python 3 where it\ndeletes the entry with the given key.", "response": "def delete(self, key):\n \"\"\"\n >>> c = LRUCache()\n >>> c.put(1, 'one')\n >>> c.get(1)\n 'one'\n >>> c.delete(1)\n >>> c.get(1)\n Traceback (most recent call last):\n ...\n KeyError: 1\n >>> c.delete(1)\n Traceback (most recent call last):\n ...\n KeyError: 1\n \"\"\"\n del self._cache[key]\n self._order.delete(key)\n self._size -= 1"} {"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef put(self, key, value):\n mem = sys.getsizeof(value)\n if self._mem + mem > self._maxmem:\n self.delete(self.last())\n LRUCache.put(self, key, (value, mem))\n self._mem += mem", "response": "Put a key - value pair into the cache."} {"SOURCE": "codesearchnet", "instruction": "Implement a function in Python 3 to\ndelete an entry from the cache.", "response": "def delete(self, key):\n \"\"\"\n >>> c = MemSizeLRUCache()\n >>> c.put(1, 1)\n >>> c.mem()\n 24\n >>> c.delete(1)\n >>> c.mem()\n 0\n \"\"\"\n (_value, mem) = LRUCache.get(self, key)\n self._mem -= mem\n LRUCache.delete(self, key)"} {"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef put(self, key, value):\n # check if we're maxed out first\n if self.size() == self._maxsize:\n # need to kick something out...\n self.delete(self.last())\n LRUCache.put(self, key, value)", "response": "Put a key - value pair into the cache."} {"SOURCE": "codesearchnet", "instruction": "How would you code a function in Python 3 to\nretrieve the value of a setting whose name is indicated by name_hyphen.", "response": "def setting(self, name_hyphen):\n \"\"\"\n Retrieves the setting value whose name is indicated by name_hyphen.\n\n Values starting with $ are assumed to reference environment variables,\n and the value stored in environment variables is retrieved. It's an\n error if thes corresponding environment variable it not set.\n \"\"\"\n if name_hyphen in self._instance_settings:\n value = self._instance_settings[name_hyphen][1]\n else:\n msg = \"No setting named '%s'\" % name_hyphen\n raise UserFeedback(msg)\n\n if hasattr(value, 'startswith') and value.startswith(\"$\"):\n env_var = value.lstrip(\"$\")\n if env_var in os.environ:\n return os.getenv(env_var)\n else:\n msg = \"'%s' is not defined in your environment\" % env_var\n raise UserFeedback(msg)\n\n elif hasattr(value, 'startswith') and value.startswith(\"\\$\"):\n return value.replace(\"\\$\", \"$\")\n\n else:\n return value"} {"SOURCE": "codesearchnet", "instruction": "How would you implement a function in Python 3 that\nreturns a dict of all setting values.", "response": "def setting_values(self, skip=None):\n \"\"\"\n Returns dict of all setting values (removes the helpstrings).\n \"\"\"\n if not skip:\n skip = []\n\n return dict(\n (k, v[1])\n for k, v in six.iteritems(self._instance_settings)\n if not k in skip)"} {"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script to\nupdate the internal settings of the cashew instance.", "response": "def _update_settings(self, new_settings, enforce_helpstring=True):\n \"\"\"\n This method does the work of updating settings. Can be passed with\n enforce_helpstring = False which you may want if allowing end users to\n add arbitrary metadata via the settings system.\n\n Preferable to use update_settings (without leading _) in code to do the\n right thing and always have docstrings.\n \"\"\"\n for raw_setting_name, value in six.iteritems(new_settings):\n setting_name = raw_setting_name.replace(\"_\", \"-\")\n\n setting_already_exists = setting_name in self._instance_settings\n value_is_list_len_2 = isinstance(value, list) and len(value) == 2\n treat_as_tuple = not setting_already_exists and value_is_list_len_2\n\n if isinstance(value, tuple) or treat_as_tuple:\n self._instance_settings[setting_name] = value\n\n else:\n if setting_name not in self._instance_settings:\n if enforce_helpstring:\n msg = \"You must specify param '%s' as a tuple of (helpstring, value)\"\n raise InternalCashewException(msg % setting_name)\n\n else:\n # Create entry with blank helpstring.\n self._instance_settings[setting_name] = ('', value,)\n\n else:\n # Save inherited helpstring, replace default value.\n orig = self._instance_settings[setting_name]\n self._instance_settings[setting_name] = (orig[0], value,)"} {"SOURCE": "codesearchnet", "instruction": "Can you create a Python 3 function that\nreturns a combined dictionary of setting values and attribute values.", "response": "def settings_and_attributes(self):\n \"\"\"Return a combined dictionary of setting values and attribute values.\"\"\"\n attrs = self.setting_values()\n attrs.update(self.__dict__)\n skip = [\"_instance_settings\", \"aliases\"]\n for a in skip:\n del attrs[a]\n return attrs"} {"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function for\ndetecting if we get a class or a name convert a name to a class.", "response": "def get_reference_to_class(cls, class_or_class_name):\n \"\"\"\n Detect if we get a class or a name, convert a name to a class.\n \"\"\"\n if isinstance(class_or_class_name, type):\n return class_or_class_name\n\n elif isinstance(class_or_class_name, string_types):\n if \":\" in class_or_class_name:\n mod_name, class_name = class_or_class_name.split(\":\")\n\n if not mod_name in sys.modules:\n __import__(mod_name)\n\n mod = sys.modules[mod_name]\n return mod.__dict__[class_name]\n\n else:\n return cls.load_class_from_locals(class_or_class_name)\n\n else:\n msg = \"Unexpected Type '%s'\" % type(class_or_class_name)\n raise InternalCashewException(msg)"} {"SOURCE": "codesearchnet", "instruction": "Can you implement a function in Python 3 that\nchecks that the class has a docstring and returns it if successful.", "response": "def check_docstring(cls):\n \"\"\"\n Asserts that the class has a docstring, returning it if successful.\n \"\"\"\n docstring = inspect.getdoc(cls)\n if not docstring:\n breadcrumbs = \" -> \".join(t.__name__ for t in inspect.getmro(cls)[:-1][::-1])\n msg = \"docstring required for plugin '%s' (%s, defined in %s)\"\n args = (cls.__name__, breadcrumbs, cls.__module__)\n raise InternalCashewException(msg % args)\n\n max_line_length = cls._class_settings.get('max-docstring-length')\n if max_line_length:\n for i, line in enumerate(docstring.splitlines()):\n if len(line) > max_line_length:\n msg = \"docstring line %s of %s is %s chars too long\" \n args = (i, cls.__name__, len(line) - max_line_length)\n raise Exception(msg % args)\n\n return docstring"} {"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef resourcePath(self, relative_path):\n from os import path\n import sys\n \n try:\n # PyInstaller creates a temp folder and stores path in _MEIPASS\n base_path = sys._MEIPASS\n except Exception:\n base_path = path.dirname(path.abspath(__file__))\n return path.join(base_path, relative_path)", "response": "Get absolute path to resource"} {"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef addLogbook(self, physDef= \"LCLS\", mccDef=\"MCC\", initialInstance=False):\n '''Add new block of logbook selection windows. Only 5 allowed.'''\n if self.logMenuCount < 5:\n self.logMenus.append(LogSelectMenu(self.logui.multiLogLayout, initialInstance))\n self.logMenus[-1].addLogbooks(self.logTypeList[1], self.physics_programs, physDef)\n self.logMenus[-1].addLogbooks(self.logTypeList[0], self.mcc_programs, mccDef)\n self.logMenus[-1].show()\n self.logMenuCount += 1\n if initialInstance:\n # Initial logbook menu can add additional menus, all others can only remove themselves.\n QObject.connect(self.logMenus[-1].logButton, SIGNAL(\"clicked()\"), self.addLogbook)\n else:\n from functools import partial\n QObject.connect(self.logMenus[-1].logButton, SIGNAL(\"clicked()\"), partial(self.removeLogbook, self.logMenus[-1]))", "response": "Add new block of logbook selection windows. Only 5 allowed."} {"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function that can\nremove logbook menu set.", "response": "def removeLogbook(self, menu=None):\n '''Remove logbook menu set.'''\n if self.logMenuCount > 1 and menu is not None:\n menu.removeMenu()\n self.logMenus.remove(menu)\n self.logMenuCount -= 1"} {"SOURCE": "codesearchnet", "instruction": "Implement a Python 3 function for\nreturning selected log books by type.", "response": "def selectedLogs(self):\n '''Return selected log books by type.'''\n mcclogs = []\n physlogs = []\n for i in range(len(self.logMenus)):\n logType = self.logMenus[i].selectedType()\n log = self.logMenus[i].selectedProgram()\n if logType == \"MCC\":\n if log not in mcclogs:\n mcclogs.append(log)\n elif logType == \"Physics\":\n if log not in physlogs:\n physlogs.append(log)\n return mcclogs, physlogs"} {"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef acceptedUser(self, logType):\n '''Verify enetered user name is on accepted MCC logbook list.'''\n from urllib2 import urlopen, URLError, HTTPError\n import json\n \n isApproved = False\n \n userName = str(self.logui.userName.text())\n if userName == \"\":\n return False # Must have a user name to submit entry\n \n if logType == \"MCC\":\n networkFault = False\n data = []\n log_url = \"https://mccelog.slac.stanford.edu/elog/dev/mgibbs/dev_json_user_list.php/?username=\" + userName\n try:\n data = urlopen(log_url, None, 5).read()\n data = json.loads(data)\n except URLError as error:\n print(\"URLError: \" + str(error.reason))\n networkFault = True\n except HTTPError as error:\n print(\"HTTPError: \" + str(error.reason))\n networkFault = True\n \n # If network fails, ask user to verify\n if networkFault:\n msgBox = QMessageBox()\n msgBox.setText(\"Cannot connect to MCC Log Server!\")\n msgBox.setInformativeText(\"Use entered User name anyway?\")\n msgBox.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel)\n msgBox.setDefaultButton(QMessageBox.Ok)\n if msgBox.exec_() == QMessageBox.Ok:\n isApproved = True\n \n if data != [] and (data is not None):\n isApproved = True\n else:\n isApproved = True\n return isApproved", "response": "Verify enetered user name is on accepted MCC logbook list."} {"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef xmlSetup(self, logType, logList):\n \n from xml.etree.ElementTree import Element, SubElement, ElementTree\n from datetime import datetime\n \n curr_time = datetime.now()\n if logType == \"MCC\":\n # Set up xml tags\n log_entry = Element('log_entry')\n title = SubElement(log_entry, 'title')\n program = SubElement(log_entry, 'program')\n timestamp = SubElement(log_entry, 'timestamp')\n priority = SubElement(log_entry, 'priority')\n os_user = SubElement(log_entry, 'os_user')\n hostname = SubElement(log_entry, 'hostname')\n text = SubElement(log_entry, 'text')\n log_user = SubElement(log_entry, 'log_user')\n\n # Check for multiple logbooks and parse into seperate tags\n logbook = []\n for i in range(len(logList)):\n logbook.append(SubElement(log_entry, 'logbook'))\n logbook[i].text = logList[i].lower()\n \n # Take care of dummy, unchanging tags first\n log_entry.attrib['type'] = \"LOGENTRY\"\n program.text = \"152\"\n priority.text = \"NORMAL\"\n os_user.text = \"nobody\"\n hostname.text = \"mccelog\"\n text.attrib['type'] = \"text/plain\"\n \n # Handle attachment if image exists\n if not self.imagePixmap.isNull():\n attachment = SubElement(log_entry, 'attachment')\n attachment.attrib['name'] = \"Figure 1\"\n attachment.attrib['type'] = \"image/\" + self.imageType\n attachment.text = curr_time.strftime(\"%Y%m%d_%H%M%S_\") + str(curr_time.microsecond) + \".\" + self.imageType\n \n # Set timestamp format\n timestamp.text = curr_time.strftime(\"%Y/%m/%d %H:%M:%S\")\n \n fileName = \"/tmp/\" + curr_time.strftime(\"%Y%m%d_%H%M%S_\") + str(curr_time.microsecond) + \".xml\"\n \n else: # If using Physics logbook\n timeString = curr_time.strftime(\"%Y-%m-%dT%H:%M:%S\")\n \n # Set up xml tags\n log_entry = Element(None)\n severity = SubElement(log_entry, 'severity')\n location = SubElement(log_entry, 'location')\n keywords = SubElement(log_entry, 'keywords')\n time = SubElement(log_entry, 'time')\n isodate = SubElement(log_entry, 'isodate')\n log_user = SubElement(log_entry, 'author')\n category = SubElement(log_entry, 'category')\n title = SubElement(log_entry, 'title')\n metainfo = SubElement(log_entry, 'metainfo')\n \n # Handle attachment if image exists\n if not self.imagePixmap.isNull():\n imageFile = SubElement(log_entry, 'link')\n imageFile.text = timeString + \"-00.\" + self.imageType\n thumbnail = SubElement(log_entry, 'file')\n thumbnail.text = timeString + \"-00.png\"\n \n text = SubElement(log_entry, 'text') # Logbook expects Text tag to come last (for some strange reason)\n \n # Take care of dummy, unchanging tags first\n log_entry.attrib['type'] = \"LOGENTRY\"\n category.text = \"USERLOG\"\n location.text = \"not set\"\n severity.text = \"NONE\"\n keywords.text = \"none\"\n \n time.text = curr_time.strftime(\"%H:%M:%S\")\n isodate.text = curr_time.strftime(\"%Y-%m-%d\")\n \n metainfo.text = timeString + \"-00.xml\"\n fileName = \"/tmp/\" + metainfo.text\n \n # Fill in user inputs\n log_user.text = str(self.logui.userName.text())\n\n title.text = str(self.logui.titleEntry.text())\n if title.text == \"\":\n QMessageBox().warning(self, \"No Title entered\", \"Please enter a title for the entry...\")\n return None\n \n text.text = str(self.logui.textEntry.toPlainText())\n # If text field is truly empty, ElementTree leaves off tag entirely which causes logbook parser to fail\n if text.text == \"\":\n text.text = \" \"\n \n # Create xml file\n xmlFile = open(fileName, \"w\")\n if logType == \"MCC\":\n ElementTree(log_entry).write(xmlFile)\n else:\n xmlString = self.prettify(log_entry)\n xmlFile.write(xmlString)\n xmlFile.write(\"\\n\") # Close with newline so cron job parses correctly\n xmlFile.close()\n \n return fileName.rstrip(\".xml\")", "response": "Create xml file with fields from logbook form."} {"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function for\nparsing xml elements for pretty printing", "response": "def prettify(self, elem):\n \"\"\"Parse xml elements for pretty printing\"\"\"\n \n from xml.etree import ElementTree\n from re import sub\n \n rawString = ElementTree.tostring(elem, 'utf-8')\n parsedString = sub(r'(?=<[^/].*>)', '\\n', rawString) # Adds newline after each closing tag\n \n return parsedString[1:]"} {"SOURCE": "codesearchnet", "instruction": "Implement a function in Python 3 to\nconvert supplied QPixmap object to image file.", "response": "def prepareImages(self, fileName, logType):\n \"\"\"Convert supplied QPixmap object to image file.\"\"\"\n import subprocess\n \n if self.imageType == \"png\":\n self.imagePixmap.save(fileName + \".png\", \"PNG\", -1)\n if logType == \"Physics\":\n makePostScript = \"convert \" + fileName + \".png \" + fileName + \".ps\"\n process = subprocess.Popen(makePostScript, shell=True)\n process.wait()\n thumbnailPixmap = self.imagePixmap.scaled(500, 450, Qt.KeepAspectRatio)\n thumbnailPixmap.save(fileName + \".png\", \"PNG\", -1)\n else:\n renameImage = \"cp \" + self.image + \" \" + fileName + \".gif\"\n process = subprocess.Popen(renameImage, shell=True)\n process.wait()\n if logType == \"Physics\":\n thumbnailPixmap = self.imagePixmap.scaled(500, 450, Qt.KeepAspectRatio)\n thumbnailPixmap.save(fileName + \".png\", \"PNG\", -1)"} {"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef submitEntry(self):\n \n # logType = self.logui.logType.currentText()\n mcclogs, physlogs = self.selectedLogs()\n success = True\n \n if mcclogs != []:\n if not self.acceptedUser(\"MCC\"):\n QMessageBox().warning(self, \"Invalid User\", \"Please enter a valid user name!\")\n return\n \n fileName = self.xmlSetup(\"MCC\", mcclogs)\n if fileName is None:\n return\n \n if not self.imagePixmap.isNull():\n self.prepareImages(fileName, \"MCC\")\n success = self.sendToLogbook(fileName, \"MCC\")\n \n if physlogs != []:\n for i in range(len(physlogs)):\n fileName = self.xmlSetup(\"Physics\", physlogs[i])\n if fileName is None:\n return\n \n if not self.imagePixmap.isNull():\n self.prepareImages(fileName, \"Physics\")\n success_phys = self.sendToLogbook(fileName, \"Physics\", physlogs[i])\n success = success and success_phys\n \n self.done(success)", "response": "Process user inputs and subit logbook entry when user clicks Submit button"} {"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function for\nprocessing log information and push to selected logbooks.", "response": "def sendToLogbook(self, fileName, logType, location=None):\n '''Process log information and push to selected logbooks.'''\n import subprocess\n \n success = True\n if logType == \"MCC\":\n fileString = \"\"\n if not self.imagePixmap.isNull():\n fileString = fileName + \".\" + self.imageType\n \n logcmd = \"xml2elog \" + fileName + \".xml \" + fileString\n process = subprocess.Popen(logcmd, shell=True)\n process.wait()\n if process.returncode != 0:\n success = False\n else:\n from shutil import copy\n\n path = \"/u1/\" + location.lower() + \"/physics/logbook/data/\" # Prod path\n # path = \"/home/softegr/alverson/log_test/\" # Dev path\n try:\n if not self.imagePixmap.isNull():\n copy(fileName + \".png\", path)\n if self.imageType == \"png\":\n copy(fileName + \".ps\", path)\n else:\n copy(fileName + \".\" + self.imageType, path)\n \n # Copy .xml file last to ensure images will be picked up by cron job\n # print(\"Copying file \" + fileName + \" to path \" + path)\n copy(fileName + \".xml\", path)\n except IOError as error:\n print(error)\n success = False\n \n return success"} {"SOURCE": "codesearchnet", "instruction": "How would you implement a function in Python 3 that\nclears all form fields except author.", "response": "def clearForm(self):\n \"\"\"Clear all form fields (except author).\"\"\"\n \n self.logui.titleEntry.clear()\n self.logui.textEntry.clear()\n\n # Remove all log selection menus except the first\n while self.logMenuCount > 1:\n self.removeLogbook(self.logMenus[-1])"} {"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef setupUI(self):\n '''Create graphical objects for menus.'''\n \n labelSizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)\n labelSizePolicy.setHorizontalStretch(0)\n labelSizePolicy.setVerticalStretch(0)\n menuSizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)\n menuSizePolicy.setHorizontalStretch(0)\n menuSizePolicy.setVerticalStretch(0)\n \n logTypeLayout = QHBoxLayout()\n logTypeLayout.setSpacing(0)\n \n typeLabel = QLabel(\"Log Type:\")\n typeLabel.setMinimumSize(QSize(65, 0))\n typeLabel.setMaximumSize(QSize(65, 16777215))\n typeLabel.setSizePolicy(labelSizePolicy)\n logTypeLayout.addWidget(typeLabel)\n self.logType = QComboBox(self)\n self.logType.setMinimumSize(QSize(100, 0))\n self.logType.setMaximumSize(QSize(150, 16777215))\n menuSizePolicy.setHeightForWidth(self.logType.sizePolicy().hasHeightForWidth())\n self.logType.setSizePolicy(menuSizePolicy)\n logTypeLayout.addWidget(self.logType)\n logTypeLayout.setStretch(1, 6)\n \n programLayout = QHBoxLayout()\n programLayout.setSpacing(0)\n \n programLabel = QLabel(\"Program:\")\n programLabel.setMinimumSize(QSize(60, 0))\n programLabel.setMaximumSize(QSize(60, 16777215))\n programLabel.setSizePolicy(labelSizePolicy)\n programLayout.addWidget(programLabel)\n self.programName = QComboBox(self)\n self.programName.setMinimumSize(QSize(100, 0))\n self.programName.setMaximumSize(QSize(150, 16777215))\n menuSizePolicy.setHeightForWidth(self.programName.sizePolicy().hasHeightForWidth())\n self.programName.setSizePolicy(menuSizePolicy)\n programLayout.addWidget(self.programName)\n programLayout.setStretch(1, 6)\n \n # Initial instance allows adding additional menus, all following menus can only remove themselves.\n if self.initialInstance:\n self.logButton = QPushButton(\"+\", self)\n self.logButton.setToolTip(\"Add logbook\")\n else:\n self.logButton = QPushButton(\"-\")\n self.logButton.setToolTip(\"Remove logbook\")\n \n self.logButton.setMinimumSize(QSize(16, 16)) # 24x24\n self.logButton.setMaximumSize(QSize(16, 16)) # 24x24\n self.logButton.setObjectName(\"roundButton\")\n # self.logButton.setAutoFillBackground(True)\n # region = QRegion(QRect(self.logButton.x()+15, self.logButton.y()+14, 20, 20), QRegion.Ellipse)\n # self.logButton.setMask(region)\n \n self.logButton.setStyleSheet(\"QPushButton {border-radius: 8px;}\")\n \n self._logSelectLayout = QHBoxLayout()\n self._logSelectLayout.setSpacing(6)\n self._logSelectLayout.addLayout(logTypeLayout)\n self._logSelectLayout.addLayout(programLayout)\n self._logSelectLayout.addWidget(self.logButton)\n self._logSelectLayout.setStretch(0, 6)\n self._logSelectLayout.setStretch(1, 6)", "response": "Create graphical objects for menus."} {"SOURCE": "codesearchnet", "instruction": "Can you create a Python 3 function that\ndisplays menus and connect even signals.", "response": "def show(self):\n '''Display menus and connect even signals.'''\n self.parent.addLayout(self._logSelectLayout)\n self.menuCount += 1\n self._connectSlots()"} {"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef addLogbooks(self, type=None, logs=[], default=\"\"):\n '''Add or change list of logbooks.'''\n if type is not None and len(logs) != 0:\n if type in self.logList:\n for logbook in logs:\n if logbook not in self.logList.get(type)[0]:\n # print(\"Adding log \" + \" to \" + type + \" log type.\")\n self.logList.get(type)[0].append(logbook)\n else:\n # print(\"Adding log type: \" + type)\n self.logList[type] = []\n self.logList[type].append(logs)\n \n # If default given, auto-select upon menu creation\n if len(self.logList[type]) > 1 and default != \"\":\n self.logList.get(type)[1] == default\n else:\n self.logList.get(type).append(default)\n \n self.logType.clear()\n self.logType.addItems(list(self.logList.keys()))\n self.changeLogType()", "response": "Add or change list of logbooks."} {"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef removeLogbooks(self, type=None, logs=[]):\n '''Remove unwanted logbooks from list.'''\n if type is not None and type in self.logList:\n if len(logs) == 0 or logs == \"All\":\n del self.logList[type]\n else:\n for logbook in logs:\n if logbook in self.logList[type]:\n self.logList[type].remove(logbook)\n \n self.changeLogType()", "response": "Remove unwanted logbooks from list."} {"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function that can\npopulate log program list to correspond with log type selection.", "response": "def changeLogType(self):\n '''Populate log program list to correspond with log type selection.'''\n logType = self.selectedType()\n programs = self.logList.get(logType)[0]\n default = self.logList.get(logType)[1]\n if logType in self.logList:\n self.programName.clear()\n self.programName.addItems(programs)\n self.programName.setCurrentIndex(programs.index(default))"} {"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef addMenu(self):\n '''Add menus to parent gui.'''\n self.parent.multiLogLayout.addLayout(self.logSelectLayout)\n self.getPrograms(logType, programName)", "response": "Add menus to parent gui."} {"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef removeLayout(self, layout):\n '''Iteratively remove graphical objects from layout.'''\n for cnt in reversed(range(layout.count())):\n item = layout.takeAt(cnt)\n widget = item.widget()\n if widget is not None:\n widget.deleteLater()\n else:\n '''If sublayout encountered, iterate recursively.'''\n self.removeLayout(item.layout())", "response": "Remove graphical objects from layout."} {"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef addlabel(ax=None, toplabel=None, xlabel=None, ylabel=None, zlabel=None, clabel=None, cb=None, windowlabel=None, fig=None, axes=None):\n\n if (axes is None) and (ax is not None):\n axes = ax\n\n if (windowlabel is not None) and (fig is not None):\n fig.canvas.set_window_title(windowlabel)\n\n if fig is None:\n fig = _plt.gcf()\n\n if fig is not None and axes is None:\n axes = fig.get_axes()\n if axes == []:\n logger.error('No axes found!')\n\n if axes is not None:\n if toplabel is not None:\n axes.set_title(toplabel)\n if xlabel is not None:\n axes.set_xlabel(xlabel)\n if ylabel is not None:\n axes.set_ylabel(ylabel)\n if zlabel is not None:\n axes.set_zlabel(zlabel)\n\n if (clabel is not None) or (cb is not None):\n if (clabel is not None) and (cb is not None):\n cb.set_label(clabel)\n else:\n if clabel is None:\n logger.error('Missing colorbar label')\n else:\n logger.error('Missing colorbar instance')", "response": "Adds labels to a plot."} {"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function for\ndetermining the URL corresponding to Python object", "response": "def linkcode_resolve(domain, info):\n \"\"\"\n Determine the URL corresponding to Python object\n \"\"\"\n if domain != 'py':\n return None\n\n modname = info['module']\n fullname = info['fullname']\n\n submod = sys.modules.get(modname)\n if submod is None:\n return None\n\n obj = submod\n for part in fullname.split('.'):\n try:\n obj = getattr(obj, part)\n except:\n return None\n\n try:\n fn = inspect.getsourcefile(obj)\n except:\n fn = None\n if not fn:\n return None\n\n try:\n source, lineno = inspect.getsourcelines(obj)\n except:\n lineno = None\n\n if lineno:\n linespec = \"#L%d-L%d\" % (lineno, lineno + len(source) - 1)\n else:\n linespec = \"\"\n\n fn = relpath(fn, start=dirname(scisalt.__file__))\n\n if 'dev' in scisalt.__version__:\n return \"http://github.com/joelfrederico/SciSalt/blob/master/scisalt/%s%s\" % (\n fn, linespec)\n else:\n return \"http://github.com/joelfrederico/SciSalt/blob/v%s/scisalt/%s%s\" % (\n scisalt.__version__, fn, linespec)"} {"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef syncdb(args):\n cmd = args and 'syncdb %s' % ' '.join(options.args) or 'syncdb --noinput'\n call_manage(cmd)\n for fixture in options.paved.django.syncdb.fixtures:\n call_manage(\"loaddata %s\" % fixture)", "response": "Update the database with model schema. Shorthand for paver manage syncdb."} {"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef start(info):\n cmd = options.paved.django.runserver\n\n if cmd == 'runserver_plus':\n try:\n import django_extensions\n except ImportError:\n info(\"Could not import django_extensions. Using default runserver.\")\n cmd = 'runserver'\n\n port = options.paved.django.runserver_port\n if port:\n cmd = '%s %s' % (cmd, port)\n\n call_manage(cmd)", "response": "Start the dev server."} {"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef schema(args):\n try:\n import south\n cmd = args and 'schemamigration %s' % ' '.join(options.args) or 'schemamigration'\n call_manage(cmd)\n except ImportError:\n error('Could not import south.')", "response": "Run South s schemamigration command."} {"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef validate(cls, definition):\n '''\n This static method validates a BioMapMapper definition.\n It returns None on success and throws an exception otherwise.\n '''\n schema_path = os.path.join(os.path.dirname(__file__),\n '../../schema/mapper_definition_schema.json')\n with open(schema_path, 'r') as jsonfp:\n schema = json.load(jsonfp)\n # Validation of JSON schema\n jsonschema.validate(definition, schema)\n # Validation of JSON properties relations\n assert definition['main_key'] in definition['supported_keys'], \\\n '\\'main_key\\' must be contained in \\'supported_keys\\''\n assert set(definition.get('list_valued_keys', [])) <= set(definition['supported_keys']), \\\n '\\'list_valued_keys\\' must be a subset of \\'supported_keys\\''\n assert set(definition.get('disjoint', [])) <= set(definition.get('list_valued_keys', [])), \\\n '\\'disjoint\\' must be a subset of \\'list_valued_keys\\''\n assert set(definition.get('key_synonyms', {}).values()) <= set(definition['supported_keys']), \\\n '\\'The values of the \\'key_synonyms\\' mapping must be in \\'supported_keys\\''", "response": "This static method validates a BioMapMapper definition. It returns None on failure and throws an exception if the definition is invalid."} {"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script for\nreturning all data entries for a particular key. Default is the main key.", "response": "def get_all(self, key=None):\n '''\n Returns all data entries for a particular key. Default is the main key.\n\n Args:\n\n key (str): key whose values to return (default: main key)\n\n Returns:\n\n List of all data entries for the key\n '''\n key = self.definition.main_key if key is None else key\n key = self.definition.key_synonyms.get(key, key)\n entries = self._get_all(key)\n if key in self.definition.scalar_nonunique_keys:\n return set(entries)\n return entries"} {"SOURCE": "codesearchnet", "instruction": "Can you create a Python 3 function that\ngets all the requests in the database.", "response": "def get_requests(self, params={}):\n \"\"\"\n List requests\n\n http://dev.wheniwork.com/#listing-requests\n \"\"\"\n if \"status\" in params:\n params['status'] = ','.join(map(str, params['status']))\n\n requests = []\n users = {}\n messages = {}\n params['page'] = 0\n while True:\n param_list = [(k, params[k]) for k in sorted(params)]\n url = \"/2/requests/?%s\" % urlencode(param_list)\n\n data = self._get_resource(url)\n for entry in data[\"users\"]:\n user = Users.user_from_json(entry)\n users[user.user_id] = user\n for entry in data[\"requests\"]:\n request = self.request_from_json(entry)\n requests.append(request)\n for entry in data[\"messages\"]:\n message = Messages.message_from_json(entry)\n if message.request_id not in messages:\n messages[message.request_id] = []\n messages[message.request_id].append(message)\n\n if not data['more']:\n break\n\n params['page'] += 1\n\n for request in requests:\n request.user = users.get(request.user_id, None)\n request.messages = messages.get(request.request_id, [])\n\n return requests"} {"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function for\nmaking a guess of the hidden object to a set of digits.", "response": "def guess(self, *args):\n \"\"\"\n Make a guess, comparing the hidden object to a set of provided digits. The digits should\n be passed as a set of arguments, e.g:\n\n * for a normal game: 0, 1, 2, 3\n * for a hex game: 0xA, 0xB, 5, 4\n * alternate for hex game: 'A', 'b', 5, 4\n\n :param args: An iterable of digits (int or str)\n :return: A dictionary object detailing the analysis and results of the guess\n \"\"\"\n\n if self.game is None:\n raise ValueError(\"The Game is unexpectedly undefined!\")\n\n response_object = {\n \"bulls\": None,\n \"cows\": None,\n \"analysis\": None,\n \"status\": None\n }\n\n if self.game.status == self.GAME_WON:\n response_object[\"status\"] = \\\n self._start_again_message(\"You already won!\")\n elif self.game.status == self.GAME_LOST:\n response_object[\"status\"] = \\\n self._start_again_message(\"You already lost!\")\n elif self.game.guesses_remaining < 1:\n response_object[\"status\"] = \\\n self._start_again_message(\"You've made too many guesses\")\n else:\n guess_made = DigitWord(*args, wordtype=self.game.mode.digit_type)\n comparison = self.game.answer.compare(guess_made)\n\n self.game.guesses_made += 1\n response_object[\"bulls\"] = 0\n response_object[\"cows\"] = 0\n response_object[\"analysis\"] = []\n\n for comparison_object in comparison:\n if comparison_object.match:\n response_object[\"bulls\"] += 1\n elif comparison_object.in_word:\n response_object[\"cows\"] += 1\n response_object[\"analysis\"].append(comparison_object.get_object())\n\n if response_object[\"bulls\"] == self.game.mode.digits:\n self.game.status = self.GAME_WON\n self.game.guesses_made = self.game.mode.guesses_allowed\n response_object[\"status\"] = self._start_again_message(\n \"Congratulations, you win!\"\n )\n elif self.game.guesses_remaining < 1:\n self.game.status = self.GAME_LOST\n response_object[\"status\"] = self._start_again_message(\n \"Sorry, you lost!\"\n )\n\n return response_object"} {"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function that can\nload a game from a serialized JSON representation.", "response": "def load(self, game_json=None, mode=None):\n \"\"\"\n Load a game from a serialized JSON representation. The game expects a well defined\n structure as follows (Note JSON string format):\n\n '{\n \"guesses_made\": int,\n \"key\": \"str:a 4 word\",\n \"status\": \"str: one of playing, won, lost\",\n \"mode\": {\n \"digits\": int,\n \"digit_type\": DigitWord.DIGIT | DigitWord.HEXDIGIT,\n \"mode\": GameMode(),\n \"priority\": int,\n \"help_text\": str,\n \"instruction_text\": str,\n \"guesses_allowed\": int\n },\n \"ttl\": int,\n \"answer\": [int|str0, int|str1, ..., int|strN]\n }'\n\n * \"mode\" will be cast to a GameMode object\n * \"answer\" will be cast to a DigitWord object\n\n :param game_json: The source JSON - MUST be a string\n :param mode: A mode (str or GameMode) for the game being loaded\n :return: A game object\n \"\"\"\n\n if game_json is None: # New game_json\n if mode is not None:\n if isinstance(mode, str):\n _game_object = GameObject(mode=self._match_mode(mode=mode))\n elif isinstance(mode, GameMode):\n _game_object = GameObject(mode=mode)\n else:\n raise TypeError(\"Game mode must be a GameMode or string\")\n else:\n _game_object = GameObject(mode=self._game_modes[0])\n _game_object.status = self.GAME_PLAYING\n else:\n if not isinstance(game_json, str):\n raise TypeError(\"Game must be passed as a serialized JSON string.\")\n\n game_dict = json.loads(game_json)\n\n if not 'mode' in game_dict:\n raise ValueError(\"Mode is not provided in JSON; game_json cannot be loaded!\")\n\n _mode = GameMode(**game_dict[\"mode\"])\n _game_object = GameObject(mode=_mode, source_game=game_dict)\n\n self.game = copy.deepcopy(_game_object)"} {"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script to\nload the game modes for the current locale.", "response": "def load_modes(self, input_modes=None):\n \"\"\"\n Loads modes (GameMode objects) to be supported by the game object. Four default\n modes are provided (normal, easy, hard, and hex) but others could be provided\n either by calling load_modes directly or passing a list of GameMode objects to\n the instantiation call.\n\n :param input_modes: A list of GameMode objects; nb: even if only one new GameMode\n object is provided, it MUST be passed as a list - for example, passing GameMode gm1\n would require passing [gm1] NOT gm1.\n\n :return: A list of GameMode objects (both defaults and any added).\n \"\"\"\n\n # Set default game modes\n _modes = [\n GameMode(\n mode=\"normal\", priority=2, digits=4, digit_type=DigitWord.DIGIT, guesses_allowed=10\n ),\n GameMode(\n mode=\"easy\", priority=1, digits=3, digit_type=DigitWord.DIGIT, guesses_allowed=6\n ),\n GameMode(\n mode=\"hard\", priority=3, digits=6, digit_type=DigitWord.DIGIT, guesses_allowed=6\n ),\n GameMode(\n mode=\"hex\", priority=4, digits=4, digit_type=DigitWord.HEXDIGIT, guesses_allowed=10\n )\n ]\n\n if input_modes is not None:\n if not isinstance(input_modes, list):\n raise TypeError(\"Expected list of input_modes\")\n\n for mode in input_modes:\n if not isinstance(mode, GameMode):\n raise TypeError(\"Expected list to contain only GameMode objects\")\n _modes.append(mode)\n\n self._game_modes = copy.deepcopy(_modes)"} {"SOURCE": "codesearchnet", "instruction": "Can you write a function in Python 3 where it\nreturns list of strings split by input delimeter", "response": "def line(self, line):\n \"\"\"Returns list of strings split by input delimeter\n\n Argument:\n line - Input line to cut\n \"\"\"\n # Remove empty strings in case of multiple instances of delimiter\n return [x for x in re.split(self.delimiter, line.rstrip()) if x != '']"} {"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef get_message(self, message_id):\n url = \"/2/messages/%s\" % message_id\n\n return self.message_from_json(self._get_resource(url)[\"message\"])", "response": "Get a specific message by its ID"} {"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef get_messages(self, params={}):\n param_list = [(k, params[k]) for k in sorted(params)]\n url = \"/2/messages/?%s\" % urlencode(param_list)\n\n data = self._get_resource(url)\n messages = []\n for entry in data[\"messages\"]:\n messages.append(self.message_from_json(entry))\n\n return messages", "response": "Get all the messages from wheniwork."} {"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef create_message(self, params={}):\n url = \"/2/messages/\"\n body = params\n\n data = self._post_resource(url, body)\n return self.message_from_json(data[\"message\"])", "response": "Creates a new message in the given params"} {"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef update_message(self, message):\n url = \"/2/messages/%s\" % message.message_id\n\n data = self._put_resource(url, message.json_data())\n return self.message_from_json(data)", "response": "Modify an existing message."} {"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef delete_messages(self, messages):\n url = \"/2/messages/?%s\" % urlencode([('ids', \",\".join(messages))])\n\n data = self._delete_resource(url)\n return data", "response": "Delete existing messages.\n\n http://dev.wheniwork.com/#delete-existing-message"} {"SOURCE": "codesearchnet", "instruction": "Can you write a function in Python 3 where it\nreturns site data. http://dev.wheniwork.com/#get-existing-site", "response": "def get_site(self, site_id):\n \"\"\"\n Returns site data.\n\n http://dev.wheniwork.com/#get-existing-site\n \"\"\"\n url = \"/2/sites/%s\" % site_id\n\n return self.site_from_json(self._get_resource(url)[\"site\"])"} {"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef get_sites(self):\n url = \"/2/sites\"\n\n data = self._get_resource(url)\n sites = []\n for entry in data['sites']:\n sites.append(self.site_from_json(entry))\n\n return sites", "response": "Returns a list of sites."} {"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function for\ncreating a site with the given parameters.", "response": "def create_site(self, params={}):\n \"\"\"\n Creates a site\n\n http://dev.wheniwork.com/#create-update-site\n \"\"\"\n url = \"/2/sites/\"\n body = params\n\n data = self._post_resource(url, body)\n return self.site_from_json(data[\"site\"])"} {"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script to\nreturn a link to a view that moves the passed in object up in rank.", "response": "def admin_link_move_up(obj, link_text='up'):\n \"\"\"Returns a link to a view that moves the passed in object up in rank.\n\n :param obj:\n Object to move\n :param link_text:\n Text to display in the link. Defaults to \"up\"\n :returns:\n HTML link code to view for moving the object\n \"\"\"\n if obj.rank == 1:\n return ''\n\n content_type = ContentType.objects.get_for_model(obj)\n link = reverse('awl-rankedmodel-move', args=(content_type.id, obj.id, \n obj.rank - 1))\n\n return '%s' % (link, link_text)"} {"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script for\nreturning a link to a view that moves the passed in object down in rank.", "response": "def admin_link_move_down(obj, link_text='down'):\n \"\"\"Returns a link to a view that moves the passed in object down in rank.\n\n :param obj:\n Object to move\n :param link_text:\n Text to display in the link. Defaults to \"down\"\n :returns:\n HTML link code to view for moving the object\n \"\"\"\n if obj.rank == obj.grouped_filter().count():\n return ''\n\n content_type = ContentType.objects.get_for_model(obj)\n link = reverse('awl-rankedmodel-move', args=(content_type.id, obj.id, \n obj.rank + 1))\n\n return '%s' % (link, link_text)"} {"SOURCE": "codesearchnet", "instruction": "Implement a function in Python 3 to\nshow a figure with a typical orientation so that x and y axes are set up as expected.", "response": "def showfig(fig, aspect=\"auto\"):\n \"\"\"\n Shows a figure with a typical orientation so that x and y axes are set up as expected.\n \"\"\"\n\n ax = fig.gca()\n\n # Swap y axis if needed\n alim = list(ax.axis())\n if alim[3] < alim[2]:\n temp = alim[2]\n alim[2] = alim[3]\n alim[3] = temp\n ax.axis(alim)\n\n ax.set_aspect(aspect)\n fig.show()"} {"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef _setup_index(index):\n index = int(index)\n if index > 0:\n index -= 1\n elif index == 0:\n # Zero indicies should not be allowed by default.\n raise ValueError\n return index", "response": "Sets up the index for the base base."} {"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef cut(self, line):\n result = []\n line = self.line(line)\n\n for i, field in enumerate(self.positions):\n try:\n index = _setup_index(field)\n try:\n result += line[index]\n except IndexError:\n result.append(self.invalid_pos)\n except ValueError:\n result.append(str(field))\n except TypeError:\n result.extend(self._cut_range(line, int(field[0]), i))\n\n return ''.join(result)", "response": "Returns selected positions from cut input source in desired\n arrangement."} {"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function that can\nprocess the list of positions and ranges to account for ranges", "response": "def _setup_positions(self, positions):\n \"\"\"Processes positions to account for ranges\n\n Arguments:\n positions - list of positions and/or ranges to process\n \"\"\"\n updated_positions = []\n\n for i, position in enumerate(positions):\n ranger = re.search(r'(?P