hexsha
stringlengths
40
40
repo
stringlengths
7
114
path
stringlengths
4
124
license
listlengths
1
9
language
stringclasses
1 value
identifier
stringlengths
1
71
return_type
stringlengths
1
749
original_string
stringlengths
76
22.7k
original_docstring
stringlengths
16
7.61k
docstring
stringlengths
16
2.47k
docstring_tokens
listlengths
6
477
code
stringlengths
14
10.2k
code_tokens
listlengths
6
996
short_docstring
stringlengths
2
644
short_docstring_tokens
listlengths
1
116
comment
listlengths
1
89
parameters
listlengths
0
64
docstring_params
dict
85e5f25e687a3bf64dce7990c378a34266dcba0b
niosus/homework_checker
homework_checker/core/tools.py
[ "Apache-2.0" ]
Python
succeeded
bool
def succeeded(self: CmdResult) -> bool: """Check if the command succeeded.""" if self.returncode is not None: return self.returncode == CmdResult.SUCCESS if self.stderr: return False return True
Check if the command succeeded.
Check if the command succeeded.
[ "Check", "if", "the", "command", "succeeded", "." ]
def succeeded(self: CmdResult) -> bool: if self.returncode is not None: return self.returncode == CmdResult.SUCCESS if self.stderr: return False return True
[ "def", "succeeded", "(", "self", ":", "CmdResult", ")", "->", "bool", ":", "if", "self", ".", "returncode", "is", "not", "None", ":", "return", "self", ".", "returncode", "==", "CmdResult", ".", "SUCCESS", "if", "self", ".", "stderr", ":", "return", "F...
Check if the command succeeded.
[ "Check", "if", "the", "command", "succeeded", "." ]
[ "\"\"\"Check if the command succeeded.\"\"\"" ]
[ { "param": "self", "type": "CmdResult" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": "CmdResult", "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
85e5f25e687a3bf64dce7990c378a34266dcba0b
niosus/homework_checker
homework_checker/core/tools.py
[ "Apache-2.0" ]
Python
run_command
CmdResult
def run_command( command: Union[List[str], str], timeout: float, shell: bool = True, cwd: Path = Path.cwd(), env: Optional[Mapping[str, Any]] = None, ) -> CmdResult: """Run a generic command in a subprocess. Args: command (str): command to run Returns: str: raw command o...
Run a generic command in a subprocess. Args: command (str): command to run Returns: str: raw command output
Run a generic command in a subprocess.
[ "Run", "a", "generic", "command", "in", "a", "subprocess", "." ]
def run_command( command: Union[List[str], str], timeout: float, shell: bool = True, cwd: Path = Path.cwd(), env: Optional[Mapping[str, Any]] = None, ) -> CmdResult: try: startupinfo = None if shell and isinstance(command, list): command = subprocess.list2cmdline(comm...
[ "def", "run_command", "(", "command", ":", "Union", "[", "List", "[", "str", "]", ",", "str", "]", ",", "timeout", ":", "float", ",", "shell", ":", "bool", "=", "True", ",", "cwd", ":", "Path", "=", "Path", ".", "cwd", "(", ")", ",", "env", ":"...
Run a generic command in a subprocess.
[ "Run", "a", "generic", "command", "in", "a", "subprocess", "." ]
[ "\"\"\"Run a generic command in a subprocess.\n\n Args:\n command (str): command to run\n Returns:\n str: raw command output\n \"\"\"" ]
[ { "param": "command", "type": "Union[List[str], str]" }, { "param": "timeout", "type": "float" }, { "param": "shell", "type": "bool" }, { "param": "cwd", "type": "Path" }, { "param": "env", "type": "Optional[Mapping[str, Any]]" } ]
{ "returns": [ { "docstring": "raw command output", "docstring_tokens": [ "raw", "command", "output" ], "type": "str" } ], "raises": [], "params": [ { "identifier": "command", "type": "Union[List[str], str]", "docstring": "command to ...
85e5f25e687a3bf64dce7990c378a34266dcba0b
niosus/homework_checker
homework_checker/core/tools.py
[ "Apache-2.0" ]
Python
__run_subprocess
subprocess.CompletedProcess
def __run_subprocess( command: Union[List[str], str], str_input: str = None, timeout: float = None, check: bool = False, **kwargs ) -> subprocess.CompletedProcess: """Run a command as a subprocess. Using the guide from StackOverflow: https://stackoverflow.com/a/36955420/1763680 This...
Run a command as a subprocess. Using the guide from StackOverflow: https://stackoverflow.com/a/36955420/1763680 This command has been adapted from: https://github.com/python/cpython/blob/3.5/Lib/subprocess.py#L352-L399 This code does essentially the same as subprocess.run(...) but makes sure to ...
Run a command as a subprocess. This code does essentially the same as subprocess.run(...) but makes sure to kill the whole process tree which allows to use the timeout even when using shell=True. The reason I don't want to stop using shell=True here is the convenience of piping arguments from one function to another.
[ "Run", "a", "command", "as", "a", "subprocess", ".", "This", "code", "does", "essentially", "the", "same", "as", "subprocess", ".", "run", "(", "...", ")", "but", "makes", "sure", "to", "kill", "the", "whole", "process", "tree", "which", "allows", "to", ...
def __run_subprocess( command: Union[List[str], str], str_input: str = None, timeout: float = None, check: bool = False, **kwargs ) -> subprocess.CompletedProcess: if str_input is not None: if "stdin" in kwargs: raise ValueError("stdin and str_input arguments may not both be ...
[ "def", "__run_subprocess", "(", "command", ":", "Union", "[", "List", "[", "str", "]", ",", "str", "]", ",", "str_input", ":", "str", "=", "None", ",", "timeout", ":", "float", "=", "None", ",", "check", ":", "bool", "=", "False", ",", "**", "kwarg...
Run a command as a subprocess.
[ "Run", "a", "command", "as", "a", "subprocess", "." ]
[ "\"\"\"Run a command as a subprocess.\n\n Using the guide from StackOverflow:\n https://stackoverflow.com/a/36955420/1763680\n This command has been adapted from:\n https://github.com/python/cpython/blob/3.5/Lib/subprocess.py#L352-L399\n\n This code does essentially the same as subprocess.run(...) bu...
[ { "param": "command", "type": "Union[List[str], str]" }, { "param": "str_input", "type": "str" }, { "param": "timeout", "type": "float" }, { "param": "check", "type": "bool" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "command", "type": "Union[List[str], str]", "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "str_input", "type": "str", "docstring": null,...
244c45569d5682ea0858d59e4c6d48764f7d9a8c
niosus/homework_checker
homework_checker/core/checker.py
[ "Apache-2.0" ]
Python
check_homework
HomeworkResultDict
def check_homework(self: "Checker", homework_node: dict) -> HomeworkResultDict: """Run over all Tasks in a single homework.""" results: HomeworkResultDict = {} current_folder = Path(self._checked_code_folder, homework_node[Tags.FOLDER_TAG]) log.debug("current_folder: %s", current_folder)...
Run over all Tasks in a single homework.
Run over all Tasks in a single homework.
[ "Run", "over", "all", "Tasks", "in", "a", "single", "homework", "." ]
def check_homework(self: "Checker", homework_node: dict) -> HomeworkResultDict: results: HomeworkResultDict = {} current_folder = Path(self._checked_code_folder, homework_node[Tags.FOLDER_TAG]) log.debug("current_folder: %s", current_folder) if not current_folder.exists(): lo...
[ "def", "check_homework", "(", "self", ":", "\"Checker\"", ",", "homework_node", ":", "dict", ")", "->", "HomeworkResultDict", ":", "results", ":", "HomeworkResultDict", "=", "{", "}", "current_folder", "=", "Path", "(", "self", ".", "_checked_code_folder", ",", ...
Run over all Tasks in a single homework.
[ "Run", "over", "all", "Tasks", "in", "a", "single", "homework", "." ]
[ "\"\"\"Run over all Tasks in a single homework.\"\"\"" ]
[ { "param": "self", "type": "\"Checker\"" }, { "param": "homework_node", "type": "dict" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": "\"Checker\"", "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "homework_node", "type": "dict", "docstring": null, "...
244c45569d5682ea0858d59e4c6d48764f7d9a8c
niosus/homework_checker
homework_checker/core/checker.py
[ "Apache-2.0" ]
Python
check_all_homeworks
Dict[str, HomeworkResultDict]
def check_all_homeworks(self: "Checker") -> Dict[str, HomeworkResultDict]: """Run over all Tasks in all homeworks.""" results: Dict[str, HomeworkResultDict] = {} for idx, homework_node in enumerate(self._base_node[Tags.HOMEWORKS_TAG]): hw_name = tools.add_number_to_name(idx, homework...
Run over all Tasks in all homeworks.
Run over all Tasks in all homeworks.
[ "Run", "over", "all", "Tasks", "in", "all", "homeworks", "." ]
def check_all_homeworks(self: "Checker") -> Dict[str, HomeworkResultDict]: results: Dict[str, HomeworkResultDict] = {} for idx, homework_node in enumerate(self._base_node[Tags.HOMEWORKS_TAG]): hw_name = tools.add_number_to_name(idx, homework_node[Tags.NAME_TAG]) current_homework_...
[ "def", "check_all_homeworks", "(", "self", ":", "\"Checker\"", ")", "->", "Dict", "[", "str", ",", "HomeworkResultDict", "]", ":", "results", ":", "Dict", "[", "str", ",", "HomeworkResultDict", "]", "=", "{", "}", "for", "idx", ",", "homework_node", "in", ...
Run over all Tasks in all homeworks.
[ "Run", "over", "all", "Tasks", "in", "all", "homeworks", "." ]
[ "\"\"\"Run over all Tasks in all homeworks.\"\"\"" ]
[ { "param": "self", "type": "\"Checker\"" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": "\"Checker\"", "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
6a282dac266526afcb7f6b79cbc4cc9b09467ec6
niosus/homework_checker
homework_checker/core/md_writer.py
[ "Apache-2.0" ]
Python
update
null
def update(self: "MdWriter", hw_results: Dict[str, HomeworkResultDict]): """Update the table of completion.""" for hw_name, hw_dict in sorted(hw_results.items()): hw_name = remove_number_from_name(hw_name) need_hw_name = True expired = False if EXPIRED_TAG...
Update the table of completion.
Update the table of completion.
[ "Update", "the", "table", "of", "completion", "." ]
def update(self: "MdWriter", hw_results: Dict[str, HomeworkResultDict]): for hw_name, hw_dict in sorted(hw_results.items()): hw_name = remove_number_from_name(hw_name) need_hw_name = True expired = False if EXPIRED_TAG in hw_dict: expired = True ...
[ "def", "update", "(", "self", ":", "\"MdWriter\"", ",", "hw_results", ":", "Dict", "[", "str", ",", "HomeworkResultDict", "]", ")", ":", "for", "hw_name", ",", "hw_dict", "in", "sorted", "(", "hw_results", ".", "items", "(", ")", ")", ":", "hw_name", "...
Update the table of completion.
[ "Update", "the", "table", "of", "completion", "." ]
[ "\"\"\"Update the table of completion.\"\"\"", "# Maybe there is a better way to handle this, but I don't", "# want to dig into this right now. We have added the", "# EXPIRED_TAG to this dict and need to ignore it here.", "# We only print homework name once." ]
[ { "param": "self", "type": "\"MdWriter\"" }, { "param": "hw_results", "type": "Dict[str, HomeworkResultDict]" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": "\"MdWriter\"", "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "hw_results", "type": "Dict[str, HomeworkResultDict]", "do...
6a282dac266526afcb7f6b79cbc4cc9b09467ec6
niosus/homework_checker
homework_checker/core/md_writer.py
[ "Apache-2.0" ]
Python
write_md_file
null
def write_md_file(self: "MdWriter", md_file_path: Path): """Write all the added content to the md file.""" md_file_content = "# Test results\n" md_file_content += self._md_table if self._errors: md_file_content += "\n# Encountered errors\n" md_file_content += self...
Write all the added content to the md file.
Write all the added content to the md file.
[ "Write", "all", "the", "added", "content", "to", "the", "md", "file", "." ]
def write_md_file(self: "MdWriter", md_file_path: Path): md_file_content = "# Test results\n" md_file_content += self._md_table if self._errors: md_file_content += "\n# Encountered errors\n" md_file_content += self._errors md_file_content += SEPARATOR md_f...
[ "def", "write_md_file", "(", "self", ":", "\"MdWriter\"", ",", "md_file_path", ":", "Path", ")", ":", "md_file_content", "=", "\"# Test results\\n\"", "md_file_content", "+=", "self", ".", "_md_table", "if", "self", ".", "_errors", ":", "md_file_content", "+=", ...
Write all the added content to the md file.
[ "Write", "all", "the", "added", "content", "to", "the", "md", "file", "." ]
[ "\"\"\"Write all the added content to the md file.\"\"\"" ]
[ { "param": "self", "type": "\"MdWriter\"" }, { "param": "md_file_path", "type": "Path" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": "\"MdWriter\"", "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "md_file_path", "type": "Path", "docstring": null, "...
6a282dac266526afcb7f6b79cbc4cc9b09467ec6
niosus/homework_checker
homework_checker/core/md_writer.py
[ "Apache-2.0" ]
Python
_add_error
<not_specific>
def _add_error( self: "MdWriter", hw_name: str, task_name: str, test_name: str, test_result: CmdResult, expired: bool, ): """Add a section of errors to the md file.""" if test_result.succeeded(): return if expired: self....
Add a section of errors to the md file.
Add a section of errors to the md file.
[ "Add", "a", "section", "of", "errors", "to", "the", "md", "file", "." ]
def _add_error( self: "MdWriter", hw_name: str, task_name: str, test_name: str, test_result: CmdResult, expired: bool, ): if test_result.succeeded(): return if expired: self._errors += EXPIRED_TEMPLATE.format(hw_name=hw_name) ...
[ "def", "_add_error", "(", "self", ":", "\"MdWriter\"", ",", "hw_name", ":", "str", ",", "task_name", ":", "str", ",", "test_name", ":", "str", ",", "test_result", ":", "CmdResult", ",", "expired", ":", "bool", ",", ")", ":", "if", "test_result", ".", "...
Add a section of errors to the md file.
[ "Add", "a", "section", "of", "errors", "to", "the", "md", "file", "." ]
[ "\"\"\"Add a section of errors to the md file.\"\"\"" ]
[ { "param": "self", "type": "\"MdWriter\"" }, { "param": "hw_name", "type": "str" }, { "param": "task_name", "type": "str" }, { "param": "test_name", "type": "str" }, { "param": "test_result", "type": "CmdResult" }, { "param": "expired", "type": "bo...
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": "\"MdWriter\"", "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "hw_name", "type": "str", "docstring": null, "docstr...
79cb5feaae56469411cf713b687f91b7e3939f5d
williwacker/django-qr-code
qr_code/qrcode/maker.py
[ "BSD-3-Clause" ]
Python
make_qr_code_image
<not_specific>
def make_qr_code_image(text, image_factory, qr_code_options=QRCodeOptions()): """ Generates an image object (from the qrcode library) representing the QR code for the given text. Any invalid argument is silently converted into the default value for that argument. """ valid_version = _get_valid_ver...
Generates an image object (from the qrcode library) representing the QR code for the given text. Any invalid argument is silently converted into the default value for that argument.
Generates an image object (from the qrcode library) representing the QR code for the given text. Any invalid argument is silently converted into the default value for that argument.
[ "Generates", "an", "image", "object", "(", "from", "the", "qrcode", "library", ")", "representing", "the", "QR", "code", "for", "the", "given", "text", ".", "Any", "invalid", "argument", "is", "silently", "converted", "into", "the", "default", "value", "for"...
def make_qr_code_image(text, image_factory, qr_code_options=QRCodeOptions()): valid_version = _get_valid_version_or_none(qr_code_options.version) valid_size = _get_valid_size_or_default(qr_code_options.size) valid_error_correction = _get_valid_error_correction_or_default(qr_code_options.error_correction) ...
[ "def", "make_qr_code_image", "(", "text", ",", "image_factory", ",", "qr_code_options", "=", "QRCodeOptions", "(", ")", ")", ":", "valid_version", "=", "_get_valid_version_or_none", "(", "qr_code_options", ".", "version", ")", "valid_size", "=", "_get_valid_size_or_de...
Generates an image object (from the qrcode library) representing the QR code for the given text.
[ "Generates", "an", "image", "object", "(", "from", "the", "qrcode", "library", ")", "representing", "the", "QR", "code", "for", "the", "given", "text", "." ]
[ "\"\"\"\n Generates an image object (from the qrcode library) representing the QR code for the given text.\n\n Any invalid argument is silently converted into the default value for that argument.\n \"\"\"" ]
[ { "param": "text", "type": null }, { "param": "image_factory", "type": null }, { "param": "qr_code_options", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "text", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "image_factory", "type": null, "docstring": null, "docstring_t...
79cb5feaae56469411cf713b687f91b7e3939f5d
williwacker/django-qr-code
qr_code/qrcode/maker.py
[ "BSD-3-Clause" ]
Python
make_embedded_qr_code
<not_specific>
def make_embedded_qr_code(text, qr_code_options=QRCodeOptions()): """ Generates a <svg> or <img> tag representing the QR code for the given text. This tag can be embedded into an HTML document. """ image_format = qr_code_options.image_format img = make_qr_code_image(text, SvgEmbeddedInHtmlImage ...
Generates a <svg> or <img> tag representing the QR code for the given text. This tag can be embedded into an HTML document.
Generates a or tag representing the QR code for the given text. This tag can be embedded into an HTML document.
[ "Generates", "a", "or", "tag", "representing", "the", "QR", "code", "for", "the", "given", "text", ".", "This", "tag", "can", "be", "embedded", "into", "an", "HTML", "document", "." ]
def make_embedded_qr_code(text, qr_code_options=QRCodeOptions()): image_format = qr_code_options.image_format img = make_qr_code_image(text, SvgEmbeddedInHtmlImage if image_format == SVG_FORMAT_NAME else PilImageOrFallback, qr_code_options=qr_code_options) stream = BytesIO() if image_format == SVG_FORMA...
[ "def", "make_embedded_qr_code", "(", "text", ",", "qr_code_options", "=", "QRCodeOptions", "(", ")", ")", ":", "image_format", "=", "qr_code_options", ".", "image_format", "img", "=", "make_qr_code_image", "(", "text", ",", "SvgEmbeddedInHtmlImage", "if", "image_for...
Generates a <svg> or <img> tag representing the QR code for the given text.
[ "Generates", "a", "<svg", ">", "or", "<img", ">", "tag", "representing", "the", "QR", "code", "for", "the", "given", "text", "." ]
[ "\"\"\"\n Generates a <svg> or <img> tag representing the QR code for the given text. This tag can be embedded into an\n HTML document.\n \"\"\"", "# html_fragment = '<img src=\"data:image/png;base64, %s\" alt=\"%s\">' % (str(base64.b64encode(stream.getvalue()), encoding='ascii'), escape(text))" ]
[ { "param": "text", "type": null }, { "param": "qr_code_options", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "text", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "qr_code_options", "type": null, "docstring": null, "docstring...
a4c956d5ea31af324d9d6a5d51f2b28c3bcd5c00
SriramPingali/Image-To-Text
utils.py
[ "MIT" ]
Python
encode
<not_specific>
def encode(self, text): """Support batch or single str. Args: text (str or list of str): texts to convert. Returns: torch.LongTensor [length_0 + length_1 + ... length_{n - 1}]: encoded texts. torch.LongTensor [n]: length of each text. """ le...
Support batch or single str. Args: text (str or list of str): texts to convert. Returns: torch.LongTensor [length_0 + length_1 + ... length_{n - 1}]: encoded texts. torch.LongTensor [n]: length of each text.
Support batch or single str.
[ "Support", "batch", "or", "single", "str", "." ]
def encode(self, text): length = [] result = [] for item in text: item = item.decode('utf-8','strict') length.append(len(item)) r = [] for char in item: index = self.dict[char] r.append(index) ...
[ "def", "encode", "(", "self", ",", "text", ")", ":", "length", "=", "[", "]", "result", "=", "[", "]", "for", "item", "in", "text", ":", "item", "=", "item", ".", "decode", "(", "'utf-8'", ",", "'strict'", ")", "length", ".", "append", "(", "len"...
Support batch or single str.
[ "Support", "batch", "or", "single", "str", "." ]
[ "\"\"\"Support batch or single str.\n\n Args:\n text (str or list of str): texts to convert.\n\n Returns:\n torch.LongTensor [length_0 + length_1 + ... length_{n - 1}]: encoded texts.\n torch.LongTensor [n]: length of each text.\n \"\"\"", "# result.append(ind...
[ { "param": "self", "type": null }, { "param": "text", "type": null } ]
{ "returns": [ { "docstring": "encoded texts.\ntorch.LongTensor [n]: length of each text.", "docstring_tokens": [ "encoded", "texts", ".", "torch", ".", "LongTensor", "[", "n", "]", ":", "length", "of", ...
a4c956d5ea31af324d9d6a5d51f2b28c3bcd5c00
SriramPingali/Image-To-Text
utils.py
[ "MIT" ]
Python
decode
<not_specific>
def decode(self, t, length, raw=False): """Decode encoded texts back into strs. Args: torch.LongTensor [length_0 + length_1 + ... length_{n - 1}]: encoded texts. torch.LongTensor [n]: length of each text. Raises: AssertionError: when the texts and its length...
Decode encoded texts back into strs. Args: torch.LongTensor [length_0 + length_1 + ... length_{n - 1}]: encoded texts. torch.LongTensor [n]: length of each text. Raises: AssertionError: when the texts and its length does not match. Returns: text...
Decode encoded texts back into strs.
[ "Decode", "encoded", "texts", "back", "into", "strs", "." ]
def decode(self, t, length, raw=False): if length.numel() == 1: length = length[0] assert t.numel() == length, "text with length: {} does not match declared length: {}".format(t.numel(), length) if raw: return ''.join([self.alphabet[i - 1] for i in t]) ...
[ "def", "decode", "(", "self", ",", "t", ",", "length", ",", "raw", "=", "False", ")", ":", "if", "length", ".", "numel", "(", ")", "==", "1", ":", "length", "=", "length", "[", "0", "]", "assert", "t", ".", "numel", "(", ")", "==", "length", ...
Decode encoded texts back into strs.
[ "Decode", "encoded", "texts", "back", "into", "strs", "." ]
[ "\"\"\"Decode encoded texts back into strs.\n\n Args:\n torch.LongTensor [length_0 + length_1 + ... length_{n - 1}]: encoded texts.\n torch.LongTensor [n]: length of each text.\n\n Raises:\n AssertionError: when the texts and its length does not match.\n\n Retur...
[ { "param": "self", "type": null }, { "param": "t", "type": null }, { "param": "length", "type": null }, { "param": "raw", "type": null } ]
{ "returns": [ { "docstring": "text (str or list of str): texts to convert.", "docstring_tokens": [ "text", "(", "str", "or", "list", "of", "str", ")", ":", "texts", "to", "convert", "." ], ...
314d7ac5c6fe5a1510384297827fec9d5191fb88
nala-cub/prost
src/baselines/unifiedqa.py
[ "Apache-2.0" ]
Python
prep_example_prost_gcp
<not_specific>
def prep_example_prost_gcp(example): """ Prepare PROST example for the T5 Colab Notebook """ template = '{ex_question} \\n (A) {A} (B) {B} (C) {C} (D) {D} \\n {context}' instance = { 'input': template.format_map(example), 'target': example[list('ABCD')[example['label']]], 'target_idx': example['labe...
Prepare PROST example for the T5 Colab Notebook
Prepare PROST example for the T5 Colab Notebook
[ "Prepare", "PROST", "example", "for", "the", "T5", "Colab", "Notebook" ]
def prep_example_prost_gcp(example): template = '{ex_question} \\n (A) {A} (B) {B} (C) {C} (D) {D} \\n {context}' instance = { 'input': template.format_map(example), 'target': example[list('ABCD')[example['label']]], 'target_idx': example['label'], **example} return instance
[ "def", "prep_example_prost_gcp", "(", "example", ")", ":", "template", "=", "'{ex_question} \\\\n (A) {A} (B) {B} (C) {C} (D) {D} \\\\n {context}'", "instance", "=", "{", "'input'", ":", "template", ".", "format_map", "(", "example", ")", ",", "'target'", ":", "example"...
Prepare PROST example for the T5 Colab Notebook
[ "Prepare", "PROST", "example", "for", "the", "T5", "Colab", "Notebook" ]
[ "\"\"\" Prepare PROST example for the T5 Colab Notebook \"\"\"" ]
[ { "param": "example", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "example", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
314d7ac5c6fe5a1510384297827fec9d5191fb88
nala-cub/prost
src/baselines/unifiedqa.py
[ "Apache-2.0" ]
Python
normalize_answer
str
def normalize_answer(s: str) -> str: """Normalize UnifiedQA Generated Text [1]. """ import re import string def remove_articles(text): return re.sub(r'\b(a|an|the)\b', ' ', text) def white_space_fix(text): return ' '.join(text.split()) # Temporary fix for bug where {}^<\` characters roundtrip int...
Normalize UnifiedQA Generated Text [1].
Normalize UnifiedQA Generated Text [1].
[ "Normalize", "UnifiedQA", "Generated", "Text", "[", "1", "]", "." ]
def normalize_answer(s: str) -> str: import re import string def remove_articles(text): return re.sub(r'\b(a|an|the)\b', ' ', text) def white_space_fix(text): return ' '.join(text.split()) def fix_buggy_characters(str): return re.sub("[{}^\\\\`\u2047<]", " ", str) def remove_punc(text): excl...
[ "def", "normalize_answer", "(", "s", ":", "str", ")", "->", "str", ":", "import", "re", "import", "string", "def", "remove_articles", "(", "text", ")", ":", "return", "re", ".", "sub", "(", "r'\\b(a|an|the)\\b'", ",", "' '", ",", "text", ")", "def", "w...
Normalize UnifiedQA Generated Text [1].
[ "Normalize", "UnifiedQA", "Generated", "Text", "[", "1", "]", "." ]
[ "\"\"\"Normalize UnifiedQA Generated Text [1]. \"\"\"", "# Temporary fix for bug where {}^<\\` characters roundtrip into \\u2047 (??) character" ]
[ { "param": "s", "type": "str" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "s", "type": "str", "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
314d7ac5c6fe5a1510384297827fec9d5191fb88
nala-cub/prost
src/baselines/unifiedqa.py
[ "Apache-2.0" ]
Python
prep_example_piqa
<not_specific>
def prep_example_piqa(example, index): """ Prepare PIQA example for scoring preds from the T5 notebook """ match = re.match(r'^(.+) \\n \(A\) (.+) \(B\) (.+)$', example['input']) instance = {} instance['sol1'] = match[2].strip().lower() instance['sol2'] = match[3].strip().lower() example['target'] = examp...
Prepare PIQA example for scoring preds from the T5 notebook
Prepare PIQA example for scoring preds from the T5 notebook
[ "Prepare", "PIQA", "example", "for", "scoring", "preds", "from", "the", "T5", "notebook" ]
def prep_example_piqa(example, index): match = re.match(r'^(.+) \\n \(A\) (.+) \(B\) (.+)$', example['input']) instance = {} instance['sol1'] = match[2].strip().lower() instance['sol2'] = match[3].strip().lower() example['target'] = example['target'].strip().lower() instance['example_idx'] = index instanc...
[ "def", "prep_example_piqa", "(", "example", ",", "index", ")", ":", "match", "=", "re", ".", "match", "(", "r'^(.+) \\\\n \\(A\\) (.+) \\(B\\) (.+)$'", ",", "example", "[", "'input'", "]", ")", "instance", "=", "{", "}", "instance", "[", "'sol1'", "]", "=", ...
Prepare PIQA example for scoring preds from the T5 notebook
[ "Prepare", "PIQA", "example", "for", "scoring", "preds", "from", "the", "T5", "notebook" ]
[ "\"\"\" Prepare PIQA example for scoring preds from the T5 notebook \"\"\"" ]
[ { "param": "example", "type": null }, { "param": "index", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "example", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "index", "type": null, "docstring": null, "docstring_tokens...
19e27ccfa1d43321c3ed4d96a1b9ccfc59bb1b88
nala-cub/prost
src/baselines/results.py
[ "Apache-2.0" ]
Python
pivoted_to_longtex
<not_specific>
def pivoted_to_longtex(df, bold=None, dest=None): """ Takes in a pivoted DF and produces a LaTeX Table Each row should be a model and each column a Task. """ dfl = df.copy(deep=True) header = r'\begin{tabular}{rl' + 'c' * (len(dfl.columns) + 2) + '}\n' header += r'\toprule' + '\n' # column heade...
Takes in a pivoted DF and produces a LaTeX Table Each row should be a model and each column a Task.
Takes in a pivoted DF and produces a LaTeX Table Each row should be a model and each column a Task.
[ "Takes", "in", "a", "pivoted", "DF", "and", "produces", "a", "LaTeX", "Table", "Each", "row", "should", "be", "a", "model", "and", "each", "column", "a", "Task", "." ]
def pivoted_to_longtex(df, bold=None, dest=None): dfl = df.copy(deep=True) header = r'\begin{tabular}{rl' + 'c' * (len(dfl.columns) + 2) + '}\n' header += r'\toprule' + '\n' dfl = dfl.reindex(sort_columns(dfl.index)) colmap = {c: c.capitalize() for c in dfl.columns} colmap['circumference'] = 'Circum.' dfl...
[ "def", "pivoted_to_longtex", "(", "df", ",", "bold", "=", "None", ",", "dest", "=", "None", ")", ":", "dfl", "=", "df", ".", "copy", "(", "deep", "=", "True", ")", "header", "=", "r'\\begin{tabular}{rl'", "+", "'c'", "*", "(", "len", "(", "dfl", "....
Takes in a pivoted DF and produces a LaTeX Table Each row should be a model and each column a Task.
[ "Takes", "in", "a", "pivoted", "DF", "and", "produces", "a", "LaTeX", "Table", "Each", "row", "should", "be", "a", "model", "and", "each", "column", "a", "Task", "." ]
[ "\"\"\" Takes in a pivoted DF and produces a LaTeX Table\n Each row should be a model and each column a Task.\n \"\"\"", "# column headers", "# make and order tasks", "#cols =", "# print(dfl.head)", "# dfl = dfl[sort_columns(dfl.index)]", "# dfl = dfl.reindex(sort_columns(dfl.index))", "# p...
[ { "param": "df", "type": null }, { "param": "bold", "type": null }, { "param": "dest", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "df", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "bold", "type": null, "docstring": null, "docstring_tokens": [],...
19e27ccfa1d43321c3ed4d96a1b9ccfc59bb1b88
nala-cub/prost
src/baselines/results.py
[ "Apache-2.0" ]
Python
process_preds_base
<not_specific>
def process_preds_base(df, info): """ Processes all Predictions into Longform DF with Dataset Examples + Correct Tags. """ dfp = to_wide_rankings(df) dfp = dfp[[('example_idx', ''), ('model_name', ''), ('pred_idx', 'final')]] dfp.columns = dfp.columns.droplevel(1) # add unifiedqa uqa_df = df[df['model_na...
Processes all Predictions into Longform DF with Dataset Examples + Correct Tags.
Processes all Predictions into Longform DF with Dataset Examples + Correct Tags.
[ "Processes", "all", "Predictions", "into", "Longform", "DF", "with", "Dataset", "Examples", "+", "Correct", "Tags", "." ]
def process_preds_base(df, info): dfp = to_wide_rankings(df) dfp = dfp[[('example_idx', ''), ('model_name', ''), ('pred_idx', 'final')]] dfp.columns = dfp.columns.droplevel(1) uqa_df = df[df['model_name'].apply(lambda x: x.startswith('allenai'))] if len(uqa_df.index) > 0: uqa_df = uqa_df[['example_idx', '...
[ "def", "process_preds_base", "(", "df", ",", "info", ")", ":", "dfp", "=", "to_wide_rankings", "(", "df", ")", "dfp", "=", "dfp", "[", "[", "(", "'example_idx'", ",", "''", ")", ",", "(", "'model_name'", ",", "''", ")", ",", "(", "'pred_idx'", ",", ...
Processes all Predictions into Longform DF with Dataset Examples + Correct Tags.
[ "Processes", "all", "Predictions", "into", "Longform", "DF", "with", "Dataset", "Examples", "+", "Correct", "Tags", "." ]
[ "\"\"\" Processes all Predictions into Longform DF with Dataset Examples + Correct Tags.\n\n \"\"\"", "# add unifiedqa", "# uqa_df = uqa_df[['example_idx', 'model_name', 'pred_idx', 'generated']]", "# add info", "# get correct (per example)", "# get groupings" ]
[ { "param": "df", "type": null }, { "param": "info", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "df", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "info", "type": null, "docstring": null, "docstring_tokens": [],...
e19108ea6f5b1b380f9a1577730a8bdd0783385d
nala-cub/prost
src/baselines/input_pipeline.py
[ "Apache-2.0" ]
Python
create_examples_albert
<not_specific>
def create_examples_albert(examples, tokenizer): """Create examples for Albert. Albert uses whole-word masking, so [MASK] should be replaced with the number of tokens that the option has. This version only accounts for SINGLE token masking, see create_examples_albert_wwm for details on the other approach....
Create examples for Albert. Albert uses whole-word masking, so [MASK] should be replaced with the number of tokens that the option has. This version only accounts for SINGLE token masking, see create_examples_albert_wwm for details on the other approach.
Create examples for Albert. Albert uses whole-word masking, so [MASK] should be replaced with the number of tokens that the option has. This version only accounts for SINGLE token masking, see create_examples_albert_wwm for details on the other approach.
[ "Create", "examples", "for", "Albert", ".", "Albert", "uses", "whole", "-", "word", "masking", "so", "[", "MASK", "]", "should", "be", "replaced", "with", "the", "number", "of", "tokens", "that", "the", "option", "has", ".", "This", "version", "only", "a...
def create_examples_albert(examples, tokenizer): example = T.valmap(T.get(0), examples) option_encodings = _get_option_encodings(example, tokenizer, True) option_input_ids = [o.input_ids[0] for o in option_encodings] example['question'] = re.sub(r'( \[MASK\])|(\[MASK\])', tokenizer.mask_token, ...
[ "def", "create_examples_albert", "(", "examples", ",", "tokenizer", ")", ":", "example", "=", "T", ".", "valmap", "(", "T", ".", "get", "(", "0", ")", ",", "examples", ")", "option_encodings", "=", "_get_option_encodings", "(", "example", ",", "tokenizer", ...
Create examples for Albert.
[ "Create", "examples", "for", "Albert", "." ]
[ "\"\"\"Create examples for Albert.\n Albert uses whole-word masking, so [MASK] should be replaced with the\n number of tokens that the option has. This version only accounts for SINGLE token\n masking, see create_examples_albert_wwm for details on the other approach.\n\n \"\"\"", "# substitute mask wi...
[ { "param": "examples", "type": null }, { "param": "tokenizer", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "examples", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "tokenizer", "type": null, "docstring": null, "docstring_t...
00aabec21d9e6f2a9a6ac8695441981020a528f2
nala-cub/prost
src/prost/prost.py
[ "Apache-2.0" ]
Python
build_examples_from_config
<not_specific>
def build_examples_from_config(config, variables, product=True, remove_duplicates=True): """Construct Test cases for a task. Args: config: raw dictionary configurary read in from scenario yml file. variables: global and scenario lexicons. Returns: Formatted examples for...
Construct Test cases for a task. Args: config: raw dictionary configurary read in from scenario yml file. variables: global and scenario lexicons. Returns: Formatted examples for the provided template
Construct Test cases for a task.
[ "Construct", "Test", "cases", "for", "a", "task", "." ]
def build_examples_from_config(config, variables, product=True, remove_duplicates=True): expect_fn = globals()[config.pop('expect_fn')] enum_variables = T.itemmap(lambda x: make_enum_vars(*x), variables) logging.debug('variables: %s, ev: %s', variables, enum_variables) template = ...
[ "def", "build_examples_from_config", "(", "config", ",", "variables", ",", "product", "=", "True", ",", "remove_duplicates", "=", "True", ")", ":", "expect_fn", "=", "globals", "(", ")", "[", "config", ".", "pop", "(", "'expect_fn'", ")", "]", "enum_variable...
Construct Test cases for a task.
[ "Construct", "Test", "cases", "for", "a", "task", "." ]
[ "\"\"\"Construct Test cases for a task.\n\n Args:\n config: raw dictionary configurary read in from scenario yml file.\n variables: global and scenario lexicons.\n Returns:\n Formatted examples for the provided template\n \"\"\"", "# get answer key function, prep evs", "# find keys for the template"...
[ { "param": "config", "type": null }, { "param": "variables", "type": null }, { "param": "product", "type": null }, { "param": "remove_duplicates", "type": null } ]
{ "returns": [ { "docstring": "Formatted examples for the provided template", "docstring_tokens": [ "Formatted", "examples", "for", "the", "provided", "template" ], "type": null } ], "raises": [], "params": [ { "identifier...
00aabec21d9e6f2a9a6ac8695441981020a528f2
nala-cub/prost
src/prost/prost.py
[ "Apache-2.0" ]
Python
preprocess_meta
<not_specific>
def preprocess_meta(fn: Callable): """ Preprocess meta dicts -> IntEnum objects""" @wraps(fn) @T.curry def _preprocess_meta(ex, meta, ev, **kwargs): # enumerate meta meta = enum_meta(meta, ev) # get options options = [] for i, k in enumerate('ABCD'): option_meta = T.valfilter(lambda x...
Preprocess meta dicts -> IntEnum objects
Preprocess meta dicts -> IntEnum objects
[ "Preprocess", "meta", "dicts", "-", ">", "IntEnum", "objects" ]
def preprocess_meta(fn: Callable): @wraps(fn) @T.curry def _preprocess_meta(ex, meta, ev, **kwargs): meta = enum_meta(meta, ev) options = [] for i, k in enumerate('ABCD'): option_meta = T.valfilter(lambda x: x['text'] == ex[k], meta) option_meta = list(option_meta.values()) if len(op...
[ "def", "preprocess_meta", "(", "fn", ":", "Callable", ")", ":", "@", "wraps", "(", "fn", ")", "@", "T", ".", "curry", "def", "_preprocess_meta", "(", "ex", ",", "meta", ",", "ev", ",", "**", "kwargs", ")", ":", "meta", "=", "enum_meta", "(", "meta"...
Preprocess meta dicts -> IntEnum objects
[ "Preprocess", "meta", "dicts", "-", ">", "IntEnum", "objects" ]
[ "\"\"\" Preprocess meta dicts -> IntEnum objects\"\"\"", "# enumerate meta", "# get options", "# get the enum for that obj" ]
[ { "param": "fn", "type": "Callable" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "fn", "type": "Callable", "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
00aabec21d9e6f2a9a6ac8695441981020a528f2
nala-cub/prost
src/prost/prost.py
[ "Apache-2.0" ]
Python
find_all_keys
set[str]
def find_all_keys(obj) -> set[str]: """Finds all tag keys in object (with options) """ return T.pipe(obj, tree.flatten, set, T.mapcat(lambda x: string.Formatter().parse(x)), T.filter(T.get(1)), T.map(lambda x: x[1] if not x[2] else '%s:%s' % (x[1], x[2])), ...
Finds all tag keys in object (with options)
Finds all tag keys in object (with options)
[ "Finds", "all", "tag", "keys", "in", "object", "(", "with", "options", ")" ]
def find_all_keys(obj) -> set[str]: return T.pipe(obj, tree.flatten, set, T.mapcat(lambda x: string.Formatter().parse(x)), T.filter(T.get(1)), T.map(lambda x: x[1] if not x[2] else '%s:%s' % (x[1], x[2])), list, set)
[ "def", "find_all_keys", "(", "obj", ")", "->", "set", "[", "str", "]", ":", "return", "T", ".", "pipe", "(", "obj", ",", "tree", ".", "flatten", ",", "set", ",", "T", ".", "mapcat", "(", "lambda", "x", ":", "string", ".", "Formatter", "(", ")", ...
Finds all tag keys in object (with options)
[ "Finds", "all", "tag", "keys", "in", "object", "(", "with", "options", ")" ]
[ "\"\"\"Finds all tag keys in object (with options) \"\"\"" ]
[ { "param": "obj", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "obj", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
00aabec21d9e6f2a9a6ac8695441981020a528f2
nala-cub/prost
src/prost/prost.py
[ "Apache-2.0" ]
Python
recursive_format
TemplateObj
def recursive_format(obj: TemplateObj, mapping: Dict, ignore_missing: bool = False) -> TemplateObj: """Formats all strings within an object, using mapping Args: obj: Object (leaves must be strings, regardless of type) mapping: format dictionary, maps keys to values ignore_missi...
Formats all strings within an object, using mapping Args: obj: Object (leaves must be strings, regardless of type) mapping: format dictionary, maps keys to values ignore_missing: If True, will not throw exception if a string contains a tag not present in mapping, and will keep the tag instead...
Formats all strings within an object, using mapping
[ "Formats", "all", "strings", "within", "an", "object", "using", "mapping" ]
def recursive_format(obj: TemplateObj, mapping: Dict, ignore_missing: bool = False) -> TemplateObj: def formatfn(x): fmt = SafeFormatter() formatz = (lambda x, m: x.format(**m) if not ignore_missing else fmt.format(x, **m)) options = re.compile(r'{([^}]+):([^}]+)}') ...
[ "def", "recursive_format", "(", "obj", ":", "TemplateObj", ",", "mapping", ":", "Dict", ",", "ignore_missing", ":", "bool", "=", "False", ")", "->", "TemplateObj", ":", "def", "formatfn", "(", "x", ")", ":", "fmt", "=", "SafeFormatter", "(", ")", "format...
Formats all strings within an object, using mapping
[ "Formats", "all", "strings", "within", "an", "object", "using", "mapping" ]
[ "\"\"\"Formats all strings within an object, using mapping\n \n Args:\n obj: Object (leaves must be strings, regardless of type)\n mapping: format dictionary, maps keys to values\n ignore_missing: If True, will not throw exception if a string contains a \n tag not present in mapping, and will kee...
[ { "param": "obj", "type": "TemplateObj" }, { "param": "mapping", "type": "Dict" }, { "param": "ignore_missing", "type": "bool" } ]
{ "returns": [ { "docstring": "Object of the same type as obj, with strings formatted (tags replaced\nby their value)", "docstring_tokens": [ "Object", "of", "the", "same", "type", "as", "obj", "with", "strings", "formatte...
12f692b8b2f9ec20ed743a31c3a5adca9f6bf0cd
JoySkipper/GBT_RFI_pipeline
GBT_RFI_pipeline/process_new_RFI_files.py
[ "MIT" ]
Python
find_parameters_to_process_file
<not_specific>
def find_parameters_to_process_file(RFI_files_to_be_processed: list,path_to_current_RFI_files): """ param: RFI_files_to_be_processed: List of all RFI files that need to be processed by the GBTIDL processing script param: path_to_current_RFI_files: String containing the path to all current RFI files, in whic...
param: RFI_files_to_be_processed: List of all RFI files that need to be processed by the GBTIDL processing script param: path_to_current_RFI_files: String containing the path to all current RFI files, in which the files to be processed are contained return: data_to_process; which is a list of lists contain...
List of all RFI files that need to be processed by the GBTIDL processing script param: path_to_current_RFI_files: String containing the path to all current RFI files, in which the files to be processed are contained return: data_to_process; which is a list of lists containing each file with the information needed to ru...
[ "List", "of", "all", "RFI", "files", "that", "need", "to", "be", "processed", "by", "the", "GBTIDL", "processing", "script", "param", ":", "path_to_current_RFI_files", ":", "String", "containing", "the", "path", "to", "all", "current", "RFI", "files", "in", ...
def find_parameters_to_process_file(RFI_files_to_be_processed: list,path_to_current_RFI_files): data_to_process = [] for file_to_be_processed in RFI_files_to_be_processed: try: _, line_to_start_reader = read_header(file_to_be_processed, path_to_current_RFI_files) except FileNotFoundE...
[ "def", "find_parameters_to_process_file", "(", "RFI_files_to_be_processed", ":", "list", ",", "path_to_current_RFI_files", ")", ":", "data_to_process", "=", "[", "]", "for", "file_to_be_processed", "in", "RFI_files_to_be_processed", ":", "try", ":", "_", ",", "line_to_s...
param: RFI_files_to_be_processed: List of all RFI files that need to be processed by the GBTIDL processing script param: path_to_current_RFI_files: String containing the path to all current RFI files, in which the files to be processed are contained return: data_to_process; which is a list of lists containing each file...
[ "param", ":", "RFI_files_to_be_processed", ":", "List", "of", "all", "RFI", "files", "that", "need", "to", "be", "processed", "by", "the", "GBTIDL", "processing", "script", "param", ":", "path_to_current_RFI_files", ":", "String", "containing", "the", "path", "t...
[ "\"\"\"\n param: RFI_files_to_be_processed: List of all RFI files that need to be processed by the GBTIDL processing script\n param: path_to_current_RFI_files: String containing the path to all current RFI files, in which the files to be processed are contained\n return: data_to_process; which is a list of...
[ { "param": "RFI_files_to_be_processed", "type": "list" }, { "param": "path_to_current_RFI_files", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "RFI_files_to_be_processed", "type": "list", "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "path_to_current_RFI_files", "type": null, "d...
12f692b8b2f9ec20ed743a31c3a5adca9f6bf0cd
JoySkipper/GBT_RFI_pipeline
GBT_RFI_pipeline/process_new_RFI_files.py
[ "MIT" ]
Python
analyze_file
null
def analyze_file(file_to_process,output_directory): """ param: file_to_process:: if the data has passed all checks up to this point, it is a dictionary containing metadata needed to process the RFI file. """ if file_to_process['list_of_scans'] == []: raise(EmptyScans) # The parameters for ru...
param: file_to_process:: if the data has passed all checks up to this point, it is a dictionary containing metadata needed to process the RFI file.
: if the data has passed all checks up to this point, it is a dictionary containing metadata needed to process the RFI file.
[ ":", "if", "the", "data", "has", "passed", "all", "checks", "up", "to", "this", "point", "it", "is", "a", "dictionary", "containing", "metadata", "needed", "to", "process", "the", "RFI", "file", "." ]
def analyze_file(file_to_process,output_directory): if file_to_process['list_of_scans'] == []: raise(EmptyScans) path = str(pathlib.Path(__file__).parent.absolute())+'/' temp_path = tempfile.gettempdir()+'/' temp_file = open(temp_path+"temp_file.pro","w+") temp_file.write('.compile '+path+'s...
[ "def", "analyze_file", "(", "file_to_process", ",", "output_directory", ")", ":", "if", "file_to_process", "[", "'list_of_scans'", "]", "==", "[", "]", ":", "raise", "(", "EmptyScans", ")", "path", "=", "str", "(", "pathlib", ".", "Path", "(", "__file__", ...
param: file_to_process:: if the data has passed all checks up to this point, it is a dictionary containing metadata needed to process the RFI file.
[ "param", ":", "file_to_process", "::", "if", "the", "data", "has", "passed", "all", "checks", "up", "to", "this", "point", "it", "is", "a", "dictionary", "containing", "metadata", "needed", "to", "process", "the", "RFI", "file", "." ]
[ "\"\"\"\n param: file_to_process:: if the data has passed all checks up to this point, it is a dictionary containing metadata needed to process the RFI file.\n \"\"\"", "# The parameters for running the process are different if the receiver is ka (26_40) so it needs to be called separately", "# Unfortunat...
[ { "param": "file_to_process", "type": null }, { "param": "output_directory", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "file_to_process", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "output_directory", "type": null, "docstring": null, ...
0e4f69c90aa6d102727975337d04cb852845e341
ajyong/CMPUT404-assignment-websockets
sockets.py
[ "Apache-2.0" ]
Python
read_ws
<not_specific>
def read_ws(ws,client): '''A greenlet function that reads from the websocket and updates the world''' try: while True: msg = ws.receive() # print "WS RECV: %s" % msg if (msg is not None): packet = json.loads(msg) # print "Packet: %s" % ...
A greenlet function that reads from the websocket and updates the world
A greenlet function that reads from the websocket and updates the world
[ "A", "greenlet", "function", "that", "reads", "from", "the", "websocket", "and", "updates", "the", "world" ]
def read_ws(ws,client): try: while True: msg = ws.receive() if (msg is not None): packet = json.loads(msg) for name, data in packet.iteritems(): entity = myWorld.get(name) for k, v in data.iteritems(): ...
[ "def", "read_ws", "(", "ws", ",", "client", ")", ":", "try", ":", "while", "True", ":", "msg", "=", "ws", ".", "receive", "(", ")", "if", "(", "msg", "is", "not", "None", ")", ":", "packet", "=", "json", ".", "loads", "(", "msg", ")", "for", ...
A greenlet function that reads from the websocket and updates the world
[ "A", "greenlet", "function", "that", "reads", "from", "the", "websocket", "and", "updates", "the", "world" ]
[ "'''A greenlet function that reads from the websocket and updates the world'''", "# print \"WS RECV: %s\" % msg", "# print \"Packet: %s\" % packet", "# Do it this way so we don't call the listener until", "# all KV pairs have been updated" ]
[ { "param": "ws", "type": null }, { "param": "client", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "ws", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "client", "type": null, "docstring": null, "docstring_tokens": [...
0e4f69c90aa6d102727975337d04cb852845e341
ajyong/CMPUT404-assignment-websockets
sockets.py
[ "Apache-2.0" ]
Python
subscribe_socket
null
def subscribe_socket(ws): '''Fufill the websocket URL of /subscribe, every update notify the websocket and read updates from the websocket ''' # print "A client has subscribed." client = Client() clients.append(client) # Give the new client the current world data client.put(json.dumps(my...
Fufill the websocket URL of /subscribe, every update notify the websocket and read updates from the websocket
Fufill the websocket URL of /subscribe, every update notify the websocket and read updates from the websocket
[ "Fufill", "the", "websocket", "URL", "of", "/", "subscribe", "every", "update", "notify", "the", "websocket", "and", "read", "updates", "from", "the", "websocket" ]
def subscribe_socket(ws): client = Client() clients.append(client) client.put(json.dumps(myWorld.world())); g = gevent.spawn( read_ws, ws, client ) try: while True: msg = client.get() ws.send(msg) except Exception as e: print "WS Error: %s" % e finally...
[ "def", "subscribe_socket", "(", "ws", ")", ":", "client", "=", "Client", "(", ")", "clients", ".", "append", "(", "client", ")", "client", ".", "put", "(", "json", ".", "dumps", "(", "myWorld", ".", "world", "(", ")", ")", ")", ";", "g", "=", "ge...
Fufill the websocket URL of /subscribe, every update notify the websocket and read updates from the websocket
[ "Fufill", "the", "websocket", "URL", "of", "/", "subscribe", "every", "update", "notify", "the", "websocket", "and", "read", "updates", "from", "the", "websocket" ]
[ "'''Fufill the websocket URL of /subscribe, every update notify the\n websocket and read updates from the websocket '''", "# print \"A client has subscribed.\"", "# Give the new client the current world data", "# Block here until we get something from the client's queue", "# print \"Got a message:\\n%...
[ { "param": "ws", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "ws", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
0e4f69c90aa6d102727975337d04cb852845e341
ajyong/CMPUT404-assignment-websockets
sockets.py
[ "Apache-2.0" ]
Python
update
<not_specific>
def update(entity): '''update the entities via this interface''' data = flask_post_json(request) for key, value in data.iteritems(): myWorld.update(entity, key, value); return make_json_response(myWorld.get(entity))
update the entities via this interface
update the entities via this interface
[ "update", "the", "entities", "via", "this", "interface" ]
def update(entity): data = flask_post_json(request) for key, value in data.iteritems(): myWorld.update(entity, key, value); return make_json_response(myWorld.get(entity))
[ "def", "update", "(", "entity", ")", ":", "data", "=", "flask_post_json", "(", "request", ")", "for", "key", ",", "value", "in", "data", ".", "iteritems", "(", ")", ":", "myWorld", ".", "update", "(", "entity", ",", "key", ",", "value", ")", ";", "...
update the entities via this interface
[ "update", "the", "entities", "via", "this", "interface" ]
[ "'''update the entities via this interface'''" ]
[ { "param": "entity", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "entity", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
6c5986a7ab164a554e0a20a8fc700446685830fb
ShobhitMaheshwari/sign-language1
feature.py
[ "MIT" ]
Python
features_2D_predict_generator
<not_specific>
def features_2D_predict_generator(sFrameBaseDir:str, sFeatureBaseDir:str, keModel:keras.Model, nFramesNorm:int = 40): """ Used by the MobileNet-LSTM NN architecture. The (video) frames (2-dimensional) in sFrameBaseDir are fed into keModel (eg MobileNet without top layers) and the resulting features...
Used by the MobileNet-LSTM NN architecture. The (video) frames (2-dimensional) in sFrameBaseDir are fed into keModel (eg MobileNet without top layers) and the resulting features are save to sFeatureBaseDir.
Used by the MobileNet-LSTM NN architecture. The (video) frames (2-dimensional) in sFrameBaseDir are fed into keModel and the resulting features are save to sFeatureBaseDir.
[ "Used", "by", "the", "MobileNet", "-", "LSTM", "NN", "architecture", ".", "The", "(", "video", ")", "frames", "(", "2", "-", "dimensional", ")", "in", "sFrameBaseDir", "are", "fed", "into", "keModel", "and", "the", "resulting", "features", "are", "save", ...
def features_2D_predict_generator(sFrameBaseDir:str, sFeatureBaseDir:str, keModel:keras.Model, nFramesNorm:int = 40): _, h, w, c = keModel.input_shape genFrames = FramesGenerator(sFrameBaseDir, 1, nFramesNorm, h, w, c, liClassesFull = None, bShuffle=False) print("Predict features with %s ... "...
[ "def", "features_2D_predict_generator", "(", "sFrameBaseDir", ":", "str", ",", "sFeatureBaseDir", ":", "str", ",", "keModel", ":", "keras", ".", "Model", ",", "nFramesNorm", ":", "int", "=", "40", ")", ":", "_", ",", "h", ",", "w", ",", "c", "=", "keMo...
Used by the MobileNet-LSTM NN architecture.
[ "Used", "by", "the", "MobileNet", "-", "LSTM", "NN", "architecture", "." ]
[ "\"\"\"\n Used by the MobileNet-LSTM NN architecture.\n The (video) frames (2-dimensional) in sFrameBaseDir are fed into keModel (eg MobileNet without top layers)\n and the resulting features are save to sFeatureBaseDir.\n \"\"\"", "# do not (partially) overwrite existing feature directory", "#if os...
[ { "param": "sFrameBaseDir", "type": "str" }, { "param": "sFeatureBaseDir", "type": "str" }, { "param": "keModel", "type": "keras.Model" }, { "param": "nFramesNorm", "type": "int" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "sFrameBaseDir", "type": "str", "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "sFeatureBaseDir", "type": "str", "docstring": null, ...
6c5986a7ab164a554e0a20a8fc700446685830fb
ShobhitMaheshwari/sign-language1
feature.py
[ "MIT" ]
Python
features_3D_predict_generator
<not_specific>
def features_3D_predict_generator(sFrameBaseDir:str, sFeatureBaseDir:str, keModel:keras.Model, nBatchSize:int = 16): """ Used by I3D-top-only model. The videos (frames) are fed into keModel (=I3D without top layers) and resulting features are saved to disc. (Later these features are used to tr...
Used by I3D-top-only model. The videos (frames) are fed into keModel (=I3D without top layers) and resulting features are saved to disc. (Later these features are used to train a small model containing only the adjusted I3D top layers.)
Used by I3D-top-only model. The videos (frames) are fed into keModel (=I3D without top layers) and resulting features are saved to disc. (Later these features are used to train a small model containing only the adjusted I3D top layers.)
[ "Used", "by", "I3D", "-", "top", "-", "only", "model", ".", "The", "videos", "(", "frames", ")", "are", "fed", "into", "keModel", "(", "=", "I3D", "without", "top", "layers", ")", "and", "resulting", "features", "are", "saved", "to", "disc", ".", "("...
def features_3D_predict_generator(sFrameBaseDir:str, sFeatureBaseDir:str, keModel:keras.Model, nBatchSize:int = 16): _, nFramesModel, h, w, c = keModel.input_shape genFrames = FramesGenerator(sFrameBaseDir, nBatchSize, nFramesModel, h, w, c, liClassesFull = None, bShuffle=False) print("Predict...
[ "def", "features_3D_predict_generator", "(", "sFrameBaseDir", ":", "str", ",", "sFeatureBaseDir", ":", "str", ",", "keModel", ":", "keras", ".", "Model", ",", "nBatchSize", ":", "int", "=", "16", ")", ":", "_", ",", "nFramesModel", ",", "h", ",", "w", ",...
Used by I3D-top-only model.
[ "Used", "by", "I3D", "-", "top", "-", "only", "model", "." ]
[ "\"\"\"\n Used by I3D-top-only model.\n The videos (frames) are fed into keModel (=I3D without top layers) and\n resulting features are saved to disc. \n (Later these features are used to train a small model containing \n only the adjusted I3D top layers.)\n \"\"\"", "# do not (partially) overwr...
[ { "param": "sFrameBaseDir", "type": "str" }, { "param": "sFeatureBaseDir", "type": "str" }, { "param": "keModel", "type": "keras.Model" }, { "param": "nBatchSize", "type": "int" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "sFrameBaseDir", "type": "str", "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "sFeatureBaseDir", "type": "str", "docstring": null, ...
ac46ee13662eee8bc8b3ddf0817779cf1502dc49
ShobhitMaheshwari/sign-language1
prepare_chalearn.py
[ "MIT" ]
Python
unzip_sort_videos
<not_specific>
def unzip_sort_videos(sVideoDir, sZipFile, sListFile): """ Unzip videos use Label information defined in sListFile to move videos into folders=labels """ print("Unzipping and sorting ChaLearn videos from %s into %s" % (sZipFile, sVideoDir)) # save current directory sCurrentDir = os.getcwd() ...
Unzip videos use Label information defined in sListFile to move videos into folders=labels
Unzip videos use Label information defined in sListFile to move videos into folders=labels
[ "Unzip", "videos", "use", "Label", "information", "defined", "in", "sListFile", "to", "move", "videos", "into", "folders", "=", "labels" ]
def unzip_sort_videos(sVideoDir, sZipFile, sListFile): print("Unzipping and sorting ChaLearn videos from %s into %s" % (sZipFile, sVideoDir)) sCurrentDir = os.getcwd() sTmpDir = sVideoDir + "/tmp" print("Unzipping videos to {} ...".format(sTmpDir)) if os.path.exists(sTmpDir): raise ValueError("Folde...
[ "def", "unzip_sort_videos", "(", "sVideoDir", ",", "sZipFile", ",", "sListFile", ")", ":", "print", "(", "\"Unzipping and sorting ChaLearn videos from %s into %s\"", "%", "(", "sZipFile", ",", "sVideoDir", ")", ")", "sCurrentDir", "=", "os", ".", "getcwd", "(", ")...
Unzip videos use Label information defined in sListFile to move videos into folders=labels
[ "Unzip", "videos", "use", "Label", "information", "defined", "in", "sListFile", "to", "move", "videos", "into", "folders", "=", "labels" ]
[ "\"\"\" Unzip videos use Label information defined in sListFile \n to move videos into folders=labels\n \"\"\"", "# save current directory", "# unzip videos to tmp directory ", "# read list of videos with labels ", "# assume sVideoPath = \"train/001/M_00023.avi\" and extract folders", "# check ta...
[ { "param": "sVideoDir", "type": null }, { "param": "sZipFile", "type": null }, { "param": "sListFile", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "sVideoDir", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "sZipFile", "type": null, "docstring": null, "docstring_t...
ac46ee13662eee8bc8b3ddf0817779cf1502dc49
ShobhitMaheshwari/sign-language1
prepare_chalearn.py
[ "MIT" ]
Python
move_videos
<not_specific>
def move_videos(sSourceDir, sTargetDir, fFrac = 0.2): """ Move fraction of the videos to another folder eg 20% from train to val """ # stop if new folder already exists assert os.path.exists(sTargetDir) == False sCurrentDir = os.getcwd() # get list of all directories = classes os.chdir(sSource...
Move fraction of the videos to another folder eg 20% from train to val
Move fraction of the videos to another folder eg 20% from train to val
[ "Move", "fraction", "of", "the", "videos", "to", "another", "folder", "eg", "20%", "from", "train", "to", "val" ]
def move_videos(sSourceDir, sTargetDir, fFrac = 0.2): assert os.path.exists(sTargetDir) == False sCurrentDir = os.getcwd() os.chdir(sSourceDir) liClasses = glob.glob("*") print("Found %d classes in %s. Move %.0f%% videos to %s ..." % \ (len(liClasses), sSourceDir, fFrac*100, sTargetDir)) ...
[ "def", "move_videos", "(", "sSourceDir", ",", "sTargetDir", ",", "fFrac", "=", "0.2", ")", ":", "assert", "os", ".", "path", ".", "exists", "(", "sTargetDir", ")", "==", "False", "sCurrentDir", "=", "os", ".", "getcwd", "(", ")", "os", ".", "chdir", ...
Move fraction of the videos to another folder eg 20% from train to val
[ "Move", "fraction", "of", "the", "videos", "to", "another", "folder", "eg", "20%", "from", "train", "to", "val" ]
[ "\"\"\" Move fraction of the videos to another folder eg 20% from train to val \"\"\"", "# stop if new folder already exists", "# get list of all directories = classes", "# loop through directories" ]
[ { "param": "sSourceDir", "type": null }, { "param": "sTargetDir", "type": null }, { "param": "fFrac", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "sSourceDir", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "sTargetDir", "type": null, "docstring": null, "docstrin...
1048f0b7c8cd6007cb2c0b1dc7d34ae341ea12bf
ShobhitMaheshwari/sign-language1
videocapture.py
[ "MIT" ]
Python
rectangle_text
<not_specific>
def rectangle_text(arImage, sColor, sUpper, sLower = None, tuRectangle = (224, 224)): """ Returns new image (not altering arImage) """ nHeigth, nWidth, _ = arImage.shape nRectHeigth, nRectWidth = tuRectangle x1 = int((nWidth - nRectWidth) / 2) y1 = int((nHeigth - nRectHeigth) / 2) if sColor == "green": bgr = (...
Returns new image (not altering arImage)
Returns new image (not altering arImage)
[ "Returns", "new", "image", "(", "not", "altering", "arImage", ")" ]
def rectangle_text(arImage, sColor, sUpper, sLower = None, tuRectangle = (224, 224)): nHeigth, nWidth, _ = arImage.shape nRectHeigth, nRectWidth = tuRectangle x1 = int((nWidth - nRectWidth) / 2) y1 = int((nHeigth - nRectHeigth) / 2) if sColor == "green": bgr = (84, 175, 25) elif sColor == "orange": bgr = (60, 125...
[ "def", "rectangle_text", "(", "arImage", ",", "sColor", ",", "sUpper", ",", "sLower", "=", "None", ",", "tuRectangle", "=", "(", "224", ",", "224", ")", ")", ":", "nHeigth", ",", "nWidth", ",", "_", "=", "arImage", ".", "shape", "nRectHeigth", ",", "...
Returns new image (not altering arImage)
[ "Returns", "new", "image", "(", "not", "altering", "arImage", ")" ]
[ "\"\"\" Returns new image (not altering arImage)\n\t\"\"\"", "#sColor == \"red\": ", "# display a text to the frame ", "# 2nd text" ]
[ { "param": "arImage", "type": null }, { "param": "sColor", "type": null }, { "param": "sUpper", "type": null }, { "param": "sLower", "type": null }, { "param": "tuRectangle", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "arImage", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "sColor", "type": null, "docstring": null, "docstring_token...
1048f0b7c8cd6007cb2c0b1dc7d34ae341ea12bf
ShobhitMaheshwari/sign-language1
videocapture.py
[ "MIT" ]
Python
frame_show
<not_specific>
def frame_show(oStream, sColor:str, sText:str, tuRectangle = (224, 224)): """ Read frame from webcam and display it with box+text """ (bGrabbed, oFrame) = oStream.read() oFrame = rectangle_text(cv2.flip(oFrame, 1), sColor, sText, "", tuRectangle) cv2.imshow("Video", oFrame) cv2.waitKey(1) return
Read frame from webcam and display it with box+text
Read frame from webcam and display it with box+text
[ "Read", "frame", "from", "webcam", "and", "display", "it", "with", "box", "+", "text" ]
def frame_show(oStream, sColor:str, sText:str, tuRectangle = (224, 224)): (bGrabbed, oFrame) = oStream.read() oFrame = rectangle_text(cv2.flip(oFrame, 1), sColor, sText, "", tuRectangle) cv2.imshow("Video", oFrame) cv2.waitKey(1) return
[ "def", "frame_show", "(", "oStream", ",", "sColor", ":", "str", ",", "sText", ":", "str", ",", "tuRectangle", "=", "(", "224", ",", "224", ")", ")", ":", "(", "bGrabbed", ",", "oFrame", ")", "=", "oStream", ".", "read", "(", ")", "oFrame", "=", "...
Read frame from webcam and display it with box+text
[ "Read", "frame", "from", "webcam", "and", "display", "it", "with", "box", "+", "text" ]
[ "\"\"\" Read frame from webcam and display it with box+text \"\"\"" ]
[ { "param": "oStream", "type": null }, { "param": "sColor", "type": "str" }, { "param": "sText", "type": "str" }, { "param": "tuRectangle", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "oStream", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "sColor", "type": "str", "docstring": null, "docstring_toke...
8d3b8362bddac80d6b742e73f19923bb78906925
dtedder/WPDx-Toolset
WPDx_Toolset.pyt
[ "MIT" ]
Python
queryWPDx
<not_specific>
def queryWPDx(zone): """Fetches all the water points from WPDx in given administrative area""" # First 2000 results, remove limit and get login if neccessary start = time.clock() client = Socrata("data.waterpointdata.org", None) # Set output fields (this only affects the Repair Priority tool) fi...
Fetches all the water points from WPDx in given administrative area
Fetches all the water points from WPDx in given administrative area
[ "Fetches", "all", "the", "water", "points", "from", "WPDx", "in", "given", "administrative", "area" ]
def queryWPDx(zone): start = time.clock() client = Socrata("data.waterpointdata.org", None) fields = 'adm1,adm2,country_id,country_name,created,data_lnk,fecal_coliform_presence,install_year,installer,photo_lnk,photo_lnk_description,report_date,source,status_id,subjective_quality,updated,water_source,water_t...
[ "def", "queryWPDx", "(", "zone", ")", ":", "start", "=", "time", ".", "clock", "(", ")", "client", "=", "Socrata", "(", "\"data.waterpointdata.org\"", ",", "None", ")", "fields", "=", "'adm1,adm2,country_id,country_name,created,data_lnk,fecal_coliform_presence,install_y...
Fetches all the water points from WPDx in given administrative area
[ "Fetches", "all", "the", "water", "points", "from", "WPDx", "in", "given", "administrative", "area" ]
[ "\"\"\"Fetches all the water points from WPDx in given administrative area\"\"\"", "# First 2000 results, remove limit and get login if neccessary", "# Set output fields (this only affects the Repair Priority tool)", "# it is better to change the'Admin' dataset to match what WPDx API is expecting,", "# but ...
[ { "param": "zone", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "zone", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
8d3b8362bddac80d6b742e73f19923bb78906925
dtedder/WPDx-Toolset
WPDx_Toolset.pyt
[ "MIT" ]
Python
execute
null
def execute(self, parameters, messages): """Calculates percentage of population unserved in each administrative area.""" #scratchworkspace = "in_memory" # Get Paramters global scratch scratch = tempfile.mkdtemp() zone = parameters[0].valueAsText num = parameters[...
Calculates percentage of population unserved in each administrative area.
Calculates percentage of population unserved in each administrative area.
[ "Calculates", "percentage", "of", "population", "unserved", "in", "each", "administrative", "area", "." ]
def execute(self, parameters, messages): global scratch scratch = tempfile.mkdtemp() zone = parameters[0].valueAsText num = parameters[1].valueAsText buff_dist = parameters[2].valueAsText pop_grid = parameters[3].value out_path = parameters[4].value query_...
[ "def", "execute", "(", "self", ",", "parameters", ",", "messages", ")", ":", "global", "scratch", "scratch", "=", "tempfile", ".", "mkdtemp", "(", ")", "zone", "=", "parameters", "[", "0", "]", ".", "valueAsText", "num", "=", "parameters", "[", "1", "]...
Calculates percentage of population unserved in each administrative area.
[ "Calculates", "percentage", "of", "population", "unserved", "in", "each", "administrative", "area", "." ]
[ "\"\"\"Calculates percentage of population unserved in each administrative area.\"\"\"", "#scratchworkspace = \"in_memory\"", "# Get Paramters", "# Query WPDx database", "#arcpy.env.mask = mask", "# should zones close to broken points count as good locations for a new installation?" ]
[ { "param": "self", "type": null }, { "param": "parameters", "type": null }, { "param": "messages", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "parameters", "type": null, "docstring": null, "docstring_toke...
8d3b8362bddac80d6b742e73f19923bb78906925
dtedder/WPDx-Toolset
WPDx_Toolset.pyt
[ "MIT" ]
Python
isLicensed
<not_specific>
def isLicensed(self): """Set whether tool is licensed to execute.""" if arcpy.CheckExtension("Spatial") == "Available": return True else: return False
Set whether tool is licensed to execute.
Set whether tool is licensed to execute.
[ "Set", "whether", "tool", "is", "licensed", "to", "execute", "." ]
def isLicensed(self): if arcpy.CheckExtension("Spatial") == "Available": return True else: return False
[ "def", "isLicensed", "(", "self", ")", ":", "if", "arcpy", ".", "CheckExtension", "(", "\"Spatial\"", ")", "==", "\"Available\"", ":", "return", "True", "else", ":", "return", "False" ]
Set whether tool is licensed to execute.
[ "Set", "whether", "tool", "is", "licensed", "to", "execute", "." ]
[ "\"\"\"Set whether tool is licensed to execute.\"\"\"" ]
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
8d3b8362bddac80d6b742e73f19923bb78906925
dtedder/WPDx-Toolset
WPDx_Toolset.pyt
[ "MIT" ]
Python
calcPriority
<not_specific>
def calcPriority(self, pnts_buff, pop_grid): """Uses zonal statistics to calculate population served by each point""" # create list of non-functioning points pnts = list() with arcpy.da.SearchCursor(pnts_buff, 'wpdx_id', "status_id='no'") as cursor: for row in cursor: ...
Uses zonal statistics to calculate population served by each point
Uses zonal statistics to calculate population served by each point
[ "Uses", "zonal", "statistics", "to", "calculate", "population", "served", "by", "each", "point" ]
def calcPriority(self, pnts_buff, pop_grid): pnts = list() with arcpy.da.SearchCursor(pnts_buff, 'wpdx_id', "status_id='no'") as cursor: for row in cursor: pnts.append(row[0]) start = time.clock() pop_dict = dict() with arcpy.da.SearchCursor(incr_pop,...
[ "def", "calcPriority", "(", "self", ",", "pnts_buff", ",", "pop_grid", ")", ":", "pnts", "=", "list", "(", ")", "with", "arcpy", ".", "da", ".", "SearchCursor", "(", "pnts_buff", ",", "'wpdx_id'", ",", "\"status_id='no'\"", ")", "as", "cursor", ":", "for...
Uses zonal statistics to calculate population served by each point
[ "Uses", "zonal", "statistics", "to", "calculate", "population", "served", "by", "each", "point" ]
[ "\"\"\"Uses zonal statistics to calculate population served by each point\"\"\"", "# create list of non-functioning points", "# create dictionary with population served by each point", "# Code is commented out bc ZonalStatisticsAsTable doesn't currently work with overlapping polygons", "# incr_pop = arcpy.g...
[ { "param": "self", "type": null }, { "param": "pnts_buff", "type": null }, { "param": "pop_grid", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "pnts_buff", "type": null, "docstring": null, "docstring_token...
8d3b8362bddac80d6b742e73f19923bb78906925
dtedder/WPDx-Toolset
WPDx_Toolset.pyt
[ "MIT" ]
Python
execute
null
def execute(self, parameters, messages): """The source code of the tool.""" # Get Parameters global scratch scratch = tempfile.mkdtemp() zone = parameters[0].valueAsText buff_dist = parameters[1].valueAsText pop_grid = parameters[2].value out_path = param...
The source code of the tool.
The source code of the tool.
[ "The", "source", "code", "of", "the", "tool", "." ]
def execute(self, parameters, messages): global scratch scratch = tempfile.mkdtemp() zone = parameters[0].valueAsText buff_dist = parameters[1].valueAsText pop_grid = parameters[2].value out_path = parameters[3].value query_response, mask = queryWPDx(zone) ...
[ "def", "execute", "(", "self", ",", "parameters", ",", "messages", ")", ":", "global", "scratch", "scratch", "=", "tempfile", ".", "mkdtemp", "(", ")", "zone", "=", "parameters", "[", "0", "]", ".", "valueAsText", "buff_dist", "=", "parameters", "[", "1"...
The source code of the tool.
[ "The", "source", "code", "of", "the", "tool", "." ]
[ "\"\"\"The source code of the tool.\"\"\"", "# Get Parameters", "# Calculate incremental population that could be served by each broken water point", "# Add population served to water points as an attribute" ]
[ { "param": "self", "type": null }, { "param": "parameters", "type": null }, { "param": "messages", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "parameters", "type": null, "docstring": null, "docstring_toke...
8d3b8362bddac80d6b742e73f19923bb78906925
dtedder/WPDx-Toolset
WPDx_Toolset.pyt
[ "MIT" ]
Python
calcUnserved
<not_specific>
def calcUnserved(self, admin_zones, unserved_population): """Uses zonal statistics to calculate population unserved in each zone""" start = time.clock() pop_dict = dict() pop_by_region = arcpy.gp.ZonalStatisticsAsTable_sa(admin_zones, 'Name', ...
Uses zonal statistics to calculate population unserved in each zone
Uses zonal statistics to calculate population unserved in each zone
[ "Uses", "zonal", "statistics", "to", "calculate", "population", "unserved", "in", "each", "zone" ]
def calcUnserved(self, admin_zones, unserved_population): start = time.clock() pop_dict = dict() pop_by_region = arcpy.gp.ZonalStatisticsAsTable_sa(admin_zones, 'Name', unserved_population, ...
[ "def", "calcUnserved", "(", "self", ",", "admin_zones", ",", "unserved_population", ")", ":", "start", "=", "time", ".", "clock", "(", ")", "pop_dict", "=", "dict", "(", ")", "pop_by_region", "=", "arcpy", ".", "gp", ".", "ZonalStatisticsAsTable_sa", "(", ...
Uses zonal statistics to calculate population unserved in each zone
[ "Uses", "zonal", "statistics", "to", "calculate", "population", "unserved", "in", "each", "zone" ]
[ "\"\"\"Uses zonal statistics to calculate population unserved in each zone\"\"\"" ]
[ { "param": "self", "type": null }, { "param": "admin_zones", "type": null }, { "param": "unserved_population", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "admin_zones", "type": null, "docstring": null, "docstring_tok...
8d3b8362bddac80d6b742e73f19923bb78906925
dtedder/WPDx-Toolset
WPDx_Toolset.pyt
[ "MIT" ]
Python
execute
null
def execute(self, parameters, messages): """Calculates percentage of population unserved in each administrative area.""" # Get Paramters global scratch scratch = tempfile.mkdtemp() country = parameters[0].valueAsText buff_dist = parameters[1].valueAsText pop_grid...
Calculates percentage of population unserved in each administrative area.
Calculates percentage of population unserved in each administrative area.
[ "Calculates", "percentage", "of", "population", "unserved", "in", "each", "administrative", "area", "." ]
def execute(self, parameters, messages): global scratch scratch = tempfile.mkdtemp() country = parameters[0].valueAsText buff_dist = parameters[1].valueAsText pop_grid = parameters[2].value out_path = "in_memory\ServiceOverview" query_response, mask = queryWPDx(co...
[ "def", "execute", "(", "self", ",", "parameters", ",", "messages", ")", ":", "global", "scratch", "scratch", "=", "tempfile", ".", "mkdtemp", "(", ")", "country", "=", "parameters", "[", "0", "]", ".", "valueAsText", "buff_dist", "=", "parameters", "[", ...
Calculates percentage of population unserved in each administrative area.
[ "Calculates", "percentage", "of", "population", "unserved", "in", "each", "administrative", "area", "." ]
[ "\"\"\"Calculates percentage of population unserved in each administrative area.\"\"\"", "# Get Paramters", "# Query WPDx database", "# Calculate percentage of population unserved in each administrative area", "# would buffer be faster in different coordinate system?", "# Append new data to output feature...
[ { "param": "self", "type": null }, { "param": "parameters", "type": null }, { "param": "messages", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "parameters", "type": null, "docstring": null, "docstring_toke...
8d3b8362bddac80d6b742e73f19923bb78906925
dtedder/WPDx-Toolset
WPDx_Toolset.pyt
[ "MIT" ]
Python
execute
null
def execute(self, parameters, messages): """Removes urban areas and areas near a functioning well from population raster.""" # Get Paramters global scratch scratch = tempfile.mkdtemp() zone = parameters[0].valueAsText buff_dist = parameters[1].valueAsText pop_gri...
Removes urban areas and areas near a functioning well from population raster.
Removes urban areas and areas near a functioning well from population raster.
[ "Removes", "urban", "areas", "and", "areas", "near", "a", "functioning", "well", "from", "population", "raster", "." ]
def execute(self, parameters, messages): global scratch scratch = tempfile.mkdtemp() zone = parameters[0].valueAsText buff_dist = parameters[1].valueAsText pop_grid = parameters[2].value out_path = parameters[3].value query_response, mask = queryWPDx(zone) ...
[ "def", "execute", "(", "self", ",", "parameters", ",", "messages", ")", ":", "global", "scratch", "scratch", "=", "tempfile", ".", "mkdtemp", "(", ")", "zone", "=", "parameters", "[", "0", "]", ".", "valueAsText", "buff_dist", "=", "parameters", "[", "1"...
Removes urban areas and areas near a functioning well from population raster.
[ "Removes", "urban", "areas", "and", "areas", "near", "a", "functioning", "well", "from", "population", "raster", "." ]
[ "\"\"\"Removes urban areas and areas near a functioning well from population raster.\"\"\"", "# Get Paramters", "# Query WPDx database" ]
[ { "param": "self", "type": null }, { "param": "parameters", "type": null }, { "param": "messages", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "parameters", "type": null, "docstring": null, "docstring_toke...
8d3b8362bddac80d6b742e73f19923bb78906925
dtedder/WPDx-Toolset
WPDx_Toolset.pyt
[ "MIT" ]
Python
execute
null
def execute(self, parameters, messages): """Calculates rural population in each administrative area.""" admin = join(dirname(__file__), "Data", "ToolData.gdb", "Admin") #set up a scratch workspace and set it as env scratch = tempfile.mkdtemp() gdb = arcpy.CreateFileGDB_manageme...
Calculates rural population in each administrative area.
Calculates rural population in each administrative area.
[ "Calculates", "rural", "population", "in", "each", "administrative", "area", "." ]
def execute(self, parameters, messages): admin = join(dirname(__file__), "Data", "ToolData.gdb", "Admin") scratch = tempfile.mkdtemp() gdb = arcpy.CreateFileGDB_management(scratch, "temp").getOutput(0) country = parameters[0].valueAsText if len(country) > 2: query_typ...
[ "def", "execute", "(", "self", ",", "parameters", ",", "messages", ")", ":", "admin", "=", "join", "(", "dirname", "(", "__file__", ")", ",", "\"Data\"", ",", "\"ToolData.gdb\"", ",", "\"Admin\"", ")", "scratch", "=", "tempfile", ".", "mkdtemp", "(", ")"...
Calculates rural population in each administrative area.
[ "Calculates", "rural", "population", "in", "each", "administrative", "area", "." ]
[ "\"\"\"Calculates rural population in each administrative area.\"\"\"", "#set up a scratch workspace and set it as env", "#arcpy.env.scratchGDB = gdb", "#arcpy.env.workspace = gdb", "#arcpy.env.scratchWorkspace = gdb", "# arcpy.env.snapRaster = pop_grid", "# Get path to population data", "#try:", "#...
[ { "param": "self", "type": null }, { "param": "parameters", "type": null }, { "param": "messages", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "parameters", "type": null, "docstring": null, "docstring_toke...
604b333cb7656eaddb5801d8662bf8982ce0141d
eugenevinitsky/sequential_social_dilemma_games
models/moa_model.py
[ "MIT" ]
Python
create_moa_encoder_model
<not_specific>
def create_moa_encoder_model(obs_space, model_config): """ Creates the convolutional part of the MOA model. Also casts the input uint8 observations to float32 and normalizes them to the range [0,1]. :param obs_space: The agent's observation space. :param model_config: The config ...
Creates the convolutional part of the MOA model. Also casts the input uint8 observations to float32 and normalizes them to the range [0,1]. :param obs_space: The agent's observation space. :param model_config: The config dict containing parameters for the convolution type/shape. ...
Creates the convolutional part of the MOA model. Also casts the input uint8 observations to float32 and normalizes them to the range [0,1].
[ "Creates", "the", "convolutional", "part", "of", "the", "MOA", "model", ".", "Also", "casts", "the", "input", "uint8", "observations", "to", "float32", "and", "normalizes", "them", "to", "the", "range", "[", "0", "1", "]", "." ]
def create_moa_encoder_model(obs_space, model_config): original_obs_dims = obs_space.original_space.spaces["curr_obs"].shape inputs = tf.keras.layers.Input(original_obs_dims, name="observations", dtype=tf.uint8) last_layer = tf.keras.backend.cast(inputs, tf.float32) last_layer = tf.math....
[ "def", "create_moa_encoder_model", "(", "obs_space", ",", "model_config", ")", ":", "original_obs_dims", "=", "obs_space", ".", "original_space", ".", "spaces", "[", "\"curr_obs\"", "]", ".", "shape", "inputs", "=", "tf", ".", "keras", ".", "layers", ".", "Inp...
Creates the convolutional part of the MOA model.
[ "Creates", "the", "convolutional", "part", "of", "the", "MOA", "model", "." ]
[ "\"\"\"\n Creates the convolutional part of the MOA model.\n Also casts the input uint8 observations to float32 and normalizes them to the range [0,1].\n :param obs_space: The agent's observation space.\n :param model_config: The config dict containing parameters for the convolution type...
[ { "param": "obs_space", "type": null }, { "param": "model_config", "type": null } ]
{ "returns": [ { "docstring": "A new Model object containing the convolution.", "docstring_tokens": [ "A", "new", "Model", "object", "containing", "the", "convolution", "." ], "type": null } ], "raises": [], "params"...
604b333cb7656eaddb5801d8662bf8982ce0141d
eugenevinitsky/sequential_social_dilemma_games
models/moa_model.py
[ "MIT" ]
Python
forward
<not_specific>
def forward(self, input_dict, state, seq_lens): """ First evaluate non-LSTM parts of model. Then add a time dimension to the batch before sending inputs to forward_rnn(), which evaluates the LSTM parts of the model. :param input_dict: The input tensors. :param state: The model st...
First evaluate non-LSTM parts of model. Then add a time dimension to the batch before sending inputs to forward_rnn(), which evaluates the LSTM parts of the model. :param input_dict: The input tensors. :param state: The model state. :param seq_lens: LSTM sequence lengths. ...
First evaluate non-LSTM parts of model. Then add a time dimension to the batch before sending inputs to forward_rnn(), which evaluates the LSTM parts of the model.
[ "First", "evaluate", "non", "-", "LSTM", "parts", "of", "model", ".", "Then", "add", "a", "time", "dimension", "to", "the", "batch", "before", "sending", "inputs", "to", "forward_rnn", "()", "which", "evaluates", "the", "LSTM", "parts", "of", "the", "model...
def forward(self, input_dict, state, seq_lens): actor_critic_fc_output, moa_fc_output = self.moa_encoder_model(input_dict["obs"]["curr_obs"]) rnn_input_dict = { "ac_trunk": actor_critic_fc_output, "prev_moa_trunk": state[5], "other_agent_actions": input_dict["obs"]["o...
[ "def", "forward", "(", "self", ",", "input_dict", ",", "state", ",", "seq_lens", ")", ":", "actor_critic_fc_output", ",", "moa_fc_output", "=", "self", ".", "moa_encoder_model", "(", "input_dict", "[", "\"obs\"", "]", "[", "\"curr_obs\"", "]", ")", "rnn_input_...
First evaluate non-LSTM parts of model.
[ "First", "evaluate", "non", "-", "LSTM", "parts", "of", "model", "." ]
[ "\"\"\"\n First evaluate non-LSTM parts of model. Then add a time dimension to the batch before\n sending inputs to forward_rnn(), which evaluates the LSTM parts of the model.\n :param input_dict: The input tensors.\n :param state: The model state.\n :param seq_lens: LSTM sequence...
[ { "param": "self", "type": null }, { "param": "input_dict", "type": null }, { "param": "state", "type": null }, { "param": "seq_lens", "type": null } ]
{ "returns": [ { "docstring": "The agent's own action logits and the new model state.", "docstring_tokens": [ "The", "agent", "'", "s", "own", "action", "logits", "and", "the", "new", "model", "state", ...
604b333cb7656eaddb5801d8662bf8982ce0141d
eugenevinitsky/sequential_social_dilemma_games
models/moa_model.py
[ "MIT" ]
Python
forward_rnn
<not_specific>
def forward_rnn(self, input_dict, state, seq_lens): """ Forward pass through the MOA LSTMs. Implicitly assigns the value function output to self_value_out, and does not return this. :param input_dict: The input tensors. :param state: The model state. :param seq_lens: LSTM...
Forward pass through the MOA LSTMs. Implicitly assigns the value function output to self_value_out, and does not return this. :param input_dict: The input tensors. :param state: The model state. :param seq_lens: LSTM sequence lengths. :return: The policy logits and new L...
Forward pass through the MOA LSTMs. Implicitly assigns the value function output to self_value_out, and does not return this.
[ "Forward", "pass", "through", "the", "MOA", "LSTMs", ".", "Implicitly", "assigns", "the", "value", "function", "output", "to", "self_value_out", "and", "does", "not", "return", "this", "." ]
def forward_rnn(self, input_dict, state, seq_lens): pass_dict = {"curr_obs": input_dict["ac_trunk"]} h1, c1, h2, c2, *_ = state (self._model_out, self._value_out, output_h1, output_c1,) = self.actions_model.forward_rnn( pass_dict, [h1, c1], seq_lens ) prev_moa_trunk =...
[ "def", "forward_rnn", "(", "self", ",", "input_dict", ",", "state", ",", "seq_lens", ")", ":", "pass_dict", "=", "{", "\"curr_obs\"", ":", "input_dict", "[", "\"ac_trunk\"", "]", "}", "h1", ",", "c1", ",", "h2", ",", "c2", ",", "*", "_", "=", "state"...
Forward pass through the MOA LSTMs.
[ "Forward", "pass", "through", "the", "MOA", "LSTMs", "." ]
[ "\"\"\"\n Forward pass through the MOA LSTMs.\n Implicitly assigns the value function output to self_value_out, and does not return this.\n :param input_dict: The input tensors.\n :param state: The model state.\n :param seq_lens: LSTM sequence lengths.\n :return: The policy...
[ { "param": "self", "type": null }, { "param": "input_dict", "type": null }, { "param": "state", "type": null }, { "param": "seq_lens", "type": null } ]
{ "returns": [ { "docstring": "The policy logits and new LSTM states.", "docstring_tokens": [ "The", "policy", "logits", "and", "new", "LSTM", "states", "." ], "type": null } ], "raises": [], "params": [ { ...
604b333cb7656eaddb5801d8662bf8982ce0141d
eugenevinitsky/sequential_social_dilemma_games
models/moa_model.py
[ "MIT" ]
Python
compute_influence_reward
null
def compute_influence_reward(self, input_dict, prev_action_logits, counterfactual_logits): """ Compute influence of this agent on other agents. :param input_dict: The model input tensors. :param prev_action_logits: Logits for the agent's own policy/actions at t-1 :param counterfa...
Compute influence of this agent on other agents. :param input_dict: The model input tensors. :param prev_action_logits: Logits for the agent's own policy/actions at t-1 :param counterfactual_logits: The counterfactual action logits for actions made by other agents at t.
Compute influence of this agent on other agents.
[ "Compute", "influence", "of", "this", "agent", "on", "other", "agents", "." ]
def compute_influence_reward(self, input_dict, prev_action_logits, counterfactual_logits): prev_agent_actions = tf.cast(tf.reshape(input_dict["prev_actions"], [-1, 1]), tf.int32) predicted_logits = tf.gather_nd( params=counterfactual_logits, indices=prev_agent_actions, batch_dims=1 )...
[ "def", "compute_influence_reward", "(", "self", ",", "input_dict", ",", "prev_action_logits", ",", "counterfactual_logits", ")", ":", "prev_agent_actions", "=", "tf", ".", "cast", "(", "tf", ".", "reshape", "(", "input_dict", "[", "\"prev_actions\"", "]", ",", "...
Compute influence of this agent on other agents.
[ "Compute", "influence", "of", "this", "agent", "on", "other", "agents", "." ]
[ "\"\"\"\n Compute influence of this agent on other agents.\n :param input_dict: The model input tensors.\n :param prev_action_logits: Logits for the agent's own policy/actions at t-1\n :param counterfactual_logits: The counterfactual action logits for actions made by other\n agent...
[ { "param": "self", "type": null }, { "param": "input_dict", "type": null }, { "param": "prev_action_logits", "type": null }, { "param": "counterfactual_logits", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "input_dict", "type": null, "docstring": "The model input tensors.",...
604b333cb7656eaddb5801d8662bf8982ce0141d
eugenevinitsky/sequential_social_dilemma_games
models/moa_model.py
[ "MIT" ]
Python
marginalize_predictions_over_own_actions
<not_specific>
def marginalize_predictions_over_own_actions(self, prev_action_logits, counterfactual_logits): """ Calculates marginal policies for all other agents. :param prev_action_logits: The agent's own policy logits at time t-1 . :param counterfactual_logits: The counterfactual action predictions...
Calculates marginal policies for all other agents. :param prev_action_logits: The agent's own policy logits at time t-1 . :param counterfactual_logits: The counterfactual action predictions made at time t-1 for other agents' actions at t. :return: The marginal policies for all o...
Calculates marginal policies for all other agents.
[ "Calculates", "marginal", "policies", "for", "all", "other", "agents", "." ]
def marginalize_predictions_over_own_actions(self, prev_action_logits, counterfactual_logits): logits = tf.nn.softmax(prev_action_logits) logits = logits / tf.reduce_sum(logits, axis=-1, keepdims=True) counterfactual_logits = tf.reshape( counterfactual_logits, [-1, self.num_outputs, ...
[ "def", "marginalize_predictions_over_own_actions", "(", "self", ",", "prev_action_logits", ",", "counterfactual_logits", ")", ":", "logits", "=", "tf", ".", "nn", ".", "softmax", "(", "prev_action_logits", ")", "logits", "=", "logits", "/", "tf", ".", "reduce_sum"...
Calculates marginal policies for all other agents.
[ "Calculates", "marginal", "policies", "for", "all", "other", "agents", "." ]
[ "\"\"\"\n Calculates marginal policies for all other agents.\n :param prev_action_logits: The agent's own policy logits at time t-1 .\n :param counterfactual_logits: The counterfactual action predictions made at time t-1 for\n other agents' actions at t.\n :return: The marginal po...
[ { "param": "self", "type": null }, { "param": "prev_action_logits", "type": null }, { "param": "counterfactual_logits", "type": null } ]
{ "returns": [ { "docstring": "The marginal policies for all other agents.", "docstring_tokens": [ "The", "marginal", "policies", "for", "all", "other", "agents", "." ], "type": null } ], "raises": [], "params": [ ...
604b333cb7656eaddb5801d8662bf8982ce0141d
eugenevinitsky/sequential_social_dilemma_games
models/moa_model.py
[ "MIT" ]
Python
kl_div
<not_specific>
def kl_div(x, y): """ Calculate KL divergence between two distributions. :param x: A distribution :param y: A distribution :return: The KL-divergence between x and y. Returns zeros if the KL-divergence contains NaN or Infinity. """ dist_x = tf.distribution...
Calculate KL divergence between two distributions. :param x: A distribution :param y: A distribution :return: The KL-divergence between x and y. Returns zeros if the KL-divergence contains NaN or Infinity.
Calculate KL divergence between two distributions.
[ "Calculate", "KL", "divergence", "between", "two", "distributions", "." ]
def kl_div(x, y): dist_x = tf.distributions.Categorical(probs=x) dist_y = tf.distributions.Categorical(probs=y) result = tf.distributions.kl_divergence(dist_x, dist_y) is_finite = tf.reduce_all(tf.is_finite(result)) def true_fn(): return result def false_fn():...
[ "def", "kl_div", "(", "x", ",", "y", ")", ":", "dist_x", "=", "tf", ".", "distributions", ".", "Categorical", "(", "probs", "=", "x", ")", "dist_y", "=", "tf", ".", "distributions", ".", "Categorical", "(", "probs", "=", "y", ")", "result", "=", "t...
Calculate KL divergence between two distributions.
[ "Calculate", "KL", "divergence", "between", "two", "distributions", "." ]
[ "\"\"\"\n Calculate KL divergence between two distributions.\n :param x: A distribution\n :param y: A distribution\n :return: The KL-divergence between x and y. Returns zeros if the KL-divergence contains NaN\n or Infinity.\n \"\"\"", "# Don't return nans or infs" ]
[ { "param": "x", "type": null }, { "param": "y", "type": null } ]
{ "returns": [ { "docstring": "The KL-divergence between x and y. Returns zeros if the KL-divergence contains NaN\nor Infinity.", "docstring_tokens": [ "The", "KL", "-", "divergence", "between", "x", "and", "y", ".", "Retu...
604b333cb7656eaddb5801d8662bf8982ce0141d
eugenevinitsky/sequential_social_dilemma_games
models/moa_model.py
[ "MIT" ]
Python
_reshaped_one_hot_actions
<not_specific>
def _reshaped_one_hot_actions(self, actions_tensor, name): """ Converts the collection of all actions from a number encoding to a one-hot encoding. Then, flattens the one-hot encoding so that all concatenated one-hot vectors are the same dimension. E.g. with a num_outputs (action_space.n...
Converts the collection of all actions from a number encoding to a one-hot encoding. Then, flattens the one-hot encoding so that all concatenated one-hot vectors are the same dimension. E.g. with a num_outputs (action_space.n) of 3: _reshaped_one_hot_actions([0,1,2]) returns [1,0,0,0,1,...
Converts the collection of all actions from a number encoding to a one-hot encoding. Then, flattens the one-hot encoding so that all concatenated one-hot vectors are the same dimension.
[ "Converts", "the", "collection", "of", "all", "actions", "from", "a", "number", "encoding", "to", "a", "one", "-", "hot", "encoding", ".", "Then", "flattens", "the", "one", "-", "hot", "encoding", "so", "that", "all", "concatenated", "one", "-", "hot", "...
def _reshaped_one_hot_actions(self, actions_tensor, name): one_hot_actions = tf.keras.backend.one_hot(actions_tensor, self.num_outputs) batch_time_dims = [ tf.shape(one_hot_actions)[k] for k in range(one_hot_actions.shape.rank - 2) ] reshape_dims = batch_time_dims + [actions_...
[ "def", "_reshaped_one_hot_actions", "(", "self", ",", "actions_tensor", ",", "name", ")", ":", "one_hot_actions", "=", "tf", ".", "keras", ".", "backend", ".", "one_hot", "(", "actions_tensor", ",", "self", ".", "num_outputs", ")", "batch_time_dims", "=", "[",...
Converts the collection of all actions from a number encoding to a one-hot encoding.
[ "Converts", "the", "collection", "of", "all", "actions", "from", "a", "number", "encoding", "to", "a", "one", "-", "hot", "encoding", "." ]
[ "\"\"\"\n Converts the collection of all actions from a number encoding to a one-hot encoding.\n Then, flattens the one-hot encoding so that all concatenated one-hot vectors are the same\n dimension. E.g. with a num_outputs (action_space.n) of 3:\n _reshaped_one_hot_actions([0,1,2]) retu...
[ { "param": "self", "type": null }, { "param": "actions_tensor", "type": null }, { "param": "name", "type": null } ]
{ "returns": [ { "docstring": "Tensor containing one-hot reshaped action values.", "docstring_tokens": [ "Tensor", "containing", "one", "-", "hot", "reshaped", "action", "values", "." ], "type": null } ], "rais...
604b333cb7656eaddb5801d8662bf8982ce0141d
eugenevinitsky/sequential_social_dilemma_games
models/moa_model.py
[ "MIT" ]
Python
predicted_actions
<not_specific>
def predicted_actions(self): """ :returns Predicted actions. NB: Since the agent's own true action is not known when evaluating this model, the timestep is off by one (too late). Thus, for any index n > 0, the value at n is a prediction made at n-1, about the actions taken at n. predi...
:returns Predicted actions. NB: Since the agent's own true action is not known when evaluating this model, the timestep is off by one (too late). Thus, for any index n > 0, the value at n is a prediction made at n-1, about the actions taken at n. predicted_actions[0] contains no sensible val...
:returns Predicted actions. NB: Since the agent's own true action is not known when evaluating this model, the timestep is off by one (too late). Thus, for any index n > 0, the value at n is a prediction made at n-1, about the actions taken at n. predicted_actions[0] contains no sensible value, as this would have to be...
[ ":", "returns", "Predicted", "actions", ".", "NB", ":", "Since", "the", "agent", "'", "s", "own", "true", "action", "is", "not", "known", "when", "evaluating", "this", "model", "the", "timestep", "is", "off", "by", "one", "(", "too", "late", ")", ".", ...
def predicted_actions(self): return self._action_pred
[ "def", "predicted_actions", "(", "self", ")", ":", "return", "self", ".", "_action_pred" ]
:returns Predicted actions.
[ ":", "returns", "Predicted", "actions", "." ]
[ "\"\"\" :returns Predicted actions. NB: Since the agent's own true action is not known when\n evaluating this model, the timestep is off by one (too late). Thus, for any index n > 0,\n the value at n is a prediction made at n-1, about the actions taken at n.\n predicted_actions[0] contains n...
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
7df5be47d7287e9549829cbb1e0567df775dd7e0
eugenevinitsky/sequential_social_dilemma_games
visualization/rollout.py
[ "MIT" ]
Python
rollout
<not_specific>
def rollout(self, horizon=50, save_path=None): """ Rollout several timesteps of an episode of the environment. Args: horizon: The number of timesteps to roll out. save_path: If provided, will save each frame to disk at this location. """ rewards =...
Rollout several timesteps of an episode of the environment. Args: horizon: The number of timesteps to roll out. save_path: If provided, will save each frame to disk at this location.
Rollout several timesteps of an episode of the environment.
[ "Rollout", "several", "timesteps", "of", "an", "episode", "of", "the", "environment", "." ]
def rollout(self, horizon=50, save_path=None): rewards = [] observations = [] shape = self.env.world_map.shape full_obs = [np.zeros((shape[0], shape[1], 3), dtype=np.uint8) for i in range(horizon)] for i in range(horizon): agents = list(self.env.agents.values()) ...
[ "def", "rollout", "(", "self", ",", "horizon", "=", "50", ",", "save_path", "=", "None", ")", ":", "rewards", "=", "[", "]", "observations", "=", "[", "]", "shape", "=", "self", ".", "env", ".", "world_map", ".", "shape", "full_obs", "=", "[", "np"...
Rollout several timesteps of an episode of the environment.
[ "Rollout", "several", "timesteps", "of", "an", "episode", "of", "the", "environment", "." ]
[ "\"\"\" Rollout several timesteps of an episode of the environment.\n\n Args:\n horizon: The number of timesteps to roll out.\n save_path: If provided, will save each frame to disk at this\n location.\n \"\"\"" ]
[ { "param": "self", "type": null }, { "param": "horizon", "type": null }, { "param": "save_path", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "horizon", "type": null, "docstring": "The number of timesteps to ro...
7df5be47d7287e9549829cbb1e0567df775dd7e0
eugenevinitsky/sequential_social_dilemma_games
visualization/rollout.py
[ "MIT" ]
Python
render_rollout
null
def render_rollout(self, horizon=50, path=None, render_type="pretty", fps=8): """ Render a rollout into a video. Args: horizon: The number of timesteps to roll out. path: Directory where the video will be saved. render_type: Can be 'pretty' or 'fast'. Impliciations o...
Render a rollout into a video. Args: horizon: The number of timesteps to roll out. path: Directory where the video will be saved. render_type: Can be 'pretty' or 'fast'. Impliciations obvious. fps: Integer frames per second.
Render a rollout into a video.
[ "Render", "a", "rollout", "into", "a", "video", "." ]
def render_rollout(self, horizon=50, path=None, render_type="pretty", fps=8): if path is None: path = os.path.abspath(os.path.dirname(__file__)) + "/videos" print(path) if not os.path.exists(path): os.makedirs(path) video_name = self.env_name + "_traje...
[ "def", "render_rollout", "(", "self", ",", "horizon", "=", "50", ",", "path", "=", "None", ",", "render_type", "=", "\"pretty\"", ",", "fps", "=", "8", ")", ":", "if", "path", "is", "None", ":", "path", "=", "os", ".", "path", ".", "abspath", "(", ...
Render a rollout into a video.
[ "Render", "a", "rollout", "into", "a", "video", "." ]
[ "\"\"\" Render a rollout into a video.\n\n Args:\n horizon: The number of timesteps to roll out.\n path: Directory where the video will be saved.\n render_type: Can be 'pretty' or 'fast'. Impliciations obvious.\n fps: Integer frames per second.\n \"\"\"", ...
[ { "param": "self", "type": null }, { "param": "horizon", "type": null }, { "param": "path", "type": null }, { "param": "render_type", "type": null }, { "param": "fps", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "horizon", "type": null, "docstring": "The number of timesteps to ro...
6f664ee63abf537ccb5a97d053350af3c352a1d9
eugenevinitsky/sequential_social_dilemma_games
models/actor_critic_lstm.py
[ "MIT" ]
Python
forward_rnn
<not_specific>
def forward_rnn(self, input_dict, state, seq_lens): """ Forward pass through the LSTM. :param input_dict: The input tensors. :param state: The model state. :param seq_lens: LSTM sequence lengths. :return: The model output. """ input = [input_dict["curr_obs...
Forward pass through the LSTM. :param input_dict: The input tensors. :param state: The model state. :param seq_lens: LSTM sequence lengths. :return: The model output.
Forward pass through the LSTM.
[ "Forward", "pass", "through", "the", "LSTM", "." ]
def forward_rnn(self, input_dict, state, seq_lens): input = [input_dict["curr_obs"], seq_lens] + state model_out, self._value_out, h, c = self.rnn_model(input) return model_out, self._value_out, h, c
[ "def", "forward_rnn", "(", "self", ",", "input_dict", ",", "state", ",", "seq_lens", ")", ":", "input", "=", "[", "input_dict", "[", "\"curr_obs\"", "]", ",", "seq_lens", "]", "+", "state", "model_out", ",", "self", ".", "_value_out", ",", "h", ",", "c...
Forward pass through the LSTM.
[ "Forward", "pass", "through", "the", "LSTM", "." ]
[ "\"\"\"\n Forward pass through the LSTM.\n :param input_dict: The input tensors.\n :param state: The model state.\n :param seq_lens: LSTM sequence lengths.\n :return: The model output.\n \"\"\"" ]
[ { "param": "self", "type": null }, { "param": "input_dict", "type": null }, { "param": "state", "type": null }, { "param": "seq_lens", "type": null } ]
{ "returns": [ { "docstring": "The model output.", "docstring_tokens": [ "The", "model", "output", "." ], "type": null } ], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_to...
3c1fa27068afc445fc34b15e460dc24141bb933c
eugenevinitsky/sequential_social_dilemma_games
social_dilemmas/envs/cleanup.py
[ "MIT" ]
Python
custom_reset
null
def custom_reset(self): """Initialize the walls and the waste""" for waste_start_point in self.waste_start_points: self.single_update_map(waste_start_point[0], waste_start_point[1], b"H") for river_point in self.river_points: self.single_update_map(river_point[0], river_p...
Initialize the walls and the waste
Initialize the walls and the waste
[ "Initialize", "the", "walls", "and", "the", "waste" ]
def custom_reset(self): for waste_start_point in self.waste_start_points: self.single_update_map(waste_start_point[0], waste_start_point[1], b"H") for river_point in self.river_points: self.single_update_map(river_point[0], river_point[1], b"R") for stream_point in self.s...
[ "def", "custom_reset", "(", "self", ")", ":", "for", "waste_start_point", "in", "self", ".", "waste_start_points", ":", "self", ".", "single_update_map", "(", "waste_start_point", "[", "0", "]", ",", "waste_start_point", "[", "1", "]", ",", "b\"H\"", ")", "f...
Initialize the walls and the waste
[ "Initialize", "the", "walls", "and", "the", "waste" ]
[ "\"\"\"Initialize the walls and the waste\"\"\"" ]
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
3c1fa27068afc445fc34b15e460dc24141bb933c
eugenevinitsky/sequential_social_dilemma_games
social_dilemmas/envs/cleanup.py
[ "MIT" ]
Python
custom_action
<not_specific>
def custom_action(self, agent, action): """Allows agents to take actions that are not move or turn""" updates = [] if action == "FIRE": agent.fire_beam(b"F") updates = self.update_map_fire( agent.pos.tolist(), agent.get_orientation(), ...
Allows agents to take actions that are not move or turn
Allows agents to take actions that are not move or turn
[ "Allows", "agents", "to", "take", "actions", "that", "are", "not", "move", "or", "turn" ]
def custom_action(self, agent, action): updates = [] if action == "FIRE": agent.fire_beam(b"F") updates = self.update_map_fire( agent.pos.tolist(), agent.get_orientation(), self.all_actions["FIRE"], fire_char=b"F", ...
[ "def", "custom_action", "(", "self", ",", "agent", ",", "action", ")", ":", "updates", "=", "[", "]", "if", "action", "==", "\"FIRE\"", ":", "agent", ".", "fire_beam", "(", "b\"F\"", ")", "updates", "=", "self", ".", "update_map_fire", "(", "agent", "....
Allows agents to take actions that are not move or turn
[ "Allows", "agents", "to", "take", "actions", "that", "are", "not", "move", "or", "turn" ]
[ "\"\"\"Allows agents to take actions that are not move or turn\"\"\"" ]
[ { "param": "self", "type": null }, { "param": "agent", "type": null }, { "param": "action", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "agent", "type": null, "docstring": null, "docstring_tokens": ...
5bcfcf7d6ca467ab8e59645e9fb19d11fa24b83b
eugenevinitsky/sequential_social_dilemma_games
tests/test_envs.py
[ "MIT" ]
Python
convert_empty_cells
<not_specific>
def convert_empty_cells(view): """Change all empty cells marked with '0' to ' ' for consistency.""" # No mask because it doesn't work correctly on byte arrays for x in range(len(view)): for y in range(len(view[0])): view[x, y] = b" " if view[x, y] == b"0" else view[x,...
Change all empty cells marked with '0' to ' ' for consistency.
Change all empty cells marked with '0' to ' ' for consistency.
[ "Change", "all", "empty", "cells", "marked", "with", "'", "0", "'", "to", "'", "'", "for", "consistency", "." ]
def convert_empty_cells(view): for x in range(len(view)): for y in range(len(view[0])): view[x, y] = b" " if view[x, y] == b"0" else view[x, y] return view
[ "def", "convert_empty_cells", "(", "view", ")", ":", "for", "x", "in", "range", "(", "len", "(", "view", ")", ")", ":", "for", "y", "in", "range", "(", "len", "(", "view", "[", "0", "]", ")", ")", ":", "view", "[", "x", ",", "y", "]", "=", ...
Change all empty cells marked with '0' to ' ' for consistency.
[ "Change", "all", "empty", "cells", "marked", "with", "'", "0", "'", "to", "'", "'", "for", "consistency", "." ]
[ "\"\"\"Change all empty cells marked with '0' to ' ' for consistency.\"\"\"", "# No mask because it doesn't work correctly on byte arrays" ]
[ { "param": "view", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "view", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
0c7b2e08c3e5be643b4bec0599ea7bf635fed5c6
eugenevinitsky/sequential_social_dilemma_games
algorithms/common_funcs_scm.py
[ "MIT" ]
Python
compute_curiosity_reward_weight
<not_specific>
def compute_curiosity_reward_weight(self): """ Computes multiplier for social_curiosity reward based on training steps taken and schedule parameters. """ weight = np.interp( self.timestep, self.curiosity_reward_schedule_steps, self.curiosity_reward_sch...
Computes multiplier for social_curiosity reward based on training steps taken and schedule parameters.
Computes multiplier for social_curiosity reward based on training steps taken and schedule parameters.
[ "Computes", "multiplier", "for", "social_curiosity", "reward", "based", "on", "training", "steps", "taken", "and", "schedule", "parameters", "." ]
def compute_curiosity_reward_weight(self): weight = np.interp( self.timestep, self.curiosity_reward_schedule_steps, self.curiosity_reward_schedule_weights, ) return weight * self.baseline_curiosity_reward_weight
[ "def", "compute_curiosity_reward_weight", "(", "self", ")", ":", "weight", "=", "np", ".", "interp", "(", "self", ".", "timestep", ",", "self", ".", "curiosity_reward_schedule_steps", ",", "self", ".", "curiosity_reward_schedule_weights", ",", ")", "return", "weig...
Computes multiplier for social_curiosity reward based on training steps taken and schedule parameters.
[ "Computes", "multiplier", "for", "social_curiosity", "reward", "based", "on", "training", "steps", "taken", "and", "schedule", "parameters", "." ]
[ "\"\"\" Computes multiplier for social_curiosity reward based on training steps\n taken and schedule parameters.\n \"\"\"" ]
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
0c7b2e08c3e5be643b4bec0599ea7bf635fed5c6
eugenevinitsky/sequential_social_dilemma_games
algorithms/common_funcs_scm.py
[ "MIT" ]
Python
weigh_and_add_curiosity_reward
<not_specific>
def weigh_and_add_curiosity_reward(policy, sample_batch): """Compute curiosity of this agent and add to rewards. """ cur_curiosity_reward_weight = policy.compute_curiosity_reward_weight() # Align the reward, as the reward for timestep n is calculated at timestep n+1. curiosity_reward = np.concatenat...
Compute curiosity of this agent and add to rewards.
Compute curiosity of this agent and add to rewards.
[ "Compute", "curiosity", "of", "this", "agent", "and", "add", "to", "rewards", "." ]
def weigh_and_add_curiosity_reward(policy, sample_batch): cur_curiosity_reward_weight = policy.compute_curiosity_reward_weight() curiosity_reward = np.concatenate((sample_batch[SOCIAL_CURIOSITY_REWARD][1:], [0])) reward = np.clip(curiosity_reward, -policy.curiosity_reward_clip, policy.curiosity_reward_clip)...
[ "def", "weigh_and_add_curiosity_reward", "(", "policy", ",", "sample_batch", ")", ":", "cur_curiosity_reward_weight", "=", "policy", ".", "compute_curiosity_reward_weight", "(", ")", "curiosity_reward", "=", "np", ".", "concatenate", "(", "(", "sample_batch", "[", "SO...
Compute curiosity of this agent and add to rewards.
[ "Compute", "curiosity", "of", "this", "agent", "and", "add", "to", "rewards", "." ]
[ "\"\"\"Compute curiosity of this agent and add to rewards.\n \"\"\"", "# Align the reward, as the reward for timestep n is calculated at timestep n+1.", "# Clip curiosity reward", "# Add to trajectory" ]
[ { "param": "policy", "type": null }, { "param": "sample_batch", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "policy", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "sample_batch", "type": null, "docstring": null, "docstring_...
039f1bbaedcf4cc61ebdd92b168649a6bc1d2943
eugenevinitsky/sequential_social_dilemma_games
social_dilemmas/envs/map_env.py
[ "MIT" ]
Python
ascii_to_numpy
<not_specific>
def ascii_to_numpy(self, ascii_list): """converts a list of strings into a numpy array Parameters ---------- ascii_list: list of strings List describing what the map should look like Returns ------- arr: np.ndarray numpy array describing ...
converts a list of strings into a numpy array Parameters ---------- ascii_list: list of strings List describing what the map should look like Returns ------- arr: np.ndarray numpy array describing the map with ' ' indicating an empty space ...
converts a list of strings into a numpy array Parameters list of strings List describing what the map should look like Returns np.ndarray numpy array describing the map with ' ' indicating an empty space
[ "converts", "a", "list", "of", "strings", "into", "a", "numpy", "array", "Parameters", "list", "of", "strings", "List", "describing", "what", "the", "map", "should", "look", "like", "Returns", "np", ".", "ndarray", "numpy", "array", "describing", "the", "map...
def ascii_to_numpy(self, ascii_list): arr = np.full((len(ascii_list), len(ascii_list[0])), b" ", dtype="c") for row in range(arr.shape[0]): for col in range(arr.shape[1]): arr[row, col] = ascii_list[row][col] return arr
[ "def", "ascii_to_numpy", "(", "self", ",", "ascii_list", ")", ":", "arr", "=", "np", ".", "full", "(", "(", "len", "(", "ascii_list", ")", ",", "len", "(", "ascii_list", "[", "0", "]", ")", ")", ",", "b\" \"", ",", "dtype", "=", "\"c\"", ")", "fo...
converts a list of strings into a numpy array Parameters
[ "converts", "a", "list", "of", "strings", "into", "a", "numpy", "array", "Parameters" ]
[ "\"\"\"converts a list of strings into a numpy array\n\n\n Parameters\n ----------\n ascii_list: list of strings\n List describing what the map should look like\n Returns\n -------\n arr: np.ndarray\n numpy array describing the map with ' ' indicating ...
[ { "param": "self", "type": null }, { "param": "ascii_list", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "ascii_list", "type": null, "docstring": null, "docstring_toke...
039f1bbaedcf4cc61ebdd92b168649a6bc1d2943
eugenevinitsky/sequential_social_dilemma_games
social_dilemmas/envs/map_env.py
[ "MIT" ]
Python
step
<not_specific>
def step(self, actions): """Takes in a dict of actions and converts them to a map update Parameters ---------- actions: dict {agent-id: int} dict of actions, keyed by agent-id that are passed to the agent. The agent interprets the int and converts it to a command...
Takes in a dict of actions and converts them to a map update Parameters ---------- actions: dict {agent-id: int} dict of actions, keyed by agent-id that are passed to the agent. The agent interprets the int and converts it to a command Returns ------- ...
Takes in a dict of actions and converts them to a map update Parameters dict {agent-id: int} dict of actions, keyed by agent-id that are passed to the agent. The agent interprets the int and converts it to a command Returns dict of arrays representing agent observations rewards: dict of rewards for each agent dones:...
[ "Takes", "in", "a", "dict", "of", "actions", "and", "converts", "them", "to", "a", "map", "update", "Parameters", "dict", "{", "agent", "-", "id", ":", "int", "}", "dict", "of", "actions", "keyed", "by", "agent", "-", "id", "that", "are", "passed", "...
def step(self, actions): self.beam_pos = [] agent_actions = {} for agent_id, action in actions.items(): agent_action = self.agents[agent_id].action_map(action) agent_actions[agent_id] = agent_action for agent in self.agents.values(): row, col = agent.p...
[ "def", "step", "(", "self", ",", "actions", ")", ":", "self", ".", "beam_pos", "=", "[", "]", "agent_actions", "=", "{", "}", "for", "agent_id", ",", "action", "in", "actions", ".", "items", "(", ")", ":", "agent_action", "=", "self", ".", "agents", ...
Takes in a dict of actions and converts them to a map update Parameters
[ "Takes", "in", "a", "dict", "of", "actions", "and", "converts", "them", "to", "a", "map", "update", "Parameters" ]
[ "\"\"\"Takes in a dict of actions and converts them to a map update\n\n Parameters\n ----------\n actions: dict {agent-id: int}\n dict of actions, keyed by agent-id that are passed to the agent. The agent\n interprets the int and converts it to a command\n\n Returns...
[ { "param": "self", "type": null }, { "param": "actions", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "actions", "type": null, "docstring": null, "docstring_tokens"...
039f1bbaedcf4cc61ebdd92b168649a6bc1d2943
eugenevinitsky/sequential_social_dilemma_games
social_dilemmas/envs/map_env.py
[ "MIT" ]
Python
reset
<not_specific>
def reset(self): """Reset the environment. This method is performed in between rollouts. It resets the state of the environment. Returns ------- observation: dict of numpy ndarray the initial observation of the space. The initial reward is assumed ...
Reset the environment. This method is performed in between rollouts. It resets the state of the environment. Returns ------- observation: dict of numpy ndarray the initial observation of the space. The initial reward is assumed to be zero.
Reset the environment. This method is performed in between rollouts. It resets the state of the environment. Returns dict of numpy ndarray the initial observation of the space. The initial reward is assumed to be zero.
[ "Reset", "the", "environment", ".", "This", "method", "is", "performed", "in", "between", "rollouts", ".", "It", "resets", "the", "state", "of", "the", "environment", ".", "Returns", "dict", "of", "numpy", "ndarray", "the", "initial", "observation", "of", "t...
def reset(self): self.beam_pos = [] self.agents = {} self.setup_agents() self.reset_map() self.custom_map_update() map_with_agents = self.get_map_with_agents() observations = {} for agent in self.agents.values(): agent.full_map = map_with_agent...
[ "def", "reset", "(", "self", ")", ":", "self", ".", "beam_pos", "=", "[", "]", "self", ".", "agents", "=", "{", "}", "self", ".", "setup_agents", "(", ")", "self", ".", "reset_map", "(", ")", "self", ".", "custom_map_update", "(", ")", "map_with_agen...
Reset the environment.
[ "Reset", "the", "environment", "." ]
[ "\"\"\"Reset the environment.\n\n This method is performed in between rollouts. It resets the state of\n the environment.\n\n Returns\n -------\n observation: dict of numpy ndarray\n the initial observation of the space. The initial reward is assumed\n to be ...
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
039f1bbaedcf4cc61ebdd92b168649a6bc1d2943
eugenevinitsky/sequential_social_dilemma_games
social_dilemmas/envs/map_env.py
[ "MIT" ]
Python
check_agent_map
<not_specific>
def check_agent_map(self, agent_map): """Checks the map to make sure agents aren't duplicated""" unique, counts = np.unique(agent_map, return_counts=True) count_dict = dict(zip(unique, counts)) # check for multiple agents for i in range(self.num_agents): if count_dic...
Checks the map to make sure agents aren't duplicated
Checks the map to make sure agents aren't duplicated
[ "Checks", "the", "map", "to", "make", "sure", "agents", "aren", "'", "t", "duplicated" ]
def check_agent_map(self, agent_map): unique, counts = np.unique(agent_map, return_counts=True) count_dict = dict(zip(unique, counts)) for i in range(self.num_agents): if count_dict[chr(i + 1)] != 1: print("Error! Wrong number of agent", i, "in map!") ...
[ "def", "check_agent_map", "(", "self", ",", "agent_map", ")", ":", "unique", ",", "counts", "=", "np", ".", "unique", "(", "agent_map", ",", "return_counts", "=", "True", ")", "count_dict", "=", "dict", "(", "zip", "(", "unique", ",", "counts", ")", ")...
Checks the map to make sure agents aren't duplicated
[ "Checks", "the", "map", "to", "make", "sure", "agents", "aren", "'", "t", "duplicated" ]
[ "\"\"\"Checks the map to make sure agents aren't duplicated\"\"\"", "# check for multiple agents" ]
[ { "param": "self", "type": null }, { "param": "agent_map", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "agent_map", "type": null, "docstring": null, "docstring_token...
039f1bbaedcf4cc61ebdd92b168649a6bc1d2943
eugenevinitsky/sequential_social_dilemma_games
social_dilemmas/envs/map_env.py
[ "MIT" ]
Python
map_to_colors
<not_specific>
def map_to_colors(self, mmap, color_map, rgb_arr, orientation="UP"): """Converts a map to an array of RGB values. Parameters ---------- mmap: np.ndarray map to convert to colors Double m to avoid shadowing map. color_map: dict mapping between a...
Converts a map to an array of RGB values. Parameters ---------- mmap: np.ndarray map to convert to colors Double m to avoid shadowing map. color_map: dict mapping between array elements and desired colors rgb_arr: np.array Variable ...
Converts a map to an array of RGB values. Parameters np.ndarray map to convert to colors Double m to avoid shadowing map. color_map: dict mapping between array elements and desired colors rgb_arr: np.array Variable to store the mapping in orientation: The way in which the output should be oriented. UP = no rotation. R...
[ "Converts", "a", "map", "to", "an", "array", "of", "RGB", "values", ".", "Parameters", "np", ".", "ndarray", "map", "to", "convert", "to", "colors", "Double", "m", "to", "avoid", "shadowing", "map", ".", "color_map", ":", "dict", "mapping", "between", "a...
def map_to_colors(self, mmap, color_map, rgb_arr, orientation="UP"): x_len = mmap.shape[0] y_len = mmap.shape[1] if orientation == "UP": for row_elem in range(x_len): for col_elem in range(y_len): rgb_arr[row_elem, col_elem, :] = color_map[mmap[row...
[ "def", "map_to_colors", "(", "self", ",", "mmap", ",", "color_map", ",", "rgb_arr", ",", "orientation", "=", "\"UP\"", ")", ":", "x_len", "=", "mmap", ".", "shape", "[", "0", "]", "y_len", "=", "mmap", ".", "shape", "[", "1", "]", "if", "orientation"...
Converts a map to an array of RGB values.
[ "Converts", "a", "map", "to", "an", "array", "of", "RGB", "values", "." ]
[ "\"\"\"Converts a map to an array of RGB values.\n Parameters\n ----------\n mmap: np.ndarray\n map to convert to colors\n Double m to avoid shadowing map.\n color_map: dict\n mapping between array elements and desired colors\n rgb_arr: np.array\n ...
[ { "param": "self", "type": null }, { "param": "mmap", "type": null }, { "param": "color_map", "type": null }, { "param": "rgb_arr", "type": null }, { "param": "orientation", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "mmap", "type": null, "docstring": null, "docstring_tokens": [...
039f1bbaedcf4cc61ebdd92b168649a6bc1d2943
eugenevinitsky/sequential_social_dilemma_games
social_dilemmas/envs/map_env.py
[ "MIT" ]
Python
render
null
def render(self, filename=None): """ Creates an image of the map to plot or save. Args: filename: If a string is passed, will save the image to disk at this location. """ rgb_arr = self.full_map_to_colors() plt.cla() plt.imshow(rgb_arr, ...
Creates an image of the map to plot or save. Args: filename: If a string is passed, will save the image to disk at this location.
Creates an image of the map to plot or save.
[ "Creates", "an", "image", "of", "the", "map", "to", "plot", "or", "save", "." ]
def render(self, filename=None): rgb_arr = self.full_map_to_colors() plt.cla() plt.imshow(rgb_arr, interpolation="nearest") if filename is None: plt.show() else: plt.savefig(filename)
[ "def", "render", "(", "self", ",", "filename", "=", "None", ")", ":", "rgb_arr", "=", "self", ".", "full_map_to_colors", "(", ")", "plt", ".", "cla", "(", ")", "plt", ".", "imshow", "(", "rgb_arr", ",", "interpolation", "=", "\"nearest\"", ")", "if", ...
Creates an image of the map to plot or save.
[ "Creates", "an", "image", "of", "the", "map", "to", "plot", "or", "save", "." ]
[ "\"\"\" Creates an image of the map to plot or save.\n\n Args:\n filename: If a string is passed, will save the image\n to disk at this location.\n \"\"\"" ]
[ { "param": "self", "type": null }, { "param": "filename", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "filename", "type": null, "docstring": "If a string is passed, will ...
039f1bbaedcf4cc61ebdd92b168649a6bc1d2943
eugenevinitsky/sequential_social_dilemma_games
social_dilemmas/envs/map_env.py
[ "MIT" ]
Python
update_moves
null
def update_moves(self, agent_actions): """Converts agent action tuples into a new map and new agent positions. Also resolves conflicts over multiple agents wanting a cell. This method works by finding all conflicts over a cell and randomly assigning them to one of the agents that desires...
Converts agent action tuples into a new map and new agent positions. Also resolves conflicts over multiple agents wanting a cell. This method works by finding all conflicts over a cell and randomly assigning them to one of the agents that desires the slot. It then sets all of the other agents ...
Converts agent action tuples into a new map and new agent positions. Also resolves conflicts over multiple agents wanting a cell. This method works by finding all conflicts over a cell and randomly assigning them to one of the agents that desires the slot. It then sets all of the other agents that wanted the cell to h...
[ "Converts", "agent", "action", "tuples", "into", "a", "new", "map", "and", "new", "agent", "positions", ".", "Also", "resolves", "conflicts", "over", "multiple", "agents", "wanting", "a", "cell", ".", "This", "method", "works", "by", "finding", "all", "confl...
def update_moves(self, agent_actions): reserved_slots = [] for agent_id, action in agent_actions.items(): agent = self.agents[agent_id] selected_action = self.all_actions[action] if "MOVE" in action or "STAY" in action: rot_action = self.rotate_action(...
[ "def", "update_moves", "(", "self", ",", "agent_actions", ")", ":", "reserved_slots", "=", "[", "]", "for", "agent_id", ",", "action", "in", "agent_actions", ".", "items", "(", ")", ":", "agent", "=", "self", ".", "agents", "[", "agent_id", "]", "selecte...
Converts agent action tuples into a new map and new agent positions.
[ "Converts", "agent", "action", "tuples", "into", "a", "new", "map", "and", "new", "agent", "positions", "." ]
[ "\"\"\"Converts agent action tuples into a new map and new agent positions.\n Also resolves conflicts over multiple agents wanting a cell.\n\n This method works by finding all conflicts over a cell and randomly assigning them\n to one of the agents that desires the slot. It then sets all of the ...
[ { "param": "self", "type": null }, { "param": "agent_actions", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "agent_actions", "type": null, "docstring": null, "docstring_t...
039f1bbaedcf4cc61ebdd92b168649a6bc1d2943
eugenevinitsky/sequential_social_dilemma_games
social_dilemmas/envs/map_env.py
[ "MIT" ]
Python
update_map
null
def update_map(self, new_points): """For points in new_points, place desired char on the map Update the color map as well""" for point in new_points: self.single_update_map(*point)
For points in new_points, place desired char on the map Update the color map as well
For points in new_points, place desired char on the map Update the color map as well
[ "For", "points", "in", "new_points", "place", "desired", "char", "on", "the", "map", "Update", "the", "color", "map", "as", "well" ]
def update_map(self, new_points): for point in new_points: self.single_update_map(*point)
[ "def", "update_map", "(", "self", ",", "new_points", ")", ":", "for", "point", "in", "new_points", ":", "self", ".", "single_update_map", "(", "*", "point", ")" ]
For points in new_points, place desired char on the map Update the color map as well
[ "For", "points", "in", "new_points", "place", "desired", "char", "on", "the", "map", "Update", "the", "color", "map", "as", "well" ]
[ "\"\"\"For points in new_points, place desired char on the map\n Update the color map as well\"\"\"" ]
[ { "param": "self", "type": null }, { "param": "new_points", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "new_points", "type": null, "docstring": null, "docstring_toke...
039f1bbaedcf4cc61ebdd92b168649a6bc1d2943
eugenevinitsky/sequential_social_dilemma_games
social_dilemmas/envs/map_env.py
[ "MIT" ]
Python
reset_map
null
def reset_map(self): """Resets the map to be empty as well as a custom reset set by subclasses""" self.world_map = np.full((len(self.base_map), len(self.base_map[0])), b" ", dtype="c") self.world_map_color = np.full( (len(self.base_map) + self.view_len * 2, len(self.base_map[0]) + se...
Resets the map to be empty as well as a custom reset set by subclasses
Resets the map to be empty as well as a custom reset set by subclasses
[ "Resets", "the", "map", "to", "be", "empty", "as", "well", "as", "a", "custom", "reset", "set", "by", "subclasses" ]
def reset_map(self): self.world_map = np.full((len(self.base_map), len(self.base_map[0])), b" ", dtype="c") self.world_map_color = np.full( (len(self.base_map) + self.view_len * 2, len(self.base_map[0]) + self.view_len * 2, 3), fill_value=0, dtype=np.uint8, ) ...
[ "def", "reset_map", "(", "self", ")", ":", "self", ".", "world_map", "=", "np", ".", "full", "(", "(", "len", "(", "self", ".", "base_map", ")", ",", "len", "(", "self", ".", "base_map", "[", "0", "]", ")", ")", ",", "b\" \"", ",", "dtype", "="...
Resets the map to be empty as well as a custom reset set by subclasses
[ "Resets", "the", "map", "to", "be", "empty", "as", "well", "as", "a", "custom", "reset", "set", "by", "subclasses" ]
[ "\"\"\"Resets the map to be empty as well as a custom reset set by subclasses\"\"\"" ]
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
039f1bbaedcf4cc61ebdd92b168649a6bc1d2943
eugenevinitsky/sequential_social_dilemma_games
social_dilemmas/envs/map_env.py
[ "MIT" ]
Python
update_map_fire
<not_specific>
def update_map_fire( self, firing_pos, firing_orientation, fire_len, fire_char, cell_types=[], update_char=[], blocking_cells=b"P", beam_width=3, ): """From a firing position, fire a beam that may clean or hit agents Notes: ...
From a firing position, fire a beam that may clean or hit agents Notes: (1) Beams are blocked by agents (2) A beam travels along until it hits a blocking cell at which beam the beam covers that cell and stops (3) If a beam hits a cell whose character is in ce...
From a firing position, fire a beam that may clean or hit agents Notes: (1) Beams are blocked by agents (2) A beam travels along until it hits a blocking cell at which beam the beam covers that cell and stops (3) If a beam hits a cell whose character is in cell_types, it replaces it with the corresponding index in upda...
[ "From", "a", "firing", "position", "fire", "a", "beam", "that", "may", "clean", "or", "hit", "agents", "Notes", ":", "(", "1", ")", "Beams", "are", "blocked", "by", "agents", "(", "2", ")", "A", "beam", "travels", "along", "until", "it", "hits", "a",...
def update_map_fire( self, firing_pos, firing_orientation, fire_len, fire_char, cell_types=[], update_char=[], blocking_cells=b"P", beam_width=3, ): agent_by_pos = {tuple(agent.pos): agent_id for agent_id, agent in self.agents.items()} ...
[ "def", "update_map_fire", "(", "self", ",", "firing_pos", ",", "firing_orientation", ",", "fire_len", ",", "fire_char", ",", "cell_types", "=", "[", "]", ",", "update_char", "=", "[", "]", ",", "blocking_cells", "=", "b\"P\"", ",", "beam_width", "=", "3", ...
From a firing position, fire a beam that may clean or hit agents Notes: (1) Beams are blocked by agents (2) A beam travels along until it hits a blocking cell at which beam the beam covers that cell and stops (3) If a beam hits a cell whose character is in cell_types, it replaces it with the corresponding index in upda...
[ "From", "a", "firing", "position", "fire", "a", "beam", "that", "may", "clean", "or", "hit", "agents", "Notes", ":", "(", "1", ")", "Beams", "are", "blocked", "by", "agents", "(", "2", ")", "A", "beam", "travels", "along", "until", "it", "hits", "a",...
[ "\"\"\"From a firing position, fire a beam that may clean or hit agents\n\n Notes:\n (1) Beams are blocked by agents\n (2) A beam travels along until it hits a blocking cell at which beam the beam\n covers that cell and stops\n (3) If a beam hits a cell whose c...
[ { "param": "self", "type": null }, { "param": "firing_pos", "type": null }, { "param": "firing_orientation", "type": null }, { "param": "fire_len", "type": null }, { "param": "fire_char", "type": null }, { "param": "cell_types", "type": null }, ...
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "firing_pos", "type": null, "docstring": null, "docstring_toke...
039f1bbaedcf4cc61ebdd92b168649a6bc1d2943
eugenevinitsky/sequential_social_dilemma_games
social_dilemmas/envs/map_env.py
[ "MIT" ]
Python
spawn_point
<not_specific>
def spawn_point(self): """Returns a randomly selected spawn point.""" spawn_index = 0 is_free_cell = False curr_agent_pos = [agent.pos.tolist() for agent in self.agents.values()] random.shuffle(self.spawn_points) for i, spawn_point in enumerate(self.spawn_points): ...
Returns a randomly selected spawn point.
Returns a randomly selected spawn point.
[ "Returns", "a", "randomly", "selected", "spawn", "point", "." ]
def spawn_point(self): spawn_index = 0 is_free_cell = False curr_agent_pos = [agent.pos.tolist() for agent in self.agents.values()] random.shuffle(self.spawn_points) for i, spawn_point in enumerate(self.spawn_points): if [spawn_point[0], spawn_point[1]] not in curr_ag...
[ "def", "spawn_point", "(", "self", ")", ":", "spawn_index", "=", "0", "is_free_cell", "=", "False", "curr_agent_pos", "=", "[", "agent", ".", "pos", ".", "tolist", "(", ")", "for", "agent", "in", "self", ".", "agents", ".", "values", "(", ")", "]", "...
Returns a randomly selected spawn point.
[ "Returns", "a", "randomly", "selected", "spawn", "point", "." ]
[ "\"\"\"Returns a randomly selected spawn point.\"\"\"" ]
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
039f1bbaedcf4cc61ebdd92b168649a6bc1d2943
eugenevinitsky/sequential_social_dilemma_games
social_dilemmas/envs/map_env.py
[ "MIT" ]
Python
find_visible_agents
<not_specific>
def find_visible_agents(self, agent_id): """Returns all the agents that can be seen by agent with agent_id Args ---- agent_id: str The id of the agent whose visible agents we are asking about Returns ------- visible_agents: list which agent...
Returns all the agents that can be seen by agent with agent_id Args ---- agent_id: str The id of the agent whose visible agents we are asking about Returns ------- visible_agents: list which agents can be seen by the agent with id "agent_id" ...
Returns all the agents that can be seen by agent with agent_id Args str The id of the agent whose visible agents we are asking about Returns list which agents can be seen by the agent with id "agent_id"
[ "Returns", "all", "the", "agents", "that", "can", "be", "seen", "by", "agent", "with", "agent_id", "Args", "str", "The", "id", "of", "the", "agent", "whose", "visible", "agents", "we", "are", "asking", "about", "Returns", "list", "which", "agents", "can", ...
def find_visible_agents(self, agent_id): agent_pos = self.agents[agent_id].pos upper_lim = int(agent_pos[0] + self.agents[agent_id].row_size) lower_lim = int(agent_pos[0] - self.agents[agent_id].row_size) left_lim = int(agent_pos[1] - self.agents[agent_id].col_size) right_lim = i...
[ "def", "find_visible_agents", "(", "self", ",", "agent_id", ")", ":", "agent_pos", "=", "self", ".", "agents", "[", "agent_id", "]", ".", "pos", "upper_lim", "=", "int", "(", "agent_pos", "[", "0", "]", "+", "self", ".", "agents", "[", "agent_id", "]",...
Returns all the agents that can be seen by agent with agent_id Args
[ "Returns", "all", "the", "agents", "that", "can", "be", "seen", "by", "agent", "with", "agent_id", "Args" ]
[ "\"\"\"Returns all the agents that can be seen by agent with agent_id\n Args\n ----\n agent_id: str\n The id of the agent whose visible agents we are asking about\n Returns\n -------\n visible_agents: list\n which agents can be seen by the agent with i...
[ { "param": "self", "type": null }, { "param": "agent_id", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "agent_id", "type": null, "docstring": null, "docstring_tokens...
91d04eef66c75d6a8cd200d4e79d419ebef6301a
eugenevinitsky/sequential_social_dilemma_games
algorithms/impala_moa.py
[ "MIT" ]
Python
_make_time_major
<not_specific>
def _make_time_major(policy, seq_lens, tensor, drop_last=False): """Swaps batch and trajectory axis. Arguments: policy: Policy reference seq_lens: Sequence lengths if recurrent or None tensor: A tensor or list of tensors to reshape. drop_last: A bool indicating whether to drop t...
Swaps batch and trajectory axis. Arguments: policy: Policy reference seq_lens: Sequence lengths if recurrent or None tensor: A tensor or list of tensors to reshape. drop_last: A bool indicating whether to drop the last trajectory item. Returns: res: A tensor wit...
Swaps batch and trajectory axis. Arguments: policy: Policy reference seq_lens: Sequence lengths if recurrent or None tensor: A tensor or list of tensors to reshape. drop_last: A bool indicating whether to drop the last trajectory item. A tensor with swapped axes or a list of tensors with swapped axes.
[ "Swaps", "batch", "and", "trajectory", "axis", ".", "Arguments", ":", "policy", ":", "Policy", "reference", "seq_lens", ":", "Sequence", "lengths", "if", "recurrent", "or", "None", "tensor", ":", "A", "tensor", "or", "list", "of", "tensors", "to", "reshape",...
def _make_time_major(policy, seq_lens, tensor, drop_last=False): if isinstance(tensor, list): return [_make_time_major(policy, seq_lens, t, drop_last) for t in tensor] if policy.is_recurrent(): B = tf.shape(seq_lens)[0] T = tf.shape(tensor)[0] // B else: T = policy.config["ro...
[ "def", "_make_time_major", "(", "policy", ",", "seq_lens", ",", "tensor", ",", "drop_last", "=", "False", ")", ":", "if", "isinstance", "(", "tensor", ",", "list", ")", ":", "return", "[", "_make_time_major", "(", "policy", ",", "seq_lens", ",", "t", ","...
Swaps batch and trajectory axis.
[ "Swaps", "batch", "and", "trajectory", "axis", "." ]
[ "\"\"\"Swaps batch and trajectory axis.\n\n Arguments:\n policy: Policy reference\n seq_lens: Sequence lengths if recurrent or None\n tensor: A tensor or list of tensors to reshape.\n drop_last: A bool indicating whether to drop the last\n trajectory item.\n\n Returns:\n ...
[ { "param": "policy", "type": null }, { "param": "seq_lens", "type": null }, { "param": "tensor", "type": null }, { "param": "drop_last", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "policy", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "seq_lens", "type": null, "docstring": null, "docstring_toke...
1aab01bb575856ae6deec27233d6fe81b1901184
eugenevinitsky/sequential_social_dilemma_games
models/moa_lstm.py
[ "MIT" ]
Python
forward_rnn
<not_specific>
def forward_rnn(self, input_dict, state, seq_lens): """ Forward pass through the MOA LSTM. :param input_dict: The input tensors. :param state: The model state. :param seq_lens: LSTM sequence lengths. :return: The MOA predictions and new state. """ rnn_inpu...
Forward pass through the MOA LSTM. :param input_dict: The input tensors. :param state: The model state. :param seq_lens: LSTM sequence lengths. :return: The MOA predictions and new state.
Forward pass through the MOA LSTM.
[ "Forward", "pass", "through", "the", "MOA", "LSTM", "." ]
def forward_rnn(self, input_dict, state, seq_lens): rnn_input = [input_dict["curr_obs"], seq_lens] + state rnn_input.insert(1, input_dict["prev_total_actions"]) model_out, h, c = self.rnn_model(rnn_input) return model_out, h, c
[ "def", "forward_rnn", "(", "self", ",", "input_dict", ",", "state", ",", "seq_lens", ")", ":", "rnn_input", "=", "[", "input_dict", "[", "\"curr_obs\"", "]", ",", "seq_lens", "]", "+", "state", "rnn_input", ".", "insert", "(", "1", ",", "input_dict", "["...
Forward pass through the MOA LSTM.
[ "Forward", "pass", "through", "the", "MOA", "LSTM", "." ]
[ "\"\"\"\n Forward pass through the MOA LSTM.\n :param input_dict: The input tensors.\n :param state: The model state.\n :param seq_lens: LSTM sequence lengths.\n :return: The MOA predictions and new state.\n \"\"\"" ]
[ { "param": "self", "type": null }, { "param": "input_dict", "type": null }, { "param": "state", "type": null }, { "param": "seq_lens", "type": null } ]
{ "returns": [ { "docstring": "The MOA predictions and new state.", "docstring_tokens": [ "The", "MOA", "predictions", "and", "new", "state", "." ], "type": null } ], "raises": [], "params": [ { "identifier": "self...
9aaa70882d69b906827c7c7efe9bc06d3a998f46
eugenevinitsky/sequential_social_dilemma_games
algorithms/ppo_scm.py
[ "MIT" ]
Python
extra_scm_fetches
<not_specific>
def extra_scm_fetches(policy): """ Adds value function, logits, moa predictions, SCM loss/reward to experience train_batches. :return: Updated fetches """ ppo_fetches = extra_moa_fetches(policy) ppo_fetches.update(scm_fetches(policy)) return ppo_fetches
Adds value function, logits, moa predictions, SCM loss/reward to experience train_batches. :return: Updated fetches
Adds value function, logits, moa predictions, SCM loss/reward to experience train_batches.
[ "Adds", "value", "function", "logits", "moa", "predictions", "SCM", "loss", "/", "reward", "to", "experience", "train_batches", "." ]
def extra_scm_fetches(policy): ppo_fetches = extra_moa_fetches(policy) ppo_fetches.update(scm_fetches(policy)) return ppo_fetches
[ "def", "extra_scm_fetches", "(", "policy", ")", ":", "ppo_fetches", "=", "extra_moa_fetches", "(", "policy", ")", "ppo_fetches", ".", "update", "(", "scm_fetches", "(", "policy", ")", ")", "return", "ppo_fetches" ]
Adds value function, logits, moa predictions, SCM loss/reward to experience train_batches.
[ "Adds", "value", "function", "logits", "moa", "predictions", "SCM", "loss", "/", "reward", "to", "experience", "train_batches", "." ]
[ "\"\"\"\n Adds value function, logits, moa predictions, SCM loss/reward to experience train_batches.\n :return: Updated fetches\n \"\"\"" ]
[ { "param": "policy", "type": null } ]
{ "returns": [ { "docstring": null, "docstring_tokens": [ "None" ], "type": null } ], "raises": [], "params": [ { "identifier": "policy", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null ...
9aaa70882d69b906827c7c7efe9bc06d3a998f46
eugenevinitsky/sequential_social_dilemma_games
algorithms/ppo_scm.py
[ "MIT" ]
Python
postprocess_ppo_scm
<not_specific>
def postprocess_ppo_scm(policy, sample_batch, other_agent_batches=None, episode=None): """ Add the influence and curiosity reward to the trajectory. Then, add the policy logits, VF preds, and advantages to the trajectory. :return: Updated trajectory (batch) """ batch = moa_postprocess_trajectory...
Add the influence and curiosity reward to the trajectory. Then, add the policy logits, VF preds, and advantages to the trajectory. :return: Updated trajectory (batch)
Add the influence and curiosity reward to the trajectory. Then, add the policy logits, VF preds, and advantages to the trajectory.
[ "Add", "the", "influence", "and", "curiosity", "reward", "to", "the", "trajectory", ".", "Then", "add", "the", "policy", "logits", "VF", "preds", "and", "advantages", "to", "the", "trajectory", "." ]
def postprocess_ppo_scm(policy, sample_batch, other_agent_batches=None, episode=None): batch = moa_postprocess_trajectory(policy, sample_batch) batch = scm_postprocess_trajectory(policy, batch) batch = postprocess_ppo_gae(policy, batch) return batch
[ "def", "postprocess_ppo_scm", "(", "policy", ",", "sample_batch", ",", "other_agent_batches", "=", "None", ",", "episode", "=", "None", ")", ":", "batch", "=", "moa_postprocess_trajectory", "(", "policy", ",", "sample_batch", ")", "batch", "=", "scm_postprocess_tr...
Add the influence and curiosity reward to the trajectory.
[ "Add", "the", "influence", "and", "curiosity", "reward", "to", "the", "trajectory", "." ]
[ "\"\"\"\n Add the influence and curiosity reward to the trajectory.\n Then, add the policy logits, VF preds, and advantages to the trajectory.\n :return: Updated trajectory (batch)\n \"\"\"" ]
[ { "param": "policy", "type": null }, { "param": "sample_batch", "type": null }, { "param": "other_agent_batches", "type": null }, { "param": "episode", "type": null } ]
{ "returns": [ { "docstring": "Updated trajectory (batch)", "docstring_tokens": [ "Updated", "trajectory", "(", "batch", ")" ], "type": null } ], "raises": [], "params": [ { "identifier": "policy", "type": null, "docst...
9aaa70882d69b906827c7c7efe9bc06d3a998f46
eugenevinitsky/sequential_social_dilemma_games
algorithms/ppo_scm.py
[ "MIT" ]
Python
validate_ppo_scm_config
null
def validate_ppo_scm_config(config): """ Validates the PPO+MOA+SCM config :param config: The config to validate """ validate_scm_config(config) validate_moa_config(config) validate_config(config)
Validates the PPO+MOA+SCM config :param config: The config to validate
Validates the PPO+MOA+SCM config
[ "Validates", "the", "PPO", "+", "MOA", "+", "SCM", "config" ]
def validate_ppo_scm_config(config): validate_scm_config(config) validate_moa_config(config) validate_config(config)
[ "def", "validate_ppo_scm_config", "(", "config", ")", ":", "validate_scm_config", "(", "config", ")", "validate_moa_config", "(", "config", ")", "validate_config", "(", "config", ")" ]
Validates the PPO+MOA+SCM config
[ "Validates", "the", "PPO", "+", "MOA", "+", "SCM", "config" ]
[ "\"\"\"\n Validates the PPO+MOA+SCM config\n :param config: The config to validate\n \"\"\"" ]
[ { "param": "config", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "config", "type": null, "docstring": "The config to validate", "docstring_tokens": [ "The", "config", "to", "validate" ], "default": null, "is_optional": null } ], "outl...
9aaa70882d69b906827c7c7efe9bc06d3a998f46
eugenevinitsky/sequential_social_dilemma_games
algorithms/ppo_scm.py
[ "MIT" ]
Python
build_ppo_scm_trainer
<not_specific>
def build_ppo_scm_trainer(scm_config): """ Creates a SCM+MOA+PPO policy class, then creates a trainer with this policy. :param scm_config: The configuration dictionary. :return: A new SCM+MOA+PPO trainer. """ tf.keras.backend.set_floatx("float32") trainer_name = "SCMPPOTrainer" scm_ppo...
Creates a SCM+MOA+PPO policy class, then creates a trainer with this policy. :param scm_config: The configuration dictionary. :return: A new SCM+MOA+PPO trainer.
Creates a SCM+MOA+PPO policy class, then creates a trainer with this policy.
[ "Creates", "a", "SCM", "+", "MOA", "+", "PPO", "policy", "class", "then", "creates", "a", "trainer", "with", "this", "policy", "." ]
def build_ppo_scm_trainer(scm_config): tf.keras.backend.set_floatx("float32") trainer_name = "SCMPPOTrainer" scm_ppo_policy = build_tf_policy( name="SCMPPOTFPolicy", get_default_config=lambda: scm_config, loss_fn=loss_with_scm, make_model=build_model, stats_fn=extra_s...
[ "def", "build_ppo_scm_trainer", "(", "scm_config", ")", ":", "tf", ".", "keras", ".", "backend", ".", "set_floatx", "(", "\"float32\"", ")", "trainer_name", "=", "\"SCMPPOTrainer\"", "scm_ppo_policy", "=", "build_tf_policy", "(", "name", "=", "\"SCMPPOTFPolicy\"", ...
Creates a SCM+MOA+PPO policy class, then creates a trainer with this policy.
[ "Creates", "a", "SCM", "+", "MOA", "+", "PPO", "policy", "class", "then", "creates", "a", "trainer", "with", "this", "policy", "." ]
[ "\"\"\"\n Creates a SCM+MOA+PPO policy class, then creates a trainer with this policy.\n :param scm_config: The configuration dictionary.\n :return: A new SCM+MOA+PPO trainer.\n \"\"\"" ]
[ { "param": "scm_config", "type": null } ]
{ "returns": [ { "docstring": "A new SCM+MOA+PPO trainer.", "docstring_tokens": [ "A", "new", "SCM", "+", "MOA", "+", "PPO", "trainer", "." ], "type": null } ], "raises": [], "params": [ { "identifi...
d4ed970da1a44133f90c8c4f3afed06ffdbb2f34
eugenevinitsky/sequential_social_dilemma_games
models/baseline_model.py
[ "MIT" ]
Python
forward
<not_specific>
def forward(self, input_dict, state, seq_lens): """ Evaluate the model. Adds time dimension to batch before sending inputs to forward_rnn() :param input_dict: The input tensors. :param state: The model state. :param seq_lens: LSTM sequence lengths. :return: The po...
Evaluate the model. Adds time dimension to batch before sending inputs to forward_rnn() :param input_dict: The input tensors. :param state: The model state. :param seq_lens: LSTM sequence lengths. :return: The policy logits and state.
Evaluate the model. Adds time dimension to batch before sending inputs to forward_rnn()
[ "Evaluate", "the", "model", ".", "Adds", "time", "dimension", "to", "batch", "before", "sending", "inputs", "to", "forward_rnn", "()" ]
def forward(self, input_dict, state, seq_lens): trunk = self.encoder_model(input_dict["obs"]["curr_obs"]) new_dict = {"curr_obs": add_time_dimension(trunk, seq_lens)} output, new_state = self.forward_rnn(new_dict, state, seq_lens) return tf.reshape(output, [-1, self.num_outputs]), new_st...
[ "def", "forward", "(", "self", ",", "input_dict", ",", "state", ",", "seq_lens", ")", ":", "trunk", "=", "self", ".", "encoder_model", "(", "input_dict", "[", "\"obs\"", "]", "[", "\"curr_obs\"", "]", ")", "new_dict", "=", "{", "\"curr_obs\"", ":", "add_...
Evaluate the model.
[ "Evaluate", "the", "model", "." ]
[ "\"\"\"\n Evaluate the model.\n Adds time dimension to batch before sending inputs to forward_rnn()\n :param input_dict: The input tensors.\n :param state: The model state.\n :param seq_lens: LSTM sequence lengths.\n :return: The policy logits and state.\n \"\"\"" ]
[ { "param": "self", "type": null }, { "param": "input_dict", "type": null }, { "param": "state", "type": null }, { "param": "seq_lens", "type": null } ]
{ "returns": [ { "docstring": "The policy logits and state.", "docstring_tokens": [ "The", "policy", "logits", "and", "state", "." ], "type": null } ], "raises": [], "params": [ { "identifier": "self", "type": null, ...
d4ed970da1a44133f90c8c4f3afed06ffdbb2f34
eugenevinitsky/sequential_social_dilemma_games
models/baseline_model.py
[ "MIT" ]
Python
forward_rnn
<not_specific>
def forward_rnn(self, input_dict, state, seq_lens): """ Forward pass through the LSTM. Implicitly assigns the value function output to self_value_out, and does not return this. :param input_dict: The input tensors. :param state: The model state. :param seq_lens: LSTM sequ...
Forward pass through the LSTM. Implicitly assigns the value function output to self_value_out, and does not return this. :param input_dict: The input tensors. :param state: The model state. :param seq_lens: LSTM sequence lengths. :return: The policy logits and new state....
Forward pass through the LSTM. Implicitly assigns the value function output to self_value_out, and does not return this.
[ "Forward", "pass", "through", "the", "LSTM", ".", "Implicitly", "assigns", "the", "value", "function", "output", "to", "self_value_out", "and", "does", "not", "return", "this", "." ]
def forward_rnn(self, input_dict, state, seq_lens): h1, c1 = state (self._model_out, self._value_out, output_h1, output_c1,) = self.policy_model.forward_rnn( input_dict, [h1, c1], seq_lens ) return self._model_out, [output_h1, output_c1]
[ "def", "forward_rnn", "(", "self", ",", "input_dict", ",", "state", ",", "seq_lens", ")", ":", "h1", ",", "c1", "=", "state", "(", "self", ".", "_model_out", ",", "self", ".", "_value_out", ",", "output_h1", ",", "output_c1", ",", ")", "=", "self", "...
Forward pass through the LSTM.
[ "Forward", "pass", "through", "the", "LSTM", "." ]
[ "\"\"\"\n Forward pass through the LSTM.\n Implicitly assigns the value function output to self_value_out, and does not return this.\n :param input_dict: The input tensors.\n :param state: The model state.\n :param seq_lens: LSTM sequence lengths.\n :return: The policy logi...
[ { "param": "self", "type": null }, { "param": "input_dict", "type": null }, { "param": "state", "type": null }, { "param": "seq_lens", "type": null } ]
{ "returns": [ { "docstring": "The policy logits and new state.", "docstring_tokens": [ "The", "policy", "logits", "and", "new", "state", "." ], "type": null } ], "raises": [], "params": [ { "identifier": "self", ...
da2c1e5065ca76e0d9a9922ba232e482bb5d1af0
eugenevinitsky/sequential_social_dilemma_games
algorithms/a3c_moa.py
[ "MIT" ]
Python
postprocess_a3c_moa
<not_specific>
def postprocess_a3c_moa(policy, sample_batch, other_agent_batches=None, episode=None): """Adds the policy logits, VF preds, and advantages to the trajectory.""" batch = moa_postprocess_trajectory(policy, sample_batch) batch = postprocess_advantages(policy, batch) return batch
Adds the policy logits, VF preds, and advantages to the trajectory.
Adds the policy logits, VF preds, and advantages to the trajectory.
[ "Adds", "the", "policy", "logits", "VF", "preds", "and", "advantages", "to", "the", "trajectory", "." ]
def postprocess_a3c_moa(policy, sample_batch, other_agent_batches=None, episode=None): batch = moa_postprocess_trajectory(policy, sample_batch) batch = postprocess_advantages(policy, batch) return batch
[ "def", "postprocess_a3c_moa", "(", "policy", ",", "sample_batch", ",", "other_agent_batches", "=", "None", ",", "episode", "=", "None", ")", ":", "batch", "=", "moa_postprocess_trajectory", "(", "policy", ",", "sample_batch", ")", "batch", "=", "postprocess_advant...
Adds the policy logits, VF preds, and advantages to the trajectory.
[ "Adds", "the", "policy", "logits", "VF", "preds", "and", "advantages", "to", "the", "trajectory", "." ]
[ "\"\"\"Adds the policy logits, VF preds, and advantages to the trajectory.\"\"\"" ]
[ { "param": "policy", "type": null }, { "param": "sample_batch", "type": null }, { "param": "other_agent_batches", "type": null }, { "param": "episode", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "policy", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "sample_batch", "type": null, "docstring": null, "docstring_...
601ec833c8daf89c1e84bc255d13cdd9e02b1a78
eugenevinitsky/sequential_social_dilemma_games
models/scm_model.py
[ "MIT" ]
Python
create_scm_encoder_model
<not_specific>
def create_scm_encoder_model(obs_space, model_config): """ Create the encoder submodel, which is part of the SCM. :param obs_space: A single agent's observation space. :param model_config: The model config dict. :return: A new encoder model. """ original_obs_dims ...
Create the encoder submodel, which is part of the SCM. :param obs_space: A single agent's observation space. :param model_config: The model config dict. :return: A new encoder model.
Create the encoder submodel, which is part of the SCM.
[ "Create", "the", "encoder", "submodel", "which", "is", "part", "of", "the", "SCM", "." ]
def create_scm_encoder_model(obs_space, model_config): original_obs_dims = obs_space.original_space.spaces["curr_obs"].shape input_layer = tf.keras.layers.Input(original_obs_dims, name="observations", dtype=tf.uint8) last_layer = tf.keras.backend.cast(input_layer, tf.float32) last_layer ...
[ "def", "create_scm_encoder_model", "(", "obs_space", ",", "model_config", ")", ":", "original_obs_dims", "=", "obs_space", ".", "original_space", ".", "spaces", "[", "\"curr_obs\"", "]", ".", "shape", "input_layer", "=", "tf", ".", "keras", ".", "layers", ".", ...
Create the encoder submodel, which is part of the SCM.
[ "Create", "the", "encoder", "submodel", "which", "is", "part", "of", "the", "SCM", "." ]
[ "\"\"\"\n Create the encoder submodel, which is part of the SCM.\n :param obs_space: A single agent's observation space.\n :param model_config: The model config dict.\n :return: A new encoder model.\n \"\"\"", "# Divide by 255 to transform [0,255] uint8 rgb pixel values to [0,1]...
[ { "param": "obs_space", "type": null }, { "param": "model_config", "type": null } ]
{ "returns": [ { "docstring": "A new encoder model.", "docstring_tokens": [ "A", "new", "encoder", "model", "." ], "type": null } ], "raises": [], "params": [ { "identifier": "obs_space", "type": null, "docstring": "A ...
601ec833c8daf89c1e84bc255d13cdd9e02b1a78
eugenevinitsky/sequential_social_dilemma_games
models/scm_model.py
[ "MIT" ]
Python
forward
<not_specific>
def forward(self, input_dict, state, seq_lens): """ The forward pass through the SCM network. :param input_dict: The input tensors. :param state: The model state. :param seq_lens: The LSTM sequence lengths. :return: The SCM output and new model state. """ ...
The forward pass through the SCM network. :param input_dict: The input tensors. :param state: The model state. :param seq_lens: The LSTM sequence lengths. :return: The SCM output and new model state.
The forward pass through the SCM network.
[ "The", "forward", "pass", "through", "the", "SCM", "network", "." ]
def forward(self, input_dict, state, seq_lens): output, new_state = super(SocialCuriosityModule, self).forward(input_dict, state, seq_lens) encoded_state = self.scm_encoder_model(input_dict["obs"]["curr_obs"]) new_state.append(encoded_state) influence_reward = tf.expand_dims(self._social...
[ "def", "forward", "(", "self", ",", "input_dict", ",", "state", ",", "seq_lens", ")", ":", "output", ",", "new_state", "=", "super", "(", "SocialCuriosityModule", ",", "self", ")", ".", "forward", "(", "input_dict", ",", "state", ",", "seq_lens", ")", "e...
The forward pass through the SCM network.
[ "The", "forward", "pass", "through", "the", "SCM", "network", "." ]
[ "\"\"\"\n The forward pass through the SCM network.\n :param input_dict: The input tensors.\n :param state: The model state.\n :param seq_lens: The LSTM sequence lengths.\n :return: The SCM output and new model state.\n \"\"\"", "# Stop backpropagation through the LSTM.",...
[ { "param": "self", "type": null }, { "param": "input_dict", "type": null }, { "param": "state", "type": null }, { "param": "seq_lens", "type": null } ]
{ "returns": [ { "docstring": "The SCM output and new model state.", "docstring_tokens": [ "The", "SCM", "output", "and", "new", "model", "state", "." ], "type": null } ], "raises": [], "params": [ { "ident...
601ec833c8daf89c1e84bc255d13cdd9e02b1a78
eugenevinitsky/sequential_social_dilemma_games
models/scm_model.py
[ "MIT" ]
Python
batched_mse
<not_specific>
def batched_mse(true_tensor, pred_tensor): """ Calculate the mean square error on a batched tensor. The output has the same amount of dimensions as the input, but sets the last dimension size to 1, which contains the mean. :param true_tensor: The true values :param pred_t...
Calculate the mean square error on a batched tensor. The output has the same amount of dimensions as the input, but sets the last dimension size to 1, which contains the mean. :param true_tensor: The true values :param pred_tensor: The predicted values :return: The mean ...
Calculate the mean square error on a batched tensor. The output has the same amount of dimensions as the input, but sets the last dimension size to 1, which contains the mean.
[ "Calculate", "the", "mean", "square", "error", "on", "a", "batched", "tensor", ".", "The", "output", "has", "the", "same", "amount", "of", "dimensions", "as", "the", "input", "but", "sets", "the", "last", "dimension", "size", "to", "1", "which", "contains"...
def batched_mse(true_tensor, pred_tensor): squared_difference = tf.squared_difference(true_tensor, pred_tensor) mse = tf.reduce_mean(squared_difference, axis=-1, keepdims=True) return mse
[ "def", "batched_mse", "(", "true_tensor", ",", "pred_tensor", ")", ":", "squared_difference", "=", "tf", ".", "squared_difference", "(", "true_tensor", ",", "pred_tensor", ")", "mse", "=", "tf", ".", "reduce_mean", "(", "squared_difference", ",", "axis", "=", ...
Calculate the mean square error on a batched tensor.
[ "Calculate", "the", "mean", "square", "error", "on", "a", "batched", "tensor", "." ]
[ "\"\"\"\n Calculate the mean square error on a batched tensor.\n The output has the same amount of dimensions as the input,\n but sets the last dimension size to 1, which contains the mean.\n :param true_tensor: The true values\n :param pred_tensor: The predicted values\n :...
[ { "param": "true_tensor", "type": null }, { "param": "pred_tensor", "type": null } ]
{ "returns": [ { "docstring": "The mean square error between the true and predicted tensors.", "docstring_tokens": [ "The", "mean", "square", "error", "between", "the", "true", "and", "predicted", "tensors", "." ...
b91c618b8b488b06d1a22133b2b3dd1a61195a16
mightyBroccoli/xmpp-chatbot
common/misc.py
[ "0BSD" ]
Python
validate
<not_specific>
def validate(keyword, target): """ validation method to reduce malformed querys and unnecessary connection attempts :param keyword: used keyword :param target: provided target :return: true if valid """ # if keyword in domain_keywords list if keyword in StaticAnswers().keys('domain_keywords'): # if target is ...
validation method to reduce malformed querys and unnecessary connection attempts :param keyword: used keyword :param target: provided target :return: true if valid
validation method to reduce malformed querys and unnecessary connection attempts
[ "validation", "method", "to", "reduce", "malformed", "querys", "and", "unnecessary", "connection", "attempts" ]
def validate(keyword, target): if keyword in StaticAnswers().keys('domain_keywords'): if validators.domain(target) or validators.email(target): return True elif keyword in StaticAnswers().keys('number_keywords'): if target is not None: return target.isdigit() elif keyword in StaticAnswers().keys("no_arg_ke...
[ "def", "validate", "(", "keyword", ",", "target", ")", ":", "if", "keyword", "in", "StaticAnswers", "(", ")", ".", "keys", "(", "'domain_keywords'", ")", ":", "if", "validators", ".", "domain", "(", "target", ")", "or", "validators", ".", "email", "(", ...
validation method to reduce malformed querys and unnecessary connection attempts
[ "validation", "method", "to", "reduce", "malformed", "querys", "and", "unnecessary", "connection", "attempts" ]
[ "\"\"\"\n\tvalidation method to reduce malformed querys and unnecessary connection attempts\n\t:param keyword: used keyword\n\t:param target: provided target\n\t:return: true if valid\n\t\"\"\"", "# if keyword in domain_keywords list", "# if target is a domain / email return True", "# check if keyword is in n...
[ { "param": "keyword", "type": null }, { "param": "target", "type": null } ]
{ "returns": [ { "docstring": "true if valid", "docstring_tokens": [ "true", "if", "valid" ], "type": null } ], "raises": [], "params": [ { "identifier": "keyword", "type": null, "docstring": null, "docstring_tokens": [ ...
f5fae61879a1bdefe098f72cda4c92cc18f541e3
mightyBroccoli/xmpp-chatbot
classes/xep.py
[ "0BSD" ]
Python
req_xeplist
null
def req_xeplist(self): """ query and save the current xep list to reduce network bandwidth """ # check if etag header is present if not set local_etag to "" if os.path.isfile("./common/.etag"): with open("./common/.etag") as file: local_etag = file.read() else: local_etag = "" with requests.Ses...
query and save the current xep list to reduce network bandwidth
query and save the current xep list to reduce network bandwidth
[ "query", "and", "save", "the", "current", "xep", "list", "to", "reduce", "network", "bandwidth" ]
def req_xeplist(self): if os.path.isfile("./common/.etag"): with open("./common/.etag") as file: local_etag = file.read() else: local_etag = "" with requests.Session() as s: s.headers.update({'Accept': 'application/xml'}) head = s.head("https://xmpp.org/extensions/xeplist.xml") etag = head.head...
[ "def", "req_xeplist", "(", "self", ")", ":", "if", "os", ".", "path", ".", "isfile", "(", "\"./common/.etag\"", ")", ":", "with", "open", "(", "\"./common/.etag\"", ")", "as", "file", ":", "local_etag", "=", "file", ".", "read", "(", ")", "else", ":", ...
query and save the current xep list to reduce network bandwidth
[ "query", "and", "save", "the", "current", "xep", "list", "to", "reduce", "network", "bandwidth" ]
[ "\"\"\"\n\t\tquery and save the current xep list to reduce network bandwidth\n\t\t\"\"\"", "# check if etag header is present if not set local_etag to \"\"", "# head request the xeplist.xml", "# compare etag with local_etag if they match up no request is made", "# if the connection is not possible use cache...
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
50f9b03431b8c70e8d3c283257e567434cfb55b3
mightyBroccoli/xmpp-chatbot
main.py
[ "0BSD" ]
Python
start
null
def start(self, event): """ :param event -- An empty dictionary. The session_start event does not provide any additional data. """ self.send_presence() self.get_roster() # If a room password is needed, use: password=the_room_password if self.room: for rooms in self.room.split(sep=","): logging.deb...
:param event -- An empty dictionary. The session_start event does not provide any additional data.
:param event -- An empty dictionary. The session_start event does not provide any additional data.
[ ":", "param", "event", "--", "An", "empty", "dictionary", ".", "The", "session_start", "event", "does", "not", "provide", "any", "additional", "data", "." ]
def start(self, event): self.send_presence() self.get_roster() if self.room: for rooms in self.room.split(sep=","): logging.debug("joining: %s" % rooms) self.plugin['xep_0045'].join_muc(rooms, self.nick, wait=True)
[ "def", "start", "(", "self", ",", "event", ")", ":", "self", ".", "send_presence", "(", ")", "self", ".", "get_roster", "(", ")", "if", "self", ".", "room", ":", "for", "rooms", "in", "self", ".", "room", ".", "split", "(", "sep", "=", "\",\"", "...
:param event -- An empty dictionary.
[ ":", "param", "event", "--", "An", "empty", "dictionary", "." ]
[ "\"\"\"\n\t\t:param event -- An empty dictionary. The session_start event does not provide any additional data.\n\t\t\"\"\"", "# If a room password is needed, use: password=the_room_password" ]
[ { "param": "self", "type": null }, { "param": "event", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "event", "type": null, "docstring": null, "docstring_tokens": ...
31f050ccb9a80b948aecf66ee178b8ca9d152fae
gizmag/django-haystack
haystack/admin.py
[ "BSD-3-Clause" ]
Python
list_max_show_all
<not_specific>
def list_max_show_all(changelist): """ Returns the maximum amount of results a changelist can have for the "Show all" link to be displayed in a manner compatible with both Django 1.4 and 1.3. See Django ticket #15997 for details. """ try: # This import is available in Django 1.3 and belo...
Returns the maximum amount of results a changelist can have for the "Show all" link to be displayed in a manner compatible with both Django 1.4 and 1.3. See Django ticket #15997 for details.
Returns the maximum amount of results a changelist can have for the "Show all" link to be displayed in a manner compatible with both Django 1.4 and 1.3. See Django ticket #15997 for details.
[ "Returns", "the", "maximum", "amount", "of", "results", "a", "changelist", "can", "have", "for", "the", "\"", "Show", "all", "\"", "link", "to", "be", "displayed", "in", "a", "manner", "compatible", "with", "both", "Django", "1", ".", "4", "and", "1", ...
def list_max_show_all(changelist): try: from django.contrib.admin.views.main import MAX_SHOW_ALL_ALLOWED return MAX_SHOW_ALL_ALLOWED except ImportError: return changelist.list_max_show_all
[ "def", "list_max_show_all", "(", "changelist", ")", ":", "try", ":", "from", "django", ".", "contrib", ".", "admin", ".", "views", ".", "main", "import", "MAX_SHOW_ALL_ALLOWED", "return", "MAX_SHOW_ALL_ALLOWED", "except", "ImportError", ":", "return", "changelist"...
Returns the maximum amount of results a changelist can have for the "Show all" link to be displayed in a manner compatible with both Django 1.4 and 1.3.
[ "Returns", "the", "maximum", "amount", "of", "results", "a", "changelist", "can", "have", "for", "the", "\"", "Show", "all", "\"", "link", "to", "be", "displayed", "in", "a", "manner", "compatible", "with", "both", "Django", "1", ".", "4", "and", "1", ...
[ "\"\"\"\n Returns the maximum amount of results a changelist can have for the\n \"Show all\" link to be displayed in a manner compatible with both Django\n 1.4 and 1.3. See Django ticket #15997 for details.\n \"\"\"", "# This import is available in Django 1.3 and below" ]
[ { "param": "changelist", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "changelist", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
248a514da2fae6ba69dfe88cf6e4e55511a4045e
Hawkpath/he-music-extractor
HE_music_extractor.py
[ "MIT" ]
Python
write_pcm_to_file
<not_specific>
def write_pcm_to_file( output_path: Path, payload: bytes, samplerate: int, output_options: List[str] = None ): """ Write unsigned 8-bit audio data to an audio file. :param output_path: path to write audio file :param payload: raw PCM samples :param sa...
Write unsigned 8-bit audio data to an audio file. :param output_path: path to write audio file :param payload: raw PCM samples :param samplerate: samplerate of the audio data :param output_options: ffmpeg options for output file
Write unsigned 8-bit audio data to an audio file.
[ "Write", "unsigned", "8", "-", "bit", "audio", "data", "to", "an", "audio", "file", "." ]
def write_pcm_to_file( output_path: Path, payload: bytes, samplerate: int, output_options: List[str] = None ): output_options = output_options or [] ffmpeg = Popen([ 'ffmpeg', '-hide_banner', '-loglevel', 'error', '-f', 'u8', '-ar', str(samplerate), '-...
[ "def", "write_pcm_to_file", "(", "output_path", ":", "Path", ",", "payload", ":", "bytes", ",", "samplerate", ":", "int", ",", "output_options", ":", "List", "[", "str", "]", "=", "None", ")", ":", "output_options", "=", "output_options", "or", "[", "]", ...
Write unsigned 8-bit audio data to an audio file.
[ "Write", "unsigned", "8", "-", "bit", "audio", "data", "to", "an", "audio", "file", "." ]
[ "\"\"\"\n Write unsigned 8-bit audio data to an audio file.\n\n :param output_path: path to write audio file\n :param payload: raw PCM samples\n :param samplerate: samplerate of the audio data\n :param output_options: ffmpeg options for output file\n \"\"\"" ]
[ { "param": "output_path", "type": "Path" }, { "param": "payload", "type": "bytes" }, { "param": "samplerate", "type": "int" }, { "param": "output_options", "type": "List[str]" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "output_path", "type": "Path", "docstring": "path to write audio file", "docstring_tokens": [ "path", "to", "write", "audio", "file" ], "default": null, "is_optional": n...
248a514da2fae6ba69dfe88cf6e4e55511a4045e
Hawkpath/he-music-extractor
HE_music_extractor.py
[ "MIT" ]
Python
write_pcm_to_mp3
<not_specific>
def write_pcm_to_mp3( output_path: Path, payload: bytes, samplerate: int, quality_or_bitrate: Union[int, str] = 0, title: str = None, artist: str = None, album: str = None, year: str = None, track: int = None, ...
Write unsigned 8-bit audio data to an MP3 file. :param output_path: path to write MP3 file :param payload: raw PCM samples :param samplerate: samplerate of the audio data :param quality_or_bitrate: if an integer, encode with this VBR quality preset, otherwise if a s...
Write unsigned 8-bit audio data to an MP3 file.
[ "Write", "unsigned", "8", "-", "bit", "audio", "data", "to", "an", "MP3", "file", "." ]
def write_pcm_to_mp3( output_path: Path, payload: bytes, samplerate: int, quality_or_bitrate: Union[int, str] = 0, title: str = None, artist: str = None, album: str = None, year: str = None, track: int = None, ...
[ "def", "write_pcm_to_mp3", "(", "output_path", ":", "Path", ",", "payload", ":", "bytes", ",", "samplerate", ":", "int", ",", "quality_or_bitrate", ":", "Union", "[", "int", ",", "str", "]", "=", "0", ",", "title", ":", "str", "=", "None", ",", "artist...
Write unsigned 8-bit audio data to an MP3 file.
[ "Write", "unsigned", "8", "-", "bit", "audio", "data", "to", "an", "MP3", "file", "." ]
[ "\"\"\"\n Write unsigned 8-bit audio data to an MP3 file.\n\n :param output_path: path to write MP3 file\n :param payload: raw PCM samples\n :param samplerate: samplerate of the audio data\n :param quality_or_bitrate: if an integer, encode with this VBR quality\n preset...
[ { "param": "output_path", "type": "Path" }, { "param": "payload", "type": "bytes" }, { "param": "samplerate", "type": "int" }, { "param": "quality_or_bitrate", "type": "Union[int, str]" }, { "param": "title", "type": "str" }, { "param": "artist", "...
{ "returns": [], "raises": [], "params": [ { "identifier": "output_path", "type": "Path", "docstring": "path to write MP3 file", "docstring_tokens": [ "path", "to", "write", "MP3", "file" ], "default": null, "is_optional": null ...
248a514da2fae6ba69dfe88cf6e4e55511a4045e
Hawkpath/he-music-extractor
HE_music_extractor.py
[ "MIT" ]
Python
try_int_coerce
Union[int, str]
def try_int_coerce(string: str) -> Union[int, str]: """Try to convert string to integer, otherwise keep as string""" try: return int(string) except ValueError: return string
Try to convert string to integer, otherwise keep as string
Try to convert string to integer, otherwise keep as string
[ "Try", "to", "convert", "string", "to", "integer", "otherwise", "keep", "as", "string" ]
def try_int_coerce(string: str) -> Union[int, str]: try: return int(string) except ValueError: return string
[ "def", "try_int_coerce", "(", "string", ":", "str", ")", "->", "Union", "[", "int", ",", "str", "]", ":", "try", ":", "return", "int", "(", "string", ")", "except", "ValueError", ":", "return", "string" ]
Try to convert string to integer, otherwise keep as string
[ "Try", "to", "convert", "string", "to", "integer", "otherwise", "keep", "as", "string" ]
[ "\"\"\"Try to convert string to integer, otherwise keep as string\"\"\"" ]
[ { "param": "string", "type": "str" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "string", "type": "str", "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
3d032fb67c80a8b1262120dba41572c8a27c456b
internetofwater/geoconnex.us
PID-server/yourls_client.py
[ "CC0-1.0" ]
Python
walk_path
<not_specific>
def walk_path(path): """ Walks os directory path collecting all CSV files. :param path: required, string. os directory. :return: list. List of csv paths. """ file_list = [] for root, _, files in os.walk(path, topdown=False): for name in files: if name.startswit...
Walks os directory path collecting all CSV files. :param path: required, string. os directory. :return: list. List of csv paths.
Walks os directory path collecting all CSV files.
[ "Walks", "os", "directory", "path", "collecting", "all", "CSV", "files", "." ]
def walk_path(path): file_list = [] for root, _, files in os.walk(path, topdown=False): for name in files: if name.startswith('example'): continue elif name.endswith('.csv'): file_list.append(os.path.join(root, name)) return file_list
[ "def", "walk_path", "(", "path", ")", ":", "file_list", "=", "[", "]", "for", "root", ",", "_", ",", "files", "in", "os", ".", "walk", "(", "path", ",", "topdown", "=", "False", ")", ":", "for", "name", "in", "files", ":", "if", "name", ".", "s...
Walks os directory path collecting all CSV files.
[ "Walks", "os", "directory", "path", "collecting", "all", "CSV", "files", "." ]
[ "\"\"\"\r\n Walks os directory path collecting all CSV files.\r\n\r\n :param path: required, string. os directory.\r\n :return: list. List of csv paths.\r\n \"\"\"" ]
[ { "param": "path", "type": null } ]
{ "returns": [ { "docstring": "list. List of csv paths.", "docstring_tokens": [ "list", ".", "List", "of", "csv", "paths", "." ], "type": null } ], "raises": [], "params": [ { "identifier": "path", "type": nu...
3047b75e307dc268638edb54852db9cfac31d92a
internetofwater/geoconnex.us
PID-server/yourls_api.py
[ "CC0-1.0" ]
Python
handle_csv
<not_specific>
def handle_csv(self, file): """ Parses and shortens CSV file. :param file: required, string or list of strings. Name of csv files to be shortened """ if isinstance(file, list): self._handle_csvs(file) return parsed_csv = self.parse_csv(...
Parses and shortens CSV file. :param file: required, string or list of strings. Name of csv files to be shortened
Parses and shortens CSV file.
[ "Parses", "and", "shortens", "CSV", "file", "." ]
def handle_csv(self, file): if isinstance(file, list): self._handle_csvs(file) return parsed_csv = self.parse_csv(file) chunky_parsed = self.chunkify( parsed_csv ) for chunk in chunky_parsed: r = self.shorten_csv(file, chunk)
[ "def", "handle_csv", "(", "self", ",", "file", ")", ":", "if", "isinstance", "(", "file", ",", "list", ")", ":", "self", ".", "_handle_csvs", "(", "file", ")", "return", "parsed_csv", "=", "self", ".", "parse_csv", "(", "file", ")", "chunky_parsed", "=...
Parses and shortens CSV file.
[ "Parses", "and", "shortens", "CSV", "file", "." ]
[ "\"\"\"\r\n Parses and shortens CSV file.\r\n\r\n :param file: required, string or list of strings. Name of csv files to be shortened\r\n \"\"\"" ]
[ { "param": "self", "type": null }, { "param": "file", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "file", "type": null, "docstring": "required, string or list of stri...
3047b75e307dc268638edb54852db9cfac31d92a
internetofwater/geoconnex.us
PID-server/yourls_api.py
[ "CC0-1.0" ]
Python
parse_csv
<not_specific>
def parse_csv(self, filename): """ Parse CSV file into yourls-friendly csv. :param filename: required, string. URL to be shortened. :return: list. Parsed csv. """ _ = self._check_kwargs(('url', 'keyword', 'title')) vals = {k: v for k, v in _} t...
Parse CSV file into yourls-friendly csv. :param filename: required, string. URL to be shortened. :return: list. Parsed csv.
Parse CSV file into yourls-friendly csv.
[ "Parse", "CSV", "file", "into", "yourls", "-", "friendly", "csv", "." ]
def parse_csv(self, filename): _ = self._check_kwargs(('url', 'keyword', 'title')) vals = {k: v for k, v in _} try: r = requests.get(filename) fp = r.content.decode().splitlines() except requests.exceptions.MissingSchema: r = None fp = open...
[ "def", "parse_csv", "(", "self", ",", "filename", ")", ":", "_", "=", "self", ".", "_check_kwargs", "(", "(", "'url'", ",", "'keyword'", ",", "'title'", ")", ")", "vals", "=", "{", "k", ":", "v", "for", "k", ",", "v", "in", "_", "}", "try", ":"...
Parse CSV file into yourls-friendly csv.
[ "Parse", "CSV", "file", "into", "yourls", "-", "friendly", "csv", "." ]
[ "\"\"\"\r\n Parse CSV file into yourls-friendly csv.\r\n\r\n :param filename: required, string. URL to be shortened.\r\n :return: list. Parsed csv.\r\n \"\"\"" ]
[ { "param": "self", "type": null }, { "param": "filename", "type": null } ]
{ "returns": [ { "docstring": "list. Parsed csv.", "docstring_tokens": [ "list", ".", "Parsed", "csv", "." ], "type": null } ], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "...
88bc8ba18596ca219e4195a1b59d0a366c07db9d
onespacemedia/cms
cms/apps/media/models.py
[ "BSD-3-Clause" ]
Python
embed_html
<not_specific>
def embed_html(self, loop=False, autoplay=False, controls=False, mute=False, youtube_parameters=None): ''' Returns the HTML code for embedding the video. Expects youtube_parameters as a dictionary in the form {parameter:value} When using, this is a function so call with {{ video.embed_ht...
Returns the HTML code for embedding the video. Expects youtube_parameters as a dictionary in the form {parameter:value} When using, this is a function so call with {{ video.embed_html|safe }}
Returns the HTML code for embedding the video. Expects youtube_parameters as a dictionary in the form {parameter:value} When using, this is a function so call with {{ video.embed_html|safe }}
[ "Returns", "the", "HTML", "code", "for", "embedding", "the", "video", ".", "Expects", "youtube_parameters", "as", "a", "dictionary", "in", "the", "form", "{", "parameter", ":", "value", "}", "When", "using", "this", "is", "a", "function", "so", "call", "wi...
def embed_html(self, loop=False, autoplay=False, controls=False, mute=False, youtube_parameters=None): if self.external_video: if self.external_video_service == 'youtube': return render_to_string('videos/youtube.html', { 'src': self.external_video_iframe_url, ...
[ "def", "embed_html", "(", "self", ",", "loop", "=", "False", ",", "autoplay", "=", "False", ",", "controls", "=", "False", ",", "mute", "=", "False", ",", "youtube_parameters", "=", "None", ")", ":", "if", "self", ".", "external_video", ":", "if", "sel...
Returns the HTML code for embedding the video.
[ "Returns", "the", "HTML", "code", "for", "embedding", "the", "video", "." ]
[ "'''\n Returns the HTML code for embedding the video.\n Expects youtube_parameters as a dictionary in the form {parameter:value}\n When using, this is a function so call with {{ video.embed_html|safe }}\n '''" ]
[ { "param": "self", "type": null }, { "param": "loop", "type": null }, { "param": "autoplay", "type": null }, { "param": "controls", "type": null }, { "param": "mute", "type": null }, { "param": "youtube_parameters", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "loop", "type": null, "docstring": null, "docstring_tokens": [...
94853dfb50404566c66776a922c87d186fe617d9
onespacemedia/cms
cms/apps/media/admin.py
[ "BSD-3-Clause" ]
Python
response_add
<not_specific>
def response_add(self, request, obj, post_url_continue=None): '''Returns the response for a successful add action.''' if '_tinymce' in request.GET: context = {'permalink': permalinks.create(obj), 'title': obj.title} return render(request, 'admin/media/file/...
Returns the response for a successful add action.
Returns the response for a successful add action.
[ "Returns", "the", "response", "for", "a", "successful", "add", "action", "." ]
def response_add(self, request, obj, post_url_continue=None): if '_tinymce' in request.GET: context = {'permalink': permalinks.create(obj), 'title': obj.title} return render(request, 'admin/media/file/filebrowser_add_success.html', context) return super().r...
[ "def", "response_add", "(", "self", ",", "request", ",", "obj", ",", "post_url_continue", "=", "None", ")", ":", "if", "'_tinymce'", "in", "request", ".", "GET", ":", "context", "=", "{", "'permalink'", ":", "permalinks", ".", "create", "(", "obj", ")", ...
Returns the response for a successful add action.
[ "Returns", "the", "response", "for", "a", "successful", "add", "action", "." ]
[ "'''Returns the response for a successful add action.'''" ]
[ { "param": "self", "type": null }, { "param": "request", "type": null }, { "param": "obj", "type": null }, { "param": "post_url_continue", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "request", "type": null, "docstring": null, "docstring_tokens"...
94853dfb50404566c66776a922c87d186fe617d9
onespacemedia/cms
cms/apps/media/admin.py
[ "BSD-3-Clause" ]
Python
media_library_changelist_view
<not_specific>
def media_library_changelist_view(self, request, extra_context=None): '''Renders the change list, but sets 'is_popup=True' into the template context to make it render the media library sans navigation, without needing _popup in the URL (which causes an exception with Jet's Javascript, wh...
Renders the change list, but sets 'is_popup=True' into the template context to make it render the media library sans navigation, without needing _popup in the URL (which causes an exception with Jet's Javascript, which assumes that if _popup is in the URL that it is a related item popup)...
Renders the change list, but sets 'is_popup=True' into the template context to make it render the media library sans navigation, without needing _popup in the URL (which causes an exception with Jet's Javascript, which assumes that if _popup is in the URL that it is a related item popup).
[ "Renders", "the", "change", "list", "but", "sets", "'", "is_popup", "=", "True", "'", "into", "the", "template", "context", "to", "make", "it", "render", "the", "media", "library", "sans", "navigation", "without", "needing", "_popup", "in", "the", "URL", "...
def media_library_changelist_view(self, request, extra_context=None): context = extra_context or {} context.setdefault('changelist_template_parent', 'reversion/change_list.html') context['is_popup'] = True context['is_media_library_iframe'] = True return super().changelist_view(r...
[ "def", "media_library_changelist_view", "(", "self", ",", "request", ",", "extra_context", "=", "None", ")", ":", "context", "=", "extra_context", "or", "{", "}", "context", ".", "setdefault", "(", "'changelist_template_parent'", ",", "'reversion/change_list.html'", ...
Renders the change list, but sets 'is_popup=True' into the template context to make it render the media library sans navigation, without needing _popup in the URL (which causes an exception with Jet's Javascript, which assumes that if _popup is in the URL that it is a related item popup).
[ "Renders", "the", "change", "list", "but", "sets", "'", "is_popup", "=", "True", "'", "into", "the", "template", "context", "to", "make", "it", "render", "the", "media", "library", "sans", "navigation", "without", "needing", "_popup", "in", "the", "URL", "...
[ "'''Renders the change list, but sets 'is_popup=True' into the template\n context to make it render the media library sans navigation, without\n needing _popup in the URL (which causes an exception with Jet's\n Javascript, which assumes that if _popup is in the URL that it is a\n related...
[ { "param": "self", "type": null }, { "param": "request", "type": null }, { "param": "extra_context", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "request", "type": null, "docstring": null, "docstring_tokens"...
ef9a0a80dc67a65e872fd1e8c27837f3bd63e4d4
onespacemedia/cms
cms/models/base.py
[ "BSD-3-Clause" ]
Python
render
<not_specific>
def render(self, request, template, context=None, **kwargs): """Renders a template as a HttpResponse using the context of this page.""" page_context = self.get_context_data() page_context.update(context or {}) return render(request, template, page_context, **kwargs)
Renders a template as a HttpResponse using the context of this page.
Renders a template as a HttpResponse using the context of this page.
[ "Renders", "a", "template", "as", "a", "HttpResponse", "using", "the", "context", "of", "this", "page", "." ]
def render(self, request, template, context=None, **kwargs): page_context = self.get_context_data() page_context.update(context or {}) return render(request, template, page_context, **kwargs)
[ "def", "render", "(", "self", ",", "request", ",", "template", ",", "context", "=", "None", ",", "**", "kwargs", ")", ":", "page_context", "=", "self", ".", "get_context_data", "(", ")", "page_context", ".", "update", "(", "context", "or", "{", "}", ")...
Renders a template as a HttpResponse using the context of this page.
[ "Renders", "a", "template", "as", "a", "HttpResponse", "using", "the", "context", "of", "this", "page", "." ]
[ "\"\"\"Renders a template as a HttpResponse using the context of this page.\"\"\"" ]
[ { "param": "self", "type": null }, { "param": "request", "type": null }, { "param": "template", "type": null }, { "param": "context", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "request", "type": null, "docstring": null, "docstring_tokens"...
31fcfd60953ddecfa02f7fdf36e0b680889a5aa4
onespacemedia/cms
cms/apps/pages/utils.py
[ "BSD-3-Clause" ]
Python
duplicate_page
<not_specific>
def duplicate_page(original_page, page_changes=None): ''' Takes a page and duplicates it as a child of the original's parent page. Expects to be passed the original page and an optional function ''' from .admin import page_admin original_content = original_page.content with update_i...
Takes a page and duplicates it as a child of the original's parent page. Expects to be passed the original page and an optional function
Takes a page and duplicates it as a child of the original's parent page. Expects to be passed the original page and an optional function
[ "Takes", "a", "page", "and", "duplicates", "it", "as", "a", "child", "of", "the", "original", "'", "s", "parent", "page", ".", "Expects", "to", "be", "passed", "the", "original", "page", "and", "an", "optional", "function" ]
def duplicate_page(original_page, page_changes=None): from .admin import page_admin original_content = original_page.content with update_index(): page = deepcopy(original_page) page.pk = None if callable(page_changes): page = page_changes(page, original_page) page...
[ "def", "duplicate_page", "(", "original_page", ",", "page_changes", "=", "None", ")", ":", "from", ".", "admin", "import", "page_admin", "original_content", "=", "original_page", ".", "content", "with", "update_index", "(", ")", ":", "page", "=", "deepcopy", "...
Takes a page and duplicates it as a child of the original's parent page.
[ "Takes", "a", "page", "and", "duplicates", "it", "as", "a", "child", "of", "the", "original", "'", "s", "parent", "page", "." ]
[ "'''\n Takes a page and duplicates it as a child of the original's parent page.\n Expects to be passed the original page and an optional function\n '''", "# This doesn't copy m2m relations on the copied inline" ]
[ { "param": "original_page", "type": null }, { "param": "page_changes", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "original_page", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "page_changes", "type": null, "docstring": null, "doc...
31fcfd60953ddecfa02f7fdf36e0b680889a5aa4
onespacemedia/cms
cms/apps/pages/utils.py
[ "BSD-3-Clause" ]
Python
overlay_page_obj
<not_specific>
def overlay_page_obj(original_page, overlay_page, commit=False): ''' A function that takes a page and overlay the fields and linked objects from a different page. ''' from .admin import page_admin original_content = original_page.content page_fields_exclude = ['pk', 'id', 'version_for', 'lef...
A function that takes a page and overlay the fields and linked objects from a different page.
A function that takes a page and overlay the fields and linked objects from a different page.
[ "A", "function", "that", "takes", "a", "page", "and", "overlay", "the", "fields", "and", "linked", "objects", "from", "a", "different", "page", "." ]
def overlay_page_obj(original_page, overlay_page, commit=False): from .admin import page_admin original_content = original_page.content page_fields_exclude = ['pk', 'id', 'version_for', 'left', 'right'] content_fields_exclude = ['pk', 'id', 'page'] checked_models = [] related_fields = [] def...
[ "def", "overlay_page_obj", "(", "original_page", ",", "overlay_page", ",", "commit", "=", "False", ")", ":", "from", ".", "admin", "import", "page_admin", "original_content", "=", "original_page", ".", "content", "page_fields_exclude", "=", "[", "'pk'", ",", "'i...
A function that takes a page and overlay the fields and linked objects from a different page.
[ "A", "function", "that", "takes", "a", "page", "and", "overlay", "the", "fields", "and", "linked", "objects", "from", "a", "different", "page", "." ]
[ "'''\n A function that takes a page and overlay the fields and linked objects from a different page.\n '''", "# Overlay page fields", "# Overlay page content fields" ]
[ { "param": "original_page", "type": null }, { "param": "overlay_page", "type": null }, { "param": "commit", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "original_page", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "overlay_page", "type": null, "docstring": null, "doc...
a2cbbea4b9c4a421a71d226474a2557564ca262e
onespacemedia/cms
cms/html.py
[ "BSD-3-Clause" ]
Python
process
<not_specific>
def process(text): """ Expands permalinks in <a/> and <img/> tags. Images will also be automatically thumbnailed to fit their specified width and height. """ resolved_permalinks = {} def sub_tag(match): tagname = match.group(1) attrs = dict(RE_ATTR.findall(match.group(2))) ...
Expands permalinks in <a/> and <img/> tags. Images will also be automatically thumbnailed to fit their specified width and height.
Expands permalinks in and tags. Images will also be automatically thumbnailed to fit their specified width and height.
[ "Expands", "permalinks", "in", "and", "tags", ".", "Images", "will", "also", "be", "automatically", "thumbnailed", "to", "fit", "their", "specified", "width", "and", "height", "." ]
def process(text): resolved_permalinks = {} def sub_tag(match): tagname = match.group(1) attrs = dict(RE_ATTR.findall(match.group(2))) def get_obj(attr_name): if attr_name in attrs: value = attrs[attr_name][1:-1] if value not in resolved_permal...
[ "def", "process", "(", "text", ")", ":", "resolved_permalinks", "=", "{", "}", "def", "sub_tag", "(", "match", ")", ":", "tagname", "=", "match", ".", "group", "(", "1", ")", "attrs", "=", "dict", "(", "RE_ATTR", ".", "findall", "(", "match", ".", ...
Expands permalinks in <a/> and <img/> tags.
[ "Expands", "permalinks", "in", "<a", "/", ">", "and", "<img", "/", ">", "tags", "." ]
[ "\"\"\"\n Expands permalinks in <a/> and <img/> tags.\n\n Images will also be automatically thumbnailed to fit their specified width\n and height.\n \"\"\"", "# Add in the URL of the obj.", "# Add in the title of the obj.", "# Process hyperlinks.", "# Process images.", "# Automagically detect ...
[ { "param": "text", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "text", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
11d52e4299c578f11412f2b0e7a997fb4db08942
onespacemedia/cms
cms/apps/pages/admin.py
[ "BSD-3-Clause" ]
Python
move_page_view
<not_specific>
def move_page_view(self, request): '''Moves a page up or down.''' # Check that the user has permission to move pages. if not self.has_change_permission(request): return HttpResponseForbidden('You do not have permission to move this page.') # Lock entire table. existi...
Moves a page up or down.
Moves a page up or down.
[ "Moves", "a", "page", "up", "or", "down", "." ]
def move_page_view(self, request): if not self.has_change_permission(request): return HttpResponseForbidden('You do not have permission to move this page.') existing_pages_list = Page.objects.all().exclude( is_canonical_page=False, ).select_for_update().values( ...
[ "def", "move_page_view", "(", "self", ",", "request", ")", ":", "if", "not", "self", ".", "has_change_permission", "(", "request", ")", ":", "return", "HttpResponseForbidden", "(", "'You do not have permission to move this page.'", ")", "existing_pages_list", "=", "Pa...
Moves a page up or down.
[ "Moves", "a", "page", "up", "or", "down", "." ]
[ "'''Moves a page up or down.'''", "# Check that the user has permission to move pages.", "# Lock entire table.", "# Get the page.", "# Get all the siblings.", "# Find the page to swap.", "# Put the pages in order.", "# Excise the first page.", "# Move the other page.", "# Put the page back in.", ...
[ { "param": "self", "type": null }, { "param": "request", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "request", "type": null, "docstring": null, "docstring_tokens"...