nwo
stringlengths
5
86
sha
stringlengths
40
40
path
stringlengths
4
189
language
stringclasses
1 value
identifier
stringlengths
1
94
parameters
stringlengths
2
4.03k
argument_list
stringclasses
1 value
return_statement
stringlengths
0
11.5k
docstring
stringlengths
1
33.2k
docstring_summary
stringlengths
0
5.15k
docstring_tokens
list
function
stringlengths
34
151k
function_tokens
list
url
stringlengths
90
278
ucsb-seclab/difuze
bb59a12ff87ad5ae45d9c60e349891bf80d72877
helper_scripts/components/bear_generate_preprocess.py
python
build_preprocessed
(compilation_commands, linker_commands, kernel_src_dir, target_arch, clang_path, llvm_link_path, llvm_bit_code_out)
return True
The main method that performs the preprocessing. :param compilation_commands: Parsed compilation commands from the json. :param linker_commands: Parsed linker commands from the json. :param kernel_src_dir: Path to the kernel source directory. :param target_arch: Number representing target architecture. :param clang_path: Path to clang. :param llvm_link_path: Path to llvm-link :param llvm_bit_code_out: Folder where all the linked bitcode files should be stored. :return: True
The main method that performs the preprocessing. :param compilation_commands: Parsed compilation commands from the json. :param linker_commands: Parsed linker commands from the json. :param kernel_src_dir: Path to the kernel source directory. :param target_arch: Number representing target architecture. :param clang_path: Path to clang. :param llvm_link_path: Path to llvm-link :param llvm_bit_code_out: Folder where all the linked bitcode files should be stored. :return: True
[ "The", "main", "method", "that", "performs", "the", "preprocessing", ".", ":", "param", "compilation_commands", ":", "Parsed", "compilation", "commands", "from", "the", "json", ".", ":", "param", "linker_commands", ":", "Parsed", "linker", "commands", "from", "the", "json", ".", ":", "param", "kernel_src_dir", ":", "Path", "to", "the", "kernel", "source", "directory", ".", ":", "param", "target_arch", ":", "Number", "representing", "target", "architecture", ".", ":", "param", "clang_path", ":", "Path", "to", "clang", ".", ":", "param", "llvm_link_path", ":", "Path", "to", "llvm", "-", "link", ":", "param", "llvm_bit_code_out", ":", "Folder", "where", "all", "the", "linked", "bitcode", "files", "should", "be", "stored", ".", ":", "return", ":", "True" ]
def build_preprocessed(compilation_commands, linker_commands, kernel_src_dir, target_arch, clang_path, llvm_link_path, llvm_bit_code_out): """ The main method that performs the preprocessing. :param compilation_commands: Parsed compilation commands from the json. :param linker_commands: Parsed linker commands from the json. :param kernel_src_dir: Path to the kernel source directory. :param target_arch: Number representing target architecture. :param clang_path: Path to clang. :param llvm_link_path: Path to llvm-link :param llvm_bit_code_out: Folder where all the linked bitcode files should be stored. :return: True """ output_llvm_sh_file = os.path.join(llvm_bit_code_out, 'llvm_generate_preprocessed.sh') fp_out = open(output_llvm_sh_file, 'w') fp_out.write("#!/bin/bash\n") log_info("Writing all preprocessing commands to", output_llvm_sh_file) all_compilation_commands = [] for curr_compilation_command in compilation_commands: wd, obj_file, bc_file, build_str = _get_llvm_preprocessing_str(clang_path, curr_compilation_command.curr_args, kernel_src_dir, target_arch, curr_compilation_command.work_dir, curr_compilation_command.src_file, curr_compilation_command.output_file, llvm_bit_code_out) all_compilation_commands.append((wd, build_str)) fp_out.write("cd " + wd + ";" + build_str + "\n") fp_out.close() log_info("Got", len(all_compilation_commands), "preprocessing commands.") log_info("Running preprocessing commands in multiprocessing modea.") p = Pool(cpu_count()) return_vals = p.map(run_program_with_wd, all_compilation_commands) log_success("Finished running preprocessing commands.") return True
[ "def", "build_preprocessed", "(", "compilation_commands", ",", "linker_commands", ",", "kernel_src_dir", ",", "target_arch", ",", "clang_path", ",", "llvm_link_path", ",", "llvm_bit_code_out", ")", ":", "output_llvm_sh_file", "=", "os", ".", "path", ".", "join", "(", "llvm_bit_code_out", ",", "'llvm_generate_preprocessed.sh'", ")", "fp_out", "=", "open", "(", "output_llvm_sh_file", ",", "'w'", ")", "fp_out", ".", "write", "(", "\"#!/bin/bash\\n\"", ")", "log_info", "(", "\"Writing all preprocessing commands to\"", ",", "output_llvm_sh_file", ")", "all_compilation_commands", "=", "[", "]", "for", "curr_compilation_command", "in", "compilation_commands", ":", "wd", ",", "obj_file", ",", "bc_file", ",", "build_str", "=", "_get_llvm_preprocessing_str", "(", "clang_path", ",", "curr_compilation_command", ".", "curr_args", ",", "kernel_src_dir", ",", "target_arch", ",", "curr_compilation_command", ".", "work_dir", ",", "curr_compilation_command", ".", "src_file", ",", "curr_compilation_command", ".", "output_file", ",", "llvm_bit_code_out", ")", "all_compilation_commands", ".", "append", "(", "(", "wd", ",", "build_str", ")", ")", "fp_out", ".", "write", "(", "\"cd \"", "+", "wd", "+", "\";\"", "+", "build_str", "+", "\"\\n\"", ")", "fp_out", ".", "close", "(", ")", "log_info", "(", "\"Got\"", ",", "len", "(", "all_compilation_commands", ")", ",", "\"preprocessing commands.\"", ")", "log_info", "(", "\"Running preprocessing commands in multiprocessing modea.\"", ")", "p", "=", "Pool", "(", "cpu_count", "(", ")", ")", "return_vals", "=", "p", ".", "map", "(", "run_program_with_wd", ",", "all_compilation_commands", ")", "log_success", "(", "\"Finished running preprocessing commands.\"", ")", "return", "True" ]
https://github.com/ucsb-seclab/difuze/blob/bb59a12ff87ad5ae45d9c60e349891bf80d72877/helper_scripts/components/bear_generate_preprocess.py#L142-L177
NVIDIA/MDL-SDK
aa9642b2546ad7b6236b5627385d882c2ed83c5d
src/mdl/jit/llvm/dist/bindings/python/llvm/object.py
python
Relocation.cache
(self)
Cache all cacheable properties on this instance.
Cache all cacheable properties on this instance.
[ "Cache", "all", "cacheable", "properties", "on", "this", "instance", "." ]
def cache(self): """Cache all cacheable properties on this instance.""" getattr(self, 'address') getattr(self, 'offset') getattr(self, 'symbol') getattr(self, 'type') getattr(self, 'type_name') getattr(self, 'value_string')
[ "def", "cache", "(", "self", ")", ":", "getattr", "(", "self", ",", "'address'", ")", "getattr", "(", "self", ",", "'offset'", ")", "getattr", "(", "self", ",", "'symbol'", ")", "getattr", "(", "self", ",", "'type'", ")", "getattr", "(", "self", ",", "'type_name'", ")", "getattr", "(", "self", ",", "'value_string'", ")" ]
https://github.com/NVIDIA/MDL-SDK/blob/aa9642b2546ad7b6236b5627385d882c2ed83c5d/src/mdl/jit/llvm/dist/bindings/python/llvm/object.py#L418-L425
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
contrib/gizmos/osx_carbon/gizmos.py
python
TreeListCtrl.GetChildrenCount
(*args, **kwargs)
return _gizmos.TreeListCtrl_GetChildrenCount(*args, **kwargs)
GetChildrenCount(self, TreeItemId item, bool recursively=True) -> size_t
GetChildrenCount(self, TreeItemId item, bool recursively=True) -> size_t
[ "GetChildrenCount", "(", "self", "TreeItemId", "item", "bool", "recursively", "=", "True", ")", "-", ">", "size_t" ]
def GetChildrenCount(*args, **kwargs): """GetChildrenCount(self, TreeItemId item, bool recursively=True) -> size_t""" return _gizmos.TreeListCtrl_GetChildrenCount(*args, **kwargs)
[ "def", "GetChildrenCount", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_gizmos", ".", "TreeListCtrl_GetChildrenCount", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/contrib/gizmos/osx_carbon/gizmos.py#L742-L744
yan99033/CNN-SVO
d5591ea88103f8d1b26e5296129bf3b3196a14f1
rpg_svo/svo_analysis/src/svo_analysis/tum_benchmark_tools/associate.py
python
read_file_list
(filename)
return dict(list)
Reads a trajectory from a text file. File format: The file format is "stamp d1 d2 d3 ...", where stamp denotes the time stamp (to be matched) and "d1 d2 d3.." is arbitary data (e.g., a 3D position and 3D orientation) associated to this timestamp. Input: filename -- File name Output: dict -- dictionary of (stamp,data) tuples
Reads a trajectory from a text file. File format: The file format is "stamp d1 d2 d3 ...", where stamp denotes the time stamp (to be matched) and "d1 d2 d3.." is arbitary data (e.g., a 3D position and 3D orientation) associated to this timestamp. Input: filename -- File name Output: dict -- dictionary of (stamp,data) tuples
[ "Reads", "a", "trajectory", "from", "a", "text", "file", ".", "File", "format", ":", "The", "file", "format", "is", "stamp", "d1", "d2", "d3", "...", "where", "stamp", "denotes", "the", "time", "stamp", "(", "to", "be", "matched", ")", "and", "d1", "d2", "d3", "..", "is", "arbitary", "data", "(", "e", ".", "g", ".", "a", "3D", "position", "and", "3D", "orientation", ")", "associated", "to", "this", "timestamp", ".", "Input", ":", "filename", "--", "File", "name", "Output", ":", "dict", "--", "dictionary", "of", "(", "stamp", "data", ")", "tuples" ]
def read_file_list(filename): """ Reads a trajectory from a text file. File format: The file format is "stamp d1 d2 d3 ...", where stamp denotes the time stamp (to be matched) and "d1 d2 d3.." is arbitary data (e.g., a 3D position and 3D orientation) associated to this timestamp. Input: filename -- File name Output: dict -- dictionary of (stamp,data) tuples """ file = open(filename) data = file.read() lines = data.replace(","," ").replace("\t"," ").split("\n") list = [[v.strip() for v in line.split(" ") if v.strip()!=""] for line in lines if len(line)>0 and line[0]!="#"] list = [(float(l[0]),l[1:]) for l in list if len(l)>1] return dict(list)
[ "def", "read_file_list", "(", "filename", ")", ":", "file", "=", "open", "(", "filename", ")", "data", "=", "file", ".", "read", "(", ")", "lines", "=", "data", ".", "replace", "(", "\",\"", ",", "\" \"", ")", ".", "replace", "(", "\"\\t\"", ",", "\" \"", ")", ".", "split", "(", "\"\\n\"", ")", "list", "=", "[", "[", "v", ".", "strip", "(", ")", "for", "v", "in", "line", ".", "split", "(", "\" \"", ")", "if", "v", ".", "strip", "(", ")", "!=", "\"\"", "]", "for", "line", "in", "lines", "if", "len", "(", "line", ")", ">", "0", "and", "line", "[", "0", "]", "!=", "\"#\"", "]", "list", "=", "[", "(", "float", "(", "l", "[", "0", "]", ")", ",", "l", "[", "1", ":", "]", ")", "for", "l", "in", "list", "if", "len", "(", "l", ")", ">", "1", "]", "return", "dict", "(", "list", ")" ]
https://github.com/yan99033/CNN-SVO/blob/d5591ea88103f8d1b26e5296129bf3b3196a14f1/rpg_svo/svo_analysis/src/svo_analysis/tum_benchmark_tools/associate.py#L49-L69
openmm/openmm
cb293447c4fc8b03976dfe11399f107bab70f3d9
wrappers/python/openmm/app/internal/pdbx/reader/PdbxParser.py
python
PdbxReader.__parser
(self, tokenizer, containerList)
Parser for PDBx data files and dictionaries. Input - tokenizer() reentrant method recognizing data item names (_category.attribute) quoted strings (single, double and multi-line semi-colon delimited), and unquoted strings. containerList - list-type container for data and definition objects parsed from from the input file. Return: containerList - is appended with data and definition objects -
Parser for PDBx data files and dictionaries.
[ "Parser", "for", "PDBx", "data", "files", "and", "dictionaries", "." ]
def __parser(self, tokenizer, containerList): """ Parser for PDBx data files and dictionaries. Input - tokenizer() reentrant method recognizing data item names (_category.attribute) quoted strings (single, double and multi-line semi-colon delimited), and unquoted strings. containerList - list-type container for data and definition objects parsed from from the input file. Return: containerList - is appended with data and definition objects - """ # Working container - data or definition curContainer = None # # Working category container categoryIndex = {} curCategory = None # curRow = None state = None # Find the first reserved word and begin capturing data. # while True: curCatName, curAttName, curQuotedString, curWord = next(tokenizer) if curWord is None: continue reservedWord, state = self.__getState(curWord) if reservedWord is not None: break while True: # # Set the current state - # # At this point in the processing cycle we are expecting a token containing # either a '_category.attribute' or a reserved word. # if curCatName is not None: state = "ST_KEY_VALUE_PAIR" elif curWord is not None: reservedWord, state = self.__getState(curWord) else: self.__syntaxError("Miscellaneous syntax error") return # # Process _category.attribute value assignments # if state == "ST_KEY_VALUE_PAIR": try: curCategory = categoryIndex[curCatName] except KeyError: # A new category is encountered - create a container and add a row curCategory = categoryIndex[curCatName] = DataCategory(curCatName) try: curContainer.append(curCategory) except AttributeError: self.__syntaxError("Category cannot be added to data_ block") return curRow = [] curCategory.append(curRow) else: # Recover the existing row from the category try: curRow = curCategory[0] except IndexError: self.__syntaxError("Internal index error accessing category data") return # Check for duplicate attributes and add attribute to table. if curAttName in curCategory.getAttributeList(): self.__syntaxError("Duplicate attribute encountered in category") return else: curCategory.appendAttribute(curAttName) # Get the data for this attribute from the next token tCat, tAtt, curQuotedString, curWord = next(tokenizer) if tCat is not None or (curQuotedString is None and curWord is None): self.__syntaxError("Missing data for item _%s.%s" % (curCatName,curAttName)) if curWord is not None: # # Validation check token for misplaced reserved words - # reservedWord, state = self.__getState(curWord) if reservedWord is not None: self.__syntaxError("Unexpected reserved word: %s" % (reservedWord)) curRow.append(curWord) elif curQuotedString is not None: curRow.append(curQuotedString) else: self.__syntaxError("Missing value in item-value pair") curCatName, curAttName, curQuotedString, curWord = next(tokenizer) continue # # Process a loop_ declaration and associated data - # elif state == "ST_TABLE": # The category name in the next curCatName,curAttName pair # defines the name of the category container. curCatName,curAttName,curQuotedString,curWord = next(tokenizer) if curCatName is None or curAttName is None: self.__syntaxError("Unexpected token in loop_ declaration") return # Check for a previous category declaration. if curCatName in categoryIndex: self.__syntaxError("Duplicate category declaration in loop_") return curCategory = DataCategory(curCatName) try: curContainer.append(curCategory) except AttributeError: self.__syntaxError("loop_ declaration outside of data_ block or save_ frame") return curCategory.appendAttribute(curAttName) # Read the rest of the loop_ declaration while True: curCatName, curAttName, curQuotedString, curWord = next(tokenizer) if curCatName is None: break if curCatName != curCategory.getName(): self.__syntaxError("Changed category name in loop_ declaration") return curCategory.appendAttribute(curAttName) # If the next token is a 'word', check it for any reserved words - if curWord is not None: reservedWord, state = self.__getState(curWord) if reservedWord is not None: if reservedWord == "stop": return else: self.__syntaxError("Unexpected reserved word after loop declaration: %s" % (reservedWord)) # Read the table of data for this loop_ - while True: curRow = [] curCategory.append(curRow) for tAtt in curCategory.getAttributeList(): if curWord is not None: curRow.append(curWord) elif curQuotedString is not None: curRow.append(curQuotedString) curCatName,curAttName,curQuotedString,curWord = next(tokenizer) # loop_ data processing ends if - # A new _category.attribute is encountered if curCatName is not None: break # A reserved word is encountered if curWord is not None: reservedWord, state = self.__getState(curWord) if reservedWord is not None: break continue elif state == "ST_DEFINITION": # Ignore trailing unnamed saveframe delimiters e.g. 'save_' sName=self.__getContainerName(curWord) if (len(sName) > 0): curContainer = DefinitionContainer(sName) containerList.append(curContainer) categoryIndex = {} curCategory = None curCatName,curAttName,curQuotedString,curWord = next(tokenizer) elif state == "ST_DATA_CONTAINER": # dName=self.__getContainerName(curWord) if len(dName) == 0: dName="unidentified" curContainer = DataContainer(dName) containerList.append(curContainer) categoryIndex = {} curCategory = None curCatName,curAttName,curQuotedString,curWord = next(tokenizer) elif state == "ST_STOP": return elif state == "ST_GLOBAL": curContainer = DataContainer("blank-global") curContainer.setGlobal() containerList.append(curContainer) categoryIndex = {} curCategory = None curCatName,curAttName,curQuotedString,curWord = next(tokenizer) elif state == "ST_UNKNOWN": self.__syntaxError("Unrecogized syntax element: " + str(curWord)) return
[ "def", "__parser", "(", "self", ",", "tokenizer", ",", "containerList", ")", ":", "# Working container - data or definition", "curContainer", "=", "None", "#", "# Working category container ", "categoryIndex", "=", "{", "}", "curCategory", "=", "None", "#", "curRow", "=", "None", "state", "=", "None", "# Find the first reserved word and begin capturing data.", "#", "while", "True", ":", "curCatName", ",", "curAttName", ",", "curQuotedString", ",", "curWord", "=", "next", "(", "tokenizer", ")", "if", "curWord", "is", "None", ":", "continue", "reservedWord", ",", "state", "=", "self", ".", "__getState", "(", "curWord", ")", "if", "reservedWord", "is", "not", "None", ":", "break", "while", "True", ":", "#", "# Set the current state -", "#", "# At this point in the processing cycle we are expecting a token containing", "# either a '_category.attribute' or a reserved word. ", "#", "if", "curCatName", "is", "not", "None", ":", "state", "=", "\"ST_KEY_VALUE_PAIR\"", "elif", "curWord", "is", "not", "None", ":", "reservedWord", ",", "state", "=", "self", ".", "__getState", "(", "curWord", ")", "else", ":", "self", ".", "__syntaxError", "(", "\"Miscellaneous syntax error\"", ")", "return", "#", "# Process _category.attribute value assignments ", "#", "if", "state", "==", "\"ST_KEY_VALUE_PAIR\"", ":", "try", ":", "curCategory", "=", "categoryIndex", "[", "curCatName", "]", "except", "KeyError", ":", "# A new category is encountered - create a container and add a row ", "curCategory", "=", "categoryIndex", "[", "curCatName", "]", "=", "DataCategory", "(", "curCatName", ")", "try", ":", "curContainer", ".", "append", "(", "curCategory", ")", "except", "AttributeError", ":", "self", ".", "__syntaxError", "(", "\"Category cannot be added to data_ block\"", ")", "return", "curRow", "=", "[", "]", "curCategory", ".", "append", "(", "curRow", ")", "else", ":", "# Recover the existing row from the category", "try", ":", "curRow", "=", "curCategory", "[", "0", "]", "except", "IndexError", ":", "self", ".", "__syntaxError", "(", "\"Internal index error accessing category data\"", ")", "return", "# Check for duplicate attributes and add attribute to table.", "if", "curAttName", "in", "curCategory", ".", "getAttributeList", "(", ")", ":", "self", ".", "__syntaxError", "(", "\"Duplicate attribute encountered in category\"", ")", "return", "else", ":", "curCategory", ".", "appendAttribute", "(", "curAttName", ")", "# Get the data for this attribute from the next token", "tCat", ",", "tAtt", ",", "curQuotedString", ",", "curWord", "=", "next", "(", "tokenizer", ")", "if", "tCat", "is", "not", "None", "or", "(", "curQuotedString", "is", "None", "and", "curWord", "is", "None", ")", ":", "self", ".", "__syntaxError", "(", "\"Missing data for item _%s.%s\"", "%", "(", "curCatName", ",", "curAttName", ")", ")", "if", "curWord", "is", "not", "None", ":", "# ", "# Validation check token for misplaced reserved words - ", "#", "reservedWord", ",", "state", "=", "self", ".", "__getState", "(", "curWord", ")", "if", "reservedWord", "is", "not", "None", ":", "self", ".", "__syntaxError", "(", "\"Unexpected reserved word: %s\"", "%", "(", "reservedWord", ")", ")", "curRow", ".", "append", "(", "curWord", ")", "elif", "curQuotedString", "is", "not", "None", ":", "curRow", ".", "append", "(", "curQuotedString", ")", "else", ":", "self", ".", "__syntaxError", "(", "\"Missing value in item-value pair\"", ")", "curCatName", ",", "curAttName", ",", "curQuotedString", ",", "curWord", "=", "next", "(", "tokenizer", ")", "continue", "#", "# Process a loop_ declaration and associated data -", "#", "elif", "state", "==", "\"ST_TABLE\"", ":", "# The category name in the next curCatName,curAttName pair", "# defines the name of the category container.", "curCatName", ",", "curAttName", ",", "curQuotedString", ",", "curWord", "=", "next", "(", "tokenizer", ")", "if", "curCatName", "is", "None", "or", "curAttName", "is", "None", ":", "self", ".", "__syntaxError", "(", "\"Unexpected token in loop_ declaration\"", ")", "return", "# Check for a previous category declaration.", "if", "curCatName", "in", "categoryIndex", ":", "self", ".", "__syntaxError", "(", "\"Duplicate category declaration in loop_\"", ")", "return", "curCategory", "=", "DataCategory", "(", "curCatName", ")", "try", ":", "curContainer", ".", "append", "(", "curCategory", ")", "except", "AttributeError", ":", "self", ".", "__syntaxError", "(", "\"loop_ declaration outside of data_ block or save_ frame\"", ")", "return", "curCategory", ".", "appendAttribute", "(", "curAttName", ")", "# Read the rest of the loop_ declaration ", "while", "True", ":", "curCatName", ",", "curAttName", ",", "curQuotedString", ",", "curWord", "=", "next", "(", "tokenizer", ")", "if", "curCatName", "is", "None", ":", "break", "if", "curCatName", "!=", "curCategory", ".", "getName", "(", ")", ":", "self", ".", "__syntaxError", "(", "\"Changed category name in loop_ declaration\"", ")", "return", "curCategory", ".", "appendAttribute", "(", "curAttName", ")", "# If the next token is a 'word', check it for any reserved words - ", "if", "curWord", "is", "not", "None", ":", "reservedWord", ",", "state", "=", "self", ".", "__getState", "(", "curWord", ")", "if", "reservedWord", "is", "not", "None", ":", "if", "reservedWord", "==", "\"stop\"", ":", "return", "else", ":", "self", ".", "__syntaxError", "(", "\"Unexpected reserved word after loop declaration: %s\"", "%", "(", "reservedWord", ")", ")", "# Read the table of data for this loop_ - ", "while", "True", ":", "curRow", "=", "[", "]", "curCategory", ".", "append", "(", "curRow", ")", "for", "tAtt", "in", "curCategory", ".", "getAttributeList", "(", ")", ":", "if", "curWord", "is", "not", "None", ":", "curRow", ".", "append", "(", "curWord", ")", "elif", "curQuotedString", "is", "not", "None", ":", "curRow", ".", "append", "(", "curQuotedString", ")", "curCatName", ",", "curAttName", ",", "curQuotedString", ",", "curWord", "=", "next", "(", "tokenizer", ")", "# loop_ data processing ends if - ", "# A new _category.attribute is encountered", "if", "curCatName", "is", "not", "None", ":", "break", "# A reserved word is encountered", "if", "curWord", "is", "not", "None", ":", "reservedWord", ",", "state", "=", "self", ".", "__getState", "(", "curWord", ")", "if", "reservedWord", "is", "not", "None", ":", "break", "continue", "elif", "state", "==", "\"ST_DEFINITION\"", ":", "# Ignore trailing unnamed saveframe delimiters e.g. 'save_'", "sName", "=", "self", ".", "__getContainerName", "(", "curWord", ")", "if", "(", "len", "(", "sName", ")", ">", "0", ")", ":", "curContainer", "=", "DefinitionContainer", "(", "sName", ")", "containerList", ".", "append", "(", "curContainer", ")", "categoryIndex", "=", "{", "}", "curCategory", "=", "None", "curCatName", ",", "curAttName", ",", "curQuotedString", ",", "curWord", "=", "next", "(", "tokenizer", ")", "elif", "state", "==", "\"ST_DATA_CONTAINER\"", ":", "#", "dName", "=", "self", ".", "__getContainerName", "(", "curWord", ")", "if", "len", "(", "dName", ")", "==", "0", ":", "dName", "=", "\"unidentified\"", "curContainer", "=", "DataContainer", "(", "dName", ")", "containerList", ".", "append", "(", "curContainer", ")", "categoryIndex", "=", "{", "}", "curCategory", "=", "None", "curCatName", ",", "curAttName", ",", "curQuotedString", ",", "curWord", "=", "next", "(", "tokenizer", ")", "elif", "state", "==", "\"ST_STOP\"", ":", "return", "elif", "state", "==", "\"ST_GLOBAL\"", ":", "curContainer", "=", "DataContainer", "(", "\"blank-global\"", ")", "curContainer", ".", "setGlobal", "(", ")", "containerList", ".", "append", "(", "curContainer", ")", "categoryIndex", "=", "{", "}", "curCategory", "=", "None", "curCatName", ",", "curAttName", ",", "curQuotedString", ",", "curWord", "=", "next", "(", "tokenizer", ")", "elif", "state", "==", "\"ST_UNKNOWN\"", ":", "self", ".", "__syntaxError", "(", "\"Unrecogized syntax element: \"", "+", "str", "(", "curWord", ")", ")", "return" ]
https://github.com/openmm/openmm/blob/cb293447c4fc8b03976dfe11399f107bab70f3d9/wrappers/python/openmm/app/internal/pdbx/reader/PdbxParser.py#L118-L338
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_gdi.py
python
IconLocation.__init__
(self, *args, **kwargs)
__init__(self, String filename=&wxPyEmptyString, int num=0) -> IconLocation
__init__(self, String filename=&wxPyEmptyString, int num=0) -> IconLocation
[ "__init__", "(", "self", "String", "filename", "=", "&wxPyEmptyString", "int", "num", "=", "0", ")", "-", ">", "IconLocation" ]
def __init__(self, *args, **kwargs): """__init__(self, String filename=&wxPyEmptyString, int num=0) -> IconLocation""" _gdi_.IconLocation_swiginit(self,_gdi_.new_IconLocation(*args, **kwargs))
[ "def", "__init__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "_gdi_", ".", "IconLocation_swiginit", "(", "self", ",", "_gdi_", ".", "new_IconLocation", "(", "*", "args", ",", "*", "*", "kwargs", ")", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_gdi.py#L1354-L1356
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/ipython/py2/IPython/utils/strdispatch.py
python
StrDispatch.dispatch
(self, key)
Get a seq of Commandchain objects that match key
Get a seq of Commandchain objects that match key
[ "Get", "a", "seq", "of", "Commandchain", "objects", "that", "match", "key" ]
def dispatch(self, key): """ Get a seq of Commandchain objects that match key """ if key in self.strs: yield self.strs[key] for r, obj in self.regexs.items(): if re.match(r, key): yield obj else: #print "nomatch",key # dbg pass
[ "def", "dispatch", "(", "self", ",", "key", ")", ":", "if", "key", "in", "self", ".", "strs", ":", "yield", "self", ".", "strs", "[", "key", "]", "for", "r", ",", "obj", "in", "self", ".", "regexs", ".", "items", "(", ")", ":", "if", "re", ".", "match", "(", "r", ",", "key", ")", ":", "yield", "obj", "else", ":", "#print \"nomatch\",key # dbg", "pass" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/ipython/py2/IPython/utils/strdispatch.py#L42-L52
ceph/ceph
959663007321a369c83218414a29bd9dbc8bda3a
qa/tasks/ceph_manager.py
python
CephManager.get_pool_pg_num
(self, pool_name)
Return the number of pgs in the pool specified.
Return the number of pgs in the pool specified.
[ "Return", "the", "number", "of", "pgs", "in", "the", "pool", "specified", "." ]
def get_pool_pg_num(self, pool_name): """ Return the number of pgs in the pool specified. """ with self.lock: assert isinstance(pool_name, str) if pool_name in self.pools: return self.pools[pool_name] return 0
[ "def", "get_pool_pg_num", "(", "self", ",", "pool_name", ")", ":", "with", "self", ".", "lock", ":", "assert", "isinstance", "(", "pool_name", ",", "str", ")", "if", "pool_name", "in", "self", ".", "pools", ":", "return", "self", ".", "pools", "[", "pool_name", "]", "return", "0" ]
https://github.com/ceph/ceph/blob/959663007321a369c83218414a29bd9dbc8bda3a/qa/tasks/ceph_manager.py#L2172-L2180
yushroom/FishEngine
a4b9fb9b0a6dc202f7990e75f4b7d8d5163209d9
Script/reflect/clang/cindex.py
python
Cursor.is_static_method
(self)
return conf.lib.clang_CXXMethod_isStatic(self)
Returns True if the cursor refers to a C++ member function or member function template that is declared 'static'.
Returns True if the cursor refers to a C++ member function or member function template that is declared 'static'.
[ "Returns", "True", "if", "the", "cursor", "refers", "to", "a", "C", "++", "member", "function", "or", "member", "function", "template", "that", "is", "declared", "static", "." ]
def is_static_method(self): """Returns True if the cursor refers to a C++ member function or member function template that is declared 'static'. """ return conf.lib.clang_CXXMethod_isStatic(self)
[ "def", "is_static_method", "(", "self", ")", ":", "return", "conf", ".", "lib", ".", "clang_CXXMethod_isStatic", "(", "self", ")" ]
https://github.com/yushroom/FishEngine/blob/a4b9fb9b0a6dc202f7990e75f4b7d8d5163209d9/Script/reflect/clang/cindex.py#L1390-L1394
nci/drishti
89cd8b740239c5b2c8222dffd4e27432fde170a1
bin/assets/scripts/unet3Plus/unet_collection/layer_utils.py
python
encode_layer
(X, channel, pool_size, pool, kernel_size='auto', activation='ReLU', batch_norm=False, name='encode')
return X
An overall encode layer, based on one of the: (1) max-pooling, (2) average-pooling, (3) strided conv2d. encode_layer(X, channel, pool_size, pool, kernel_size='auto', activation='ReLU', batch_norm=False, name='encode') Input ---------- X: input tensor. pool_size: the encoding factor. channel: (for strided conv only) number of convolution filters. pool: True or 'max' for MaxPooling2D. 'ave' for AveragePooling2D. False for strided conv + batch norm + activation. kernel_size: size of convolution kernels. If kernel_size='auto', then it equals to the `pool_size`. activation: one of the `tensorflow.keras.layers` interface, e.g., ReLU. batch_norm: True for batch normalization, False otherwise. name: prefix of the created keras layers. Output ---------- X: output tensor.
An overall encode layer, based on one of the: (1) max-pooling, (2) average-pooling, (3) strided conv2d. encode_layer(X, channel, pool_size, pool, kernel_size='auto', activation='ReLU', batch_norm=False, name='encode') Input ---------- X: input tensor. pool_size: the encoding factor. channel: (for strided conv only) number of convolution filters. pool: True or 'max' for MaxPooling2D. 'ave' for AveragePooling2D. False for strided conv + batch norm + activation. kernel_size: size of convolution kernels. If kernel_size='auto', then it equals to the `pool_size`. activation: one of the `tensorflow.keras.layers` interface, e.g., ReLU. batch_norm: True for batch normalization, False otherwise. name: prefix of the created keras layers. Output ---------- X: output tensor.
[ "An", "overall", "encode", "layer", "based", "on", "one", "of", "the", ":", "(", "1", ")", "max", "-", "pooling", "(", "2", ")", "average", "-", "pooling", "(", "3", ")", "strided", "conv2d", ".", "encode_layer", "(", "X", "channel", "pool_size", "pool", "kernel_size", "=", "auto", "activation", "=", "ReLU", "batch_norm", "=", "False", "name", "=", "encode", ")", "Input", "----------", "X", ":", "input", "tensor", ".", "pool_size", ":", "the", "encoding", "factor", ".", "channel", ":", "(", "for", "strided", "conv", "only", ")", "number", "of", "convolution", "filters", ".", "pool", ":", "True", "or", "max", "for", "MaxPooling2D", ".", "ave", "for", "AveragePooling2D", ".", "False", "for", "strided", "conv", "+", "batch", "norm", "+", "activation", ".", "kernel_size", ":", "size", "of", "convolution", "kernels", ".", "If", "kernel_size", "=", "auto", "then", "it", "equals", "to", "the", "pool_size", ".", "activation", ":", "one", "of", "the", "tensorflow", ".", "keras", ".", "layers", "interface", "e", ".", "g", ".", "ReLU", ".", "batch_norm", ":", "True", "for", "batch", "normalization", "False", "otherwise", ".", "name", ":", "prefix", "of", "the", "created", "keras", "layers", ".", "Output", "----------", "X", ":", "output", "tensor", "." ]
def encode_layer(X, channel, pool_size, pool, kernel_size='auto', activation='ReLU', batch_norm=False, name='encode'): ''' An overall encode layer, based on one of the: (1) max-pooling, (2) average-pooling, (3) strided conv2d. encode_layer(X, channel, pool_size, pool, kernel_size='auto', activation='ReLU', batch_norm=False, name='encode') Input ---------- X: input tensor. pool_size: the encoding factor. channel: (for strided conv only) number of convolution filters. pool: True or 'max' for MaxPooling2D. 'ave' for AveragePooling2D. False for strided conv + batch norm + activation. kernel_size: size of convolution kernels. If kernel_size='auto', then it equals to the `pool_size`. activation: one of the `tensorflow.keras.layers` interface, e.g., ReLU. batch_norm: True for batch normalization, False otherwise. name: prefix of the created keras layers. Output ---------- X: output tensor. ''' # parsers if (pool in [False, True, 'max', 'ave']) is not True: raise ValueError('Invalid pool keyword') # maxpooling2d as default if pool is True: pool = 'max' elif pool is False: # stride conv configurations bias_flag = not batch_norm if pool == 'max': X = MaxPooling2D(pool_size=(pool_size, pool_size), name='{}_maxpool'.format(name))(X) elif pool == 'ave': X = AveragePooling2D(pool_size=(pool_size, pool_size), name='{}_avepool'.format(name))(X) else: if kernel_size == 'auto': kernel_size = pool_size # linear convolution with strides X = Conv2D(channel, kernel_size, strides=(pool_size, pool_size), padding='valid', use_bias=bias_flag, name='{}_stride_conv'.format(name))(X) # batch normalization if batch_norm: X = BatchNormalization(axis=3, name='{}_bn'.format(name))(X) # activation if activation is not None: activation_func = eval(activation) X = activation_func(name='{}_activation'.format(name))(X) return X
[ "def", "encode_layer", "(", "X", ",", "channel", ",", "pool_size", ",", "pool", ",", "kernel_size", "=", "'auto'", ",", "activation", "=", "'ReLU'", ",", "batch_norm", "=", "False", ",", "name", "=", "'encode'", ")", ":", "# parsers", "if", "(", "pool", "in", "[", "False", ",", "True", ",", "'max'", ",", "'ave'", "]", ")", "is", "not", "True", ":", "raise", "ValueError", "(", "'Invalid pool keyword'", ")", "# maxpooling2d as default", "if", "pool", "is", "True", ":", "pool", "=", "'max'", "elif", "pool", "is", "False", ":", "# stride conv configurations", "bias_flag", "=", "not", "batch_norm", "if", "pool", "==", "'max'", ":", "X", "=", "MaxPooling2D", "(", "pool_size", "=", "(", "pool_size", ",", "pool_size", ")", ",", "name", "=", "'{}_maxpool'", ".", "format", "(", "name", ")", ")", "(", "X", ")", "elif", "pool", "==", "'ave'", ":", "X", "=", "AveragePooling2D", "(", "pool_size", "=", "(", "pool_size", ",", "pool_size", ")", ",", "name", "=", "'{}_avepool'", ".", "format", "(", "name", ")", ")", "(", "X", ")", "else", ":", "if", "kernel_size", "==", "'auto'", ":", "kernel_size", "=", "pool_size", "# linear convolution with strides", "X", "=", "Conv2D", "(", "channel", ",", "kernel_size", ",", "strides", "=", "(", "pool_size", ",", "pool_size", ")", ",", "padding", "=", "'valid'", ",", "use_bias", "=", "bias_flag", ",", "name", "=", "'{}_stride_conv'", ".", "format", "(", "name", ")", ")", "(", "X", ")", "# batch normalization", "if", "batch_norm", ":", "X", "=", "BatchNormalization", "(", "axis", "=", "3", ",", "name", "=", "'{}_bn'", ".", "format", "(", "name", ")", ")", "(", "X", ")", "# activation", "if", "activation", "is", "not", "None", ":", "activation_func", "=", "eval", "(", "activation", ")", "X", "=", "activation_func", "(", "name", "=", "'{}_activation'", ".", "format", "(", "name", ")", ")", "(", "X", ")", "return", "X" ]
https://github.com/nci/drishti/blob/89cd8b740239c5b2c8222dffd4e27432fde170a1/bin/assets/scripts/unet3Plus/unet_collection/layer_utils.py#L75-L138
Tencent/mars
54969ba56b402a622db123e780a4f760b38c5c36
mars/lint/cpplint.py
python
_CppLintState.RestoreFilters
(self)
Restores filters previously backed up.
Restores filters previously backed up.
[ "Restores", "filters", "previously", "backed", "up", "." ]
def RestoreFilters(self): """ Restores filters previously backed up.""" self.filters = self._filters_backup[:]
[ "def", "RestoreFilters", "(", "self", ")", ":", "self", ".", "filters", "=", "self", ".", "_filters_backup", "[", ":", "]" ]
https://github.com/Tencent/mars/blob/54969ba56b402a622db123e780a4f760b38c5c36/mars/lint/cpplint.py#L823-L825
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/x86/toolchain/lib/python2.7/plat-mac/lib-scriptpackages/Netscape/Required_suite.py
python
Required_suite_Events.open
(self, _object, _attributes={}, **_arguments)
open: Open the specified object(s) Required argument: list of objects to open Keyword argument _attributes: AppleEvent attribute dictionary
open: Open the specified object(s) Required argument: list of objects to open Keyword argument _attributes: AppleEvent attribute dictionary
[ "open", ":", "Open", "the", "specified", "object", "(", "s", ")", "Required", "argument", ":", "list", "of", "objects", "to", "open", "Keyword", "argument", "_attributes", ":", "AppleEvent", "attribute", "dictionary" ]
def open(self, _object, _attributes={}, **_arguments): """open: Open the specified object(s) Required argument: list of objects to open Keyword argument _attributes: AppleEvent attribute dictionary """ _code = 'aevt' _subcode = 'odoc' if _arguments: raise TypeError, 'No optional args expected' _arguments['----'] = _object _reply, _arguments, _attributes = self.send(_code, _subcode, _arguments, _attributes) if _arguments.get('errn', 0): raise aetools.Error, aetools.decodeerror(_arguments) # XXXX Optionally decode result if _arguments.has_key('----'): return _arguments['----']
[ "def", "open", "(", "self", ",", "_object", ",", "_attributes", "=", "{", "}", ",", "*", "*", "_arguments", ")", ":", "_code", "=", "'aevt'", "_subcode", "=", "'odoc'", "if", "_arguments", ":", "raise", "TypeError", ",", "'No optional args expected'", "_arguments", "[", "'----'", "]", "=", "_object", "_reply", ",", "_arguments", ",", "_attributes", "=", "self", ".", "send", "(", "_code", ",", "_subcode", ",", "_arguments", ",", "_attributes", ")", "if", "_arguments", ".", "get", "(", "'errn'", ",", "0", ")", ":", "raise", "aetools", ".", "Error", ",", "aetools", ".", "decodeerror", "(", "_arguments", ")", "# XXXX Optionally decode result", "if", "_arguments", ".", "has_key", "(", "'----'", ")", ":", "return", "_arguments", "[", "'----'", "]" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/plat-mac/lib-scriptpackages/Netscape/Required_suite.py#L16-L34
apple/turicreate
cce55aa5311300e3ce6af93cb45ba791fd1bdf49
src/python/turicreate/data_structures/sarray.py
python
SArray.__repr__
(self)
return ret
Returns a string description of the SArray.
Returns a string description of the SArray.
[ "Returns", "a", "string", "description", "of", "the", "SArray", "." ]
def __repr__(self): """ Returns a string description of the SArray. """ data_str = self.__str__() ret = "dtype: " + str(self.dtype.__name__) + "\n" if self.__has_size__(): ret = ret + "Rows: " + str(len(self)) + "\n" else: ret = ret + "Rows: ?\n" ret = ret + data_str return ret
[ "def", "__repr__", "(", "self", ")", ":", "data_str", "=", "self", ".", "__str__", "(", ")", "ret", "=", "\"dtype: \"", "+", "str", "(", "self", ".", "dtype", ".", "__name__", ")", "+", "\"\\n\"", "if", "self", ".", "__has_size__", "(", ")", ":", "ret", "=", "ret", "+", "\"Rows: \"", "+", "str", "(", "len", "(", "self", ")", ")", "+", "\"\\n\"", "else", ":", "ret", "=", "ret", "+", "\"Rows: ?\\n\"", "ret", "=", "ret", "+", "data_str", "return", "ret" ]
https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/src/python/turicreate/data_structures/sarray.py#L843-L854
MythTV/mythtv
d282a209cb8be85d036f85a62a8ec971b67d45f4
mythtv/programs/scripts/metadata/Music/musicbrainzngs/musicbrainz.py
python
set_format
(fmt="xml")
Sets the format that should be returned by the Web Service. The server currently supports `xml` and `json`. This method will set a default parser for the specified format, but you can modify it with :func:`set_parser`. .. warning:: The json format used by the server is different from the json format returned by the `musicbrainzngs` internal parser when using the `xml` format! This format may change at any time.
Sets the format that should be returned by the Web Service. The server currently supports `xml` and `json`.
[ "Sets", "the", "format", "that", "should", "be", "returned", "by", "the", "Web", "Service", ".", "The", "server", "currently", "supports", "xml", "and", "json", "." ]
def set_format(fmt="xml"): """Sets the format that should be returned by the Web Service. The server currently supports `xml` and `json`. This method will set a default parser for the specified format, but you can modify it with :func:`set_parser`. .. warning:: The json format used by the server is different from the json format returned by the `musicbrainzngs` internal parser when using the `xml` format! This format may change at any time. """ global ws_format if fmt == "xml": ws_format = fmt set_parser() # set to default elif fmt == "json": ws_format = fmt warn("The json format is non-official and may change at any time") set_parser(json.loads) else: raise ValueError("invalid format: %s" % fmt)
[ "def", "set_format", "(", "fmt", "=", "\"xml\"", ")", ":", "global", "ws_format", "if", "fmt", "==", "\"xml\"", ":", "ws_format", "=", "fmt", "set_parser", "(", ")", "# set to default", "elif", "fmt", "==", "\"json\"", ":", "ws_format", "=", "fmt", "warn", "(", "\"The json format is non-official and may change at any time\"", ")", "set_parser", "(", "json", ".", "loads", ")", "else", ":", "raise", "ValueError", "(", "\"invalid format: %s\"", "%", "fmt", ")" ]
https://github.com/MythTV/mythtv/blob/d282a209cb8be85d036f85a62a8ec971b67d45f4/mythtv/programs/scripts/metadata/Music/musicbrainzngs/musicbrainz.py#L560-L580
gromacs/gromacs
7dec3a3f99993cf5687a122de3e12de31c21c399
python_packaging/src/gmxapi/operation.py
python
ResultDescription.width
(self)
return self._width
ensemble width
ensemble width
[ "ensemble", "width" ]
def width(self) -> int: """ensemble width""" return self._width
[ "def", "width", "(", "self", ")", "->", "int", ":", "return", "self", ".", "_width" ]
https://github.com/gromacs/gromacs/blob/7dec3a3f99993cf5687a122de3e12de31c21c399/python_packaging/src/gmxapi/operation.py#L105-L107
adobe/chromium
cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7
media/tools/constrained_network_server/traffic_control.py
python
_CheckArgsExist
(config, *args)
Check that the args exist in config dictionary and are not None. Args: config: Any dictionary. *args: The list of key names to check. Raises: TrafficControlError: If any key name does not exist in config or is None.
Check that the args exist in config dictionary and are not None.
[ "Check", "that", "the", "args", "exist", "in", "config", "dictionary", "and", "are", "not", "None", "." ]
def _CheckArgsExist(config, *args): """Check that the args exist in config dictionary and are not None. Args: config: Any dictionary. *args: The list of key names to check. Raises: TrafficControlError: If any key name does not exist in config or is None. """ for key in args: if key not in config.keys() or config[key] is None: raise TrafficControlError('Missing "%s" parameter.' % key)
[ "def", "_CheckArgsExist", "(", "config", ",", "*", "args", ")", ":", "for", "key", "in", "args", ":", "if", "key", "not", "in", "config", ".", "keys", "(", ")", "or", "config", "[", "key", "]", "is", "None", ":", "raise", "TrafficControlError", "(", "'Missing \"%s\" parameter.'", "%", "key", ")" ]
https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/media/tools/constrained_network_server/traffic_control.py#L145-L157
hughperkins/tf-coriander
970d3df6c11400ad68405f22b0c42a52374e94ca
tensorflow/python/summary/impl/reservoir.py
python
Reservoir.Keys
(self)
Return all the keys in the reservoir. Returns: ['list', 'of', 'keys'] in the Reservoir.
Return all the keys in the reservoir.
[ "Return", "all", "the", "keys", "in", "the", "reservoir", "." ]
def Keys(self): """Return all the keys in the reservoir. Returns: ['list', 'of', 'keys'] in the Reservoir. """ with self._mutex: return list(self._buckets.keys())
[ "def", "Keys", "(", "self", ")", ":", "with", "self", ".", "_mutex", ":", "return", "list", "(", "self", ".", "_buckets", ".", "keys", "(", ")", ")" ]
https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/python/summary/impl/reservoir.py#L79-L86
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/msilib/__init__.py
python
Directory.remove_pyc
(self)
Remove .pyc files on uninstall
Remove .pyc files on uninstall
[ "Remove", ".", "pyc", "files", "on", "uninstall" ]
def remove_pyc(self): "Remove .pyc files on uninstall" add_data(self.db, "RemoveFile", [(self.component+"c", self.component, "*.pyc", self.logical, 2)])
[ "def", "remove_pyc", "(", "self", ")", ":", "add_data", "(", "self", ".", "db", ",", "\"RemoveFile\"", ",", "[", "(", "self", ".", "component", "+", "\"c\"", ",", "self", ".", "component", ",", "\"*.pyc\"", ",", "self", ".", "logical", ",", "2", ")", "]", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/msilib/__init__.py#L392-L395
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/jira/client.py
python
JIRA.user_avatars
(self, username)
return self._get_json('user/avatars', params={'username': username})
Get a dict of avatars for the specified user. :param username: the username to get avatars for
Get a dict of avatars for the specified user.
[ "Get", "a", "dict", "of", "avatars", "for", "the", "specified", "user", "." ]
def user_avatars(self, username): """Get a dict of avatars for the specified user. :param username: the username to get avatars for """ return self._get_json('user/avatars', params={'username': username})
[ "def", "user_avatars", "(", "self", ",", "username", ")", ":", "return", "self", ".", "_get_json", "(", "'user/avatars'", ",", "params", "=", "{", "'username'", ":", "username", "}", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/jira/client.py#L2184-L2189
amd/OpenCL-caffe
638543108517265366c18ae5821f3096cf5cf34a
scripts/cpp_lint.py
python
Error
(filename, linenum, category, confidence, message)
Logs the fact we've found a lint error. We log where the error was found, and also our confidence in the error, that is, how certain we are this is a legitimate style regression, and not a misidentification or a use that's sometimes justified. False positives can be suppressed by the use of "cpplint(category)" comments on the offending line. These are parsed into _error_suppressions. Args: filename: The name of the file containing the error. linenum: The number of the line containing the error. category: A string used to describe the "category" this bug falls under: "whitespace", say, or "runtime". Categories may have a hierarchy separated by slashes: "whitespace/indent". confidence: A number from 1-5 representing a confidence score for the error, with 5 meaning that we are certain of the problem, and 1 meaning that it could be a legitimate construct. message: The error message.
Logs the fact we've found a lint error.
[ "Logs", "the", "fact", "we", "ve", "found", "a", "lint", "error", "." ]
def Error(filename, linenum, category, confidence, message): """Logs the fact we've found a lint error. We log where the error was found, and also our confidence in the error, that is, how certain we are this is a legitimate style regression, and not a misidentification or a use that's sometimes justified. False positives can be suppressed by the use of "cpplint(category)" comments on the offending line. These are parsed into _error_suppressions. Args: filename: The name of the file containing the error. linenum: The number of the line containing the error. category: A string used to describe the "category" this bug falls under: "whitespace", say, or "runtime". Categories may have a hierarchy separated by slashes: "whitespace/indent". confidence: A number from 1-5 representing a confidence score for the error, with 5 meaning that we are certain of the problem, and 1 meaning that it could be a legitimate construct. message: The error message. """ if _ShouldPrintError(category, confidence, linenum): _cpplint_state.IncrementErrorCount(category) if _cpplint_state.output_format == 'vs7': sys.stderr.write('%s(%s): %s [%s] [%d]\n' % ( filename, linenum, message, category, confidence)) elif _cpplint_state.output_format == 'eclipse': sys.stderr.write('%s:%s: warning: %s [%s] [%d]\n' % ( filename, linenum, message, category, confidence)) else: sys.stderr.write('%s:%s: %s [%s] [%d]\n' % ( filename, linenum, message, category, confidence))
[ "def", "Error", "(", "filename", ",", "linenum", ",", "category", ",", "confidence", ",", "message", ")", ":", "if", "_ShouldPrintError", "(", "category", ",", "confidence", ",", "linenum", ")", ":", "_cpplint_state", ".", "IncrementErrorCount", "(", "category", ")", "if", "_cpplint_state", ".", "output_format", "==", "'vs7'", ":", "sys", ".", "stderr", ".", "write", "(", "'%s(%s): %s [%s] [%d]\\n'", "%", "(", "filename", ",", "linenum", ",", "message", ",", "category", ",", "confidence", ")", ")", "elif", "_cpplint_state", ".", "output_format", "==", "'eclipse'", ":", "sys", ".", "stderr", ".", "write", "(", "'%s:%s: warning: %s [%s] [%d]\\n'", "%", "(", "filename", ",", "linenum", ",", "message", ",", "category", ",", "confidence", ")", ")", "else", ":", "sys", ".", "stderr", ".", "write", "(", "'%s:%s: %s [%s] [%d]\\n'", "%", "(", "filename", ",", "linenum", ",", "message", ",", "category", ",", "confidence", ")", ")" ]
https://github.com/amd/OpenCL-caffe/blob/638543108517265366c18ae5821f3096cf5cf34a/scripts/cpp_lint.py#L988-L1020
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/Blast/houdini/python2.7libs/blastExport/slice.py
python
Slice.editorLockComponentId
(self, value)
:return: str
:return: str
[ ":", "return", ":", "str" ]
def editorLockComponentId(self, value): """ :return: str """ if self.__editorLockComponentId == value: return self.__editorLockComponentId = value
[ "def", "editorLockComponentId", "(", "self", ",", "value", ")", ":", "if", "self", ".", "__editorLockComponentId", "==", "value", ":", "return", "self", ".", "__editorLockComponentId", "=", "value" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/Blast/houdini/python2.7libs/blastExport/slice.py#L437-L445
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/tools/Editra/src/ed_stc.py
python
EditraStc.IsBracketHlOn
(self)
return self._config['brackethl']
Returns whether bracket highlighting is being used by this control or not. @return: status of bracket highlight activation
Returns whether bracket highlighting is being used by this control or not. @return: status of bracket highlight activation
[ "Returns", "whether", "bracket", "highlighting", "is", "being", "used", "by", "this", "control", "or", "not", ".", "@return", ":", "status", "of", "bracket", "highlight", "activation" ]
def IsBracketHlOn(self): """Returns whether bracket highlighting is being used by this control or not. @return: status of bracket highlight activation """ return self._config['brackethl']
[ "def", "IsBracketHlOn", "(", "self", ")", ":", "return", "self", ".", "_config", "[", "'brackethl'", "]" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/ed_stc.py#L1308-L1314
iam-abbas/cs-algorithms
d04aa8fd9a1fa290266dde96afe9b90ee23c5a92
Binomial_heap.py
python
BinomialHeap.__traversal
(self, curr_node, preorder, level=0)
Pre-order traversal of nodes
Pre-order traversal of nodes
[ "Pre", "-", "order", "traversal", "of", "nodes" ]
def __traversal(self, curr_node, preorder, level=0): """ Pre-order traversal of nodes """ if curr_node: preorder.append((curr_node.val, level)) self.__traversal( curr_node.left, preorder, level + 1 ) self.__traversal( curr_node.right, preorder, level + 1 ) else: preorder.append(("#", level))
[ "def", "__traversal", "(", "self", ",", "curr_node", ",", "preorder", ",", "level", "=", "0", ")", ":", "if", "curr_node", ":", "preorder", ".", "append", "(", "(", "curr_node", ".", "val", ",", "level", ")", ")", "self", ".", "__traversal", "(", "curr_node", ".", "left", ",", "preorder", ",", "level", "+", "1", ")", "self", ".", "__traversal", "(", "curr_node", ".", "right", ",", "preorder", ",", "level", "+", "1", ")", "else", ":", "preorder", ".", "append", "(", "(", "\"#\"", ",", "level", ")", ")" ]
https://github.com/iam-abbas/cs-algorithms/blob/d04aa8fd9a1fa290266dde96afe9b90ee23c5a92/Binomial_heap.py#L403-L416
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/data/experimental/ops/readers.py
python
_infer_type
(str_val, na_value, prev_type)
Given a string, infers its tensor type. Infers the type of a value by picking the least 'permissive' type possible, while still allowing the previous type inference for this column to be valid. Args: str_val: String value to infer the type of. na_value: Additional string to recognize as a NA/NaN CSV value. prev_type: Type previously inferred based on values of this column that we've seen up till now. Returns: Inferred dtype.
Given a string, infers its tensor type.
[ "Given", "a", "string", "infers", "its", "tensor", "type", "." ]
def _infer_type(str_val, na_value, prev_type): """Given a string, infers its tensor type. Infers the type of a value by picking the least 'permissive' type possible, while still allowing the previous type inference for this column to be valid. Args: str_val: String value to infer the type of. na_value: Additional string to recognize as a NA/NaN CSV value. prev_type: Type previously inferred based on values of this column that we've seen up till now. Returns: Inferred dtype. """ if str_val in ("", na_value): # If the field is null, it gives no extra information about its type return prev_type type_list = [ dtypes.int32, dtypes.int64, dtypes.float32, dtypes.float64, dtypes.string ] # list of types to try, ordered from least permissive to most type_functions = [ _is_valid_int32, _is_valid_int64, lambda str_val: _is_valid_float(str_val, dtypes.float32), lambda str_val: _is_valid_float(str_val, dtypes.float64), lambda str_val: True, ] # Corresponding list of validation functions for i in range(len(type_list)): validation_fn = type_functions[i] if validation_fn(str_val) and (prev_type is None or prev_type in type_list[:i + 1]): return type_list[i]
[ "def", "_infer_type", "(", "str_val", ",", "na_value", ",", "prev_type", ")", ":", "if", "str_val", "in", "(", "\"\"", ",", "na_value", ")", ":", "# If the field is null, it gives no extra information about its type", "return", "prev_type", "type_list", "=", "[", "dtypes", ".", "int32", ",", "dtypes", ".", "int64", ",", "dtypes", ".", "float32", ",", "dtypes", ".", "float64", ",", "dtypes", ".", "string", "]", "# list of types to try, ordered from least permissive to most", "type_functions", "=", "[", "_is_valid_int32", ",", "_is_valid_int64", ",", "lambda", "str_val", ":", "_is_valid_float", "(", "str_val", ",", "dtypes", ".", "float32", ")", ",", "lambda", "str_val", ":", "_is_valid_float", "(", "str_val", ",", "dtypes", ".", "float64", ")", ",", "lambda", "str_val", ":", "True", ",", "]", "# Corresponding list of validation functions", "for", "i", "in", "range", "(", "len", "(", "type_list", ")", ")", ":", "validation_fn", "=", "type_functions", "[", "i", "]", "if", "validation_fn", "(", "str_val", ")", "and", "(", "prev_type", "is", "None", "or", "prev_type", "in", "type_list", "[", ":", "i", "+", "1", "]", ")", ":", "return", "type_list", "[", "i", "]" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/data/experimental/ops/readers.py#L70-L104
wyrover/book-code
7f4883d9030d553bc6bcfa3da685e34789839900
3rdparty/protobuf/python/google/protobuf/internal/python_message.py
python
_ReraiseTypeErrorWithFieldName
(message_name, field_name)
Re-raise the currently-handled TypeError with the field name added.
Re-raise the currently-handled TypeError with the field name added.
[ "Re", "-", "raise", "the", "currently", "-", "handled", "TypeError", "with", "the", "field", "name", "added", "." ]
def _ReraiseTypeErrorWithFieldName(message_name, field_name): """Re-raise the currently-handled TypeError with the field name added.""" exc = sys.exc_info()[1] if len(exc.args) == 1 and type(exc) is TypeError: # simple TypeError; add field name to exception message exc = TypeError('%s for field %s.%s' % (str(exc), message_name, field_name)) # re-raise possibly-amended exception with original traceback: six.reraise(type(exc), exc, sys.exc_info()[2])
[ "def", "_ReraiseTypeErrorWithFieldName", "(", "message_name", ",", "field_name", ")", ":", "exc", "=", "sys", ".", "exc_info", "(", ")", "[", "1", "]", "if", "len", "(", "exc", ".", "args", ")", "==", "1", "and", "type", "(", "exc", ")", "is", "TypeError", ":", "# simple TypeError; add field name to exception message", "exc", "=", "TypeError", "(", "'%s for field %s.%s'", "%", "(", "str", "(", "exc", ")", ",", "message_name", ",", "field_name", ")", ")", "# re-raise possibly-amended exception with original traceback:", "six", ".", "reraise", "(", "type", "(", "exc", ")", ",", "exc", ",", "sys", ".", "exc_info", "(", ")", "[", "2", "]", ")" ]
https://github.com/wyrover/book-code/blob/7f4883d9030d553bc6bcfa3da685e34789839900/3rdparty/protobuf/python/google/protobuf/internal/python_message.py#L447-L455
microsoft/ELL
a1d6bacc37a14879cc025d9be2ba40b1a0632315
tools/utilities/pythonlibs/vision/demoHelper.py
python
ImageStream.load_next_image
(self)
return None
advance to next image in the stream
advance to next image in the stream
[ "advance", "to", "next", "image", "in", "the", "stream" ]
def load_next_image(self): """ advance to next image in the stream """ return None
[ "def", "load_next_image", "(", "self", ")", ":", "return", "None" ]
https://github.com/microsoft/ELL/blob/a1d6bacc37a14879cc025d9be2ba40b1a0632315/tools/utilities/pythonlibs/vision/demoHelper.py#L150-L152
Slicer/SlicerGitSVNArchive
65e92bb16c2b32ea47a1a66bee71f238891ee1ca
Modules/Scripted/LabelStatistics/LabelStatistics.py
python
LabelStatisticsTest.setUp
(self)
Do whatever is needed to reset the state - typically a scene clear will be enough.
Do whatever is needed to reset the state - typically a scene clear will be enough.
[ "Do", "whatever", "is", "needed", "to", "reset", "the", "state", "-", "typically", "a", "scene", "clear", "will", "be", "enough", "." ]
def setUp(self): """ Do whatever is needed to reset the state - typically a scene clear will be enough. """ slicer.mrmlScene.Clear(0)
[ "def", "setUp", "(", "self", ")", ":", "slicer", ".", "mrmlScene", ".", "Clear", "(", "0", ")" ]
https://github.com/Slicer/SlicerGitSVNArchive/blob/65e92bb16c2b32ea47a1a66bee71f238891ee1ca/Modules/Scripted/LabelStatistics/LabelStatistics.py#L514-L517
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/python/keras/_impl/keras/models.py
python
Sequential.predict_on_batch
(self, x)
return self.model.predict_on_batch(x)
Returns predictions for a single batch of samples. Arguments: x: input data, as a Numpy array or list of Numpy arrays (if the model has multiple inputs). Returns: A Numpy array of predictions.
Returns predictions for a single batch of samples.
[ "Returns", "predictions", "for", "a", "single", "batch", "of", "samples", "." ]
def predict_on_batch(self, x): """Returns predictions for a single batch of samples. Arguments: x: input data, as a Numpy array or list of Numpy arrays (if the model has multiple inputs). Returns: A Numpy array of predictions. """ if not self.built: self.build() return self.model.predict_on_batch(x)
[ "def", "predict_on_batch", "(", "self", ",", "x", ")", ":", "if", "not", "self", ".", "built", ":", "self", ".", "build", "(", ")", "return", "self", ".", "model", ".", "predict_on_batch", "(", "x", ")" ]
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/keras/_impl/keras/models.py#L891-L903
bingwin/MicroChat
81d9a71a212c1cbca5bba497ec42659a7d25dccf
mars/lint/cpplint.py
python
_NamespaceInfo.CheckEnd
(self, filename, clean_lines, linenum, error)
Check end of namespace comments.
Check end of namespace comments.
[ "Check", "end", "of", "namespace", "comments", "." ]
def CheckEnd(self, filename, clean_lines, linenum, error): """Check end of namespace comments.""" line = clean_lines.raw_lines[linenum] # Check how many lines is enclosed in this namespace. Don't issue # warning for missing namespace comments if there aren't enough # lines. However, do apply checks if there is already an end of # namespace comment and it's incorrect. # # TODO(unknown): We always want to check end of namespace comments # if a namespace is large, but sometimes we also want to apply the # check if a short namespace contained nontrivial things (something # other than forward declarations). There is currently no logic on # deciding what these nontrivial things are, so this check is # triggered by namespace size only, which works most of the time. if (linenum - self.starting_linenum < 10 and not Match(r'};*\s*(//|/\*).*\bnamespace\b', line)): return # Look for matching comment at end of namespace. # # Note that we accept C style "/* */" comments for terminating # namespaces, so that code that terminate namespaces inside # preprocessor macros can be cpplint clean. # # We also accept stuff like "// end of namespace <name>." with the # period at the end. # # Besides these, we don't accept anything else, otherwise we might # get false negatives when existing comment is a substring of the # expected namespace. if self.name: # Named namespace if not Match((r'};*\s*(//|/\*).*\bnamespace\s+' + re.escape(self.name) + r'[\*/\.\\\s]*$'), line): error(filename, linenum, 'readability/namespace', 5, 'Namespace should be terminated with "// namespace %s"' % self.name) else: # Anonymous namespace if not Match(r'};*\s*(//|/\*).*\bnamespace[\*/\.\\\s]*$', line): # If "// namespace anonymous" or "// anonymous namespace (more text)", # mention "// anonymous namespace" as an acceptable form if Match(r'}.*\b(namespace anonymous|anonymous namespace)\b', line): error(filename, linenum, 'readability/namespace', 5, 'Anonymous namespace should be terminated with "// namespace"' ' or "// anonymous namespace"') else: error(filename, linenum, 'readability/namespace', 5, 'Anonymous namespace should be terminated with "// namespace"')
[ "def", "CheckEnd", "(", "self", ",", "filename", ",", "clean_lines", ",", "linenum", ",", "error", ")", ":", "line", "=", "clean_lines", ".", "raw_lines", "[", "linenum", "]", "# Check how many lines is enclosed in this namespace. Don't issue", "# warning for missing namespace comments if there aren't enough", "# lines. However, do apply checks if there is already an end of", "# namespace comment and it's incorrect.", "#", "# TODO(unknown): We always want to check end of namespace comments", "# if a namespace is large, but sometimes we also want to apply the", "# check if a short namespace contained nontrivial things (something", "# other than forward declarations). There is currently no logic on", "# deciding what these nontrivial things are, so this check is", "# triggered by namespace size only, which works most of the time.", "if", "(", "linenum", "-", "self", ".", "starting_linenum", "<", "10", "and", "not", "Match", "(", "r'};*\\s*(//|/\\*).*\\bnamespace\\b'", ",", "line", ")", ")", ":", "return", "# Look for matching comment at end of namespace.", "#", "# Note that we accept C style \"/* */\" comments for terminating", "# namespaces, so that code that terminate namespaces inside", "# preprocessor macros can be cpplint clean.", "#", "# We also accept stuff like \"// end of namespace <name>.\" with the", "# period at the end.", "#", "# Besides these, we don't accept anything else, otherwise we might", "# get false negatives when existing comment is a substring of the", "# expected namespace.", "if", "self", ".", "name", ":", "# Named namespace", "if", "not", "Match", "(", "(", "r'};*\\s*(//|/\\*).*\\bnamespace\\s+'", "+", "re", ".", "escape", "(", "self", ".", "name", ")", "+", "r'[\\*/\\.\\\\\\s]*$'", ")", ",", "line", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'readability/namespace'", ",", "5", ",", "'Namespace should be terminated with \"// namespace %s\"'", "%", "self", ".", "name", ")", "else", ":", "# Anonymous namespace", "if", "not", "Match", "(", "r'};*\\s*(//|/\\*).*\\bnamespace[\\*/\\.\\\\\\s]*$'", ",", "line", ")", ":", "# If \"// namespace anonymous\" or \"// anonymous namespace (more text)\",", "# mention \"// anonymous namespace\" as an acceptable form", "if", "Match", "(", "r'}.*\\b(namespace anonymous|anonymous namespace)\\b'", ",", "line", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'readability/namespace'", ",", "5", ",", "'Anonymous namespace should be terminated with \"// namespace\"'", "' or \"// anonymous namespace\"'", ")", "else", ":", "error", "(", "filename", ",", "linenum", ",", "'readability/namespace'", ",", "5", ",", "'Anonymous namespace should be terminated with \"// namespace\"'", ")" ]
https://github.com/bingwin/MicroChat/blob/81d9a71a212c1cbca5bba497ec42659a7d25dccf/mars/lint/cpplint.py#L2137-L2187
apache/arrow
af33dd1157eb8d7d9bfac25ebf61445b793b7943
python/pyarrow/hdfs.py
python
HadoopFileSystem._isfilestore
(self)
return True
Return True if this is a Unix-style file store with directories.
Return True if this is a Unix-style file store with directories.
[ "Return", "True", "if", "this", "is", "a", "Unix", "-", "style", "file", "store", "with", "directories", "." ]
def _isfilestore(self): """ Return True if this is a Unix-style file store with directories. """ return True
[ "def", "_isfilestore", "(", "self", ")", ":", "return", "True" ]
https://github.com/apache/arrow/blob/af33dd1157eb8d7d9bfac25ebf61445b793b7943/python/pyarrow/hdfs.py#L55-L59
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/grid.py
python
GridCellEditor.GetControl
(*args, **kwargs)
return _grid.GridCellEditor_GetControl(*args, **kwargs)
GetControl(self) -> Control
GetControl(self) -> Control
[ "GetControl", "(", "self", ")", "-", ">", "Control" ]
def GetControl(*args, **kwargs): """GetControl(self) -> Control""" return _grid.GridCellEditor_GetControl(*args, **kwargs)
[ "def", "GetControl", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_grid", ".", "GridCellEditor_GetControl", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/grid.py#L268-L270
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/lib2to3/patcomp.py
python
PatternCompiler.compile_node
(self, node)
return pattern.optimize()
Compiles a node, recursively. This is one big switch on the node type.
Compiles a node, recursively.
[ "Compiles", "a", "node", "recursively", "." ]
def compile_node(self, node): """Compiles a node, recursively. This is one big switch on the node type. """ # XXX Optimize certain Wildcard-containing-Wildcard patterns # that can be merged if node.type == self.syms.Matcher: node = node.children[0] # Avoid unneeded recursion if node.type == self.syms.Alternatives: # Skip the odd children since they are just '|' tokens alts = [self.compile_node(ch) for ch in node.children[::2]] if len(alts) == 1: return alts[0] p = pytree.WildcardPattern([[a] for a in alts], min=1, max=1) return p.optimize() if node.type == self.syms.Alternative: units = [self.compile_node(ch) for ch in node.children] if len(units) == 1: return units[0] p = pytree.WildcardPattern([units], min=1, max=1) return p.optimize() if node.type == self.syms.NegatedUnit: pattern = self.compile_basic(node.children[1:]) p = pytree.NegatedPattern(pattern) return p.optimize() assert node.type == self.syms.Unit name = None nodes = node.children if len(nodes) >= 3 and nodes[1].type == token.EQUAL: name = nodes[0].value nodes = nodes[2:] repeat = None if len(nodes) >= 2 and nodes[-1].type == self.syms.Repeater: repeat = nodes[-1] nodes = nodes[:-1] # Now we've reduced it to: STRING | NAME [Details] | (...) | [...] pattern = self.compile_basic(nodes, repeat) if repeat is not None: assert repeat.type == self.syms.Repeater children = repeat.children child = children[0] if child.type == token.STAR: min = 0 max = pytree.HUGE elif child.type == token.PLUS: min = 1 max = pytree.HUGE elif child.type == token.LBRACE: assert children[-1].type == token.RBRACE assert len(children) in (3, 5) min = max = self.get_int(children[1]) if len(children) == 5: max = self.get_int(children[3]) else: assert False if min != 1 or max != 1: pattern = pattern.optimize() pattern = pytree.WildcardPattern([[pattern]], min=min, max=max) if name is not None: pattern.name = name return pattern.optimize()
[ "def", "compile_node", "(", "self", ",", "node", ")", ":", "# XXX Optimize certain Wildcard-containing-Wildcard patterns", "# that can be merged", "if", "node", ".", "type", "==", "self", ".", "syms", ".", "Matcher", ":", "node", "=", "node", ".", "children", "[", "0", "]", "# Avoid unneeded recursion", "if", "node", ".", "type", "==", "self", ".", "syms", ".", "Alternatives", ":", "# Skip the odd children since they are just '|' tokens", "alts", "=", "[", "self", ".", "compile_node", "(", "ch", ")", "for", "ch", "in", "node", ".", "children", "[", ":", ":", "2", "]", "]", "if", "len", "(", "alts", ")", "==", "1", ":", "return", "alts", "[", "0", "]", "p", "=", "pytree", ".", "WildcardPattern", "(", "[", "[", "a", "]", "for", "a", "in", "alts", "]", ",", "min", "=", "1", ",", "max", "=", "1", ")", "return", "p", ".", "optimize", "(", ")", "if", "node", ".", "type", "==", "self", ".", "syms", ".", "Alternative", ":", "units", "=", "[", "self", ".", "compile_node", "(", "ch", ")", "for", "ch", "in", "node", ".", "children", "]", "if", "len", "(", "units", ")", "==", "1", ":", "return", "units", "[", "0", "]", "p", "=", "pytree", ".", "WildcardPattern", "(", "[", "units", "]", ",", "min", "=", "1", ",", "max", "=", "1", ")", "return", "p", ".", "optimize", "(", ")", "if", "node", ".", "type", "==", "self", ".", "syms", ".", "NegatedUnit", ":", "pattern", "=", "self", ".", "compile_basic", "(", "node", ".", "children", "[", "1", ":", "]", ")", "p", "=", "pytree", ".", "NegatedPattern", "(", "pattern", ")", "return", "p", ".", "optimize", "(", ")", "assert", "node", ".", "type", "==", "self", ".", "syms", ".", "Unit", "name", "=", "None", "nodes", "=", "node", ".", "children", "if", "len", "(", "nodes", ")", ">=", "3", "and", "nodes", "[", "1", "]", ".", "type", "==", "token", ".", "EQUAL", ":", "name", "=", "nodes", "[", "0", "]", ".", "value", "nodes", "=", "nodes", "[", "2", ":", "]", "repeat", "=", "None", "if", "len", "(", "nodes", ")", ">=", "2", "and", "nodes", "[", "-", "1", "]", ".", "type", "==", "self", ".", "syms", ".", "Repeater", ":", "repeat", "=", "nodes", "[", "-", "1", "]", "nodes", "=", "nodes", "[", ":", "-", "1", "]", "# Now we've reduced it to: STRING | NAME [Details] | (...) | [...]", "pattern", "=", "self", ".", "compile_basic", "(", "nodes", ",", "repeat", ")", "if", "repeat", "is", "not", "None", ":", "assert", "repeat", ".", "type", "==", "self", ".", "syms", ".", "Repeater", "children", "=", "repeat", ".", "children", "child", "=", "children", "[", "0", "]", "if", "child", ".", "type", "==", "token", ".", "STAR", ":", "min", "=", "0", "max", "=", "pytree", ".", "HUGE", "elif", "child", ".", "type", "==", "token", ".", "PLUS", ":", "min", "=", "1", "max", "=", "pytree", ".", "HUGE", "elif", "child", ".", "type", "==", "token", ".", "LBRACE", ":", "assert", "children", "[", "-", "1", "]", ".", "type", "==", "token", ".", "RBRACE", "assert", "len", "(", "children", ")", "in", "(", "3", ",", "5", ")", "min", "=", "max", "=", "self", ".", "get_int", "(", "children", "[", "1", "]", ")", "if", "len", "(", "children", ")", "==", "5", ":", "max", "=", "self", ".", "get_int", "(", "children", "[", "3", "]", ")", "else", ":", "assert", "False", "if", "min", "!=", "1", "or", "max", "!=", "1", ":", "pattern", "=", "pattern", ".", "optimize", "(", ")", "pattern", "=", "pytree", ".", "WildcardPattern", "(", "[", "[", "pattern", "]", "]", ",", "min", "=", "min", ",", "max", "=", "max", ")", "if", "name", "is", "not", "None", ":", "pattern", ".", "name", "=", "name", "return", "pattern", ".", "optimize", "(", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/lib2to3/patcomp.py#L68-L137
hughperkins/tf-coriander
970d3df6c11400ad68405f22b0c42a52374e94ca
tensorflow/python/debug/framework.py
python
BaseDebugWrapperSession.run
(self, fetches, feed_dict=None, options=None, run_metadata=None)
return retvals
Wrapper around Session.run() that inserts tensor watch options. Args: fetches: Same as the fetches arg to regular Session.run() feed_dict: Same as the feed_dict arg to regular Session.run() options: Same as the options arg to regular Session.run() run_metadata: Same as the run_metadata to regular Session.run() Returns: Simply forwards the output of the wrapped Session.run() call. Raises: ValueError: On invalid OnRunStartAction value.
Wrapper around Session.run() that inserts tensor watch options.
[ "Wrapper", "around", "Session", ".", "run", "()", "that", "inserts", "tensor", "watch", "options", "." ]
def run(self, fetches, feed_dict=None, options=None, run_metadata=None): """Wrapper around Session.run() that inserts tensor watch options. Args: fetches: Same as the fetches arg to regular Session.run() feed_dict: Same as the feed_dict arg to regular Session.run() options: Same as the options arg to regular Session.run() run_metadata: Same as the run_metadata to regular Session.run() Returns: Simply forwards the output of the wrapped Session.run() call. Raises: ValueError: On invalid OnRunStartAction value. """ self._run_call_count += 1 # Invoke on-run-start callback and obtain response. run_start_resp = self.on_run_start( OnRunStartRequest(fetches, feed_dict, options, run_metadata, self._run_call_count)) _check_type(run_start_resp, OnRunStartResponse) if run_start_resp.action == OnRunStartAction.DEBUG_RUN: # Decorate RunOption to fill in debugger tensor watch specifications. decorated_run_options = options or config_pb2.RunOptions() run_metadata = run_metadata or config_pb2.RunMetadata() self._decorate_run_options(decorated_run_options, run_start_resp.debug_urls) # Invoke the run() method of the wrapped Session. retvals = self._sess.run( fetches, feed_dict=feed_dict, options=decorated_run_options, run_metadata=run_metadata) # Prepare arg for the on-run-end callback. run_end_req = OnRunEndRequest( run_start_resp.action, run_metadata=run_metadata) elif run_start_resp.action == OnRunStartAction.NON_DEBUG_RUN: # Invoke run() method of the wrapped session. retvals = self._sess.run( fetches, feed_dict=feed_dict, options=options, run_metadata=run_metadata) # Prepare arg for the on-run-end callback. run_end_req = OnRunEndRequest(run_start_resp.action) elif run_start_resp.action == OnRunStartAction.INVOKE_STEPPER: # TODO(cais): Implement stepper loop. raise NotImplementedError( "OnRunStartAction INVOKE_STEPPER has not been implemented.") else: raise ValueError( "Invalid OnRunStartAction value: %s" % run_start_resp.action) # Invoke on-run-end callback and obtain response. run_end_resp = self.on_run_end(run_end_req) _check_type(run_end_resp, OnRunEndResponse) # Currently run_end_resp is only a placeholder. No action is taken on it. return retvals
[ "def", "run", "(", "self", ",", "fetches", ",", "feed_dict", "=", "None", ",", "options", "=", "None", ",", "run_metadata", "=", "None", ")", ":", "self", ".", "_run_call_count", "+=", "1", "# Invoke on-run-start callback and obtain response.", "run_start_resp", "=", "self", ".", "on_run_start", "(", "OnRunStartRequest", "(", "fetches", ",", "feed_dict", ",", "options", ",", "run_metadata", ",", "self", ".", "_run_call_count", ")", ")", "_check_type", "(", "run_start_resp", ",", "OnRunStartResponse", ")", "if", "run_start_resp", ".", "action", "==", "OnRunStartAction", ".", "DEBUG_RUN", ":", "# Decorate RunOption to fill in debugger tensor watch specifications.", "decorated_run_options", "=", "options", "or", "config_pb2", ".", "RunOptions", "(", ")", "run_metadata", "=", "run_metadata", "or", "config_pb2", ".", "RunMetadata", "(", ")", "self", ".", "_decorate_run_options", "(", "decorated_run_options", ",", "run_start_resp", ".", "debug_urls", ")", "# Invoke the run() method of the wrapped Session.", "retvals", "=", "self", ".", "_sess", ".", "run", "(", "fetches", ",", "feed_dict", "=", "feed_dict", ",", "options", "=", "decorated_run_options", ",", "run_metadata", "=", "run_metadata", ")", "# Prepare arg for the on-run-end callback.", "run_end_req", "=", "OnRunEndRequest", "(", "run_start_resp", ".", "action", ",", "run_metadata", "=", "run_metadata", ")", "elif", "run_start_resp", ".", "action", "==", "OnRunStartAction", ".", "NON_DEBUG_RUN", ":", "# Invoke run() method of the wrapped session.", "retvals", "=", "self", ".", "_sess", ".", "run", "(", "fetches", ",", "feed_dict", "=", "feed_dict", ",", "options", "=", "options", ",", "run_metadata", "=", "run_metadata", ")", "# Prepare arg for the on-run-end callback.", "run_end_req", "=", "OnRunEndRequest", "(", "run_start_resp", ".", "action", ")", "elif", "run_start_resp", ".", "action", "==", "OnRunStartAction", ".", "INVOKE_STEPPER", ":", "# TODO(cais): Implement stepper loop.", "raise", "NotImplementedError", "(", "\"OnRunStartAction INVOKE_STEPPER has not been implemented.\"", ")", "else", ":", "raise", "ValueError", "(", "\"Invalid OnRunStartAction value: %s\"", "%", "run_start_resp", ".", "action", ")", "# Invoke on-run-end callback and obtain response.", "run_end_resp", "=", "self", ".", "on_run_end", "(", "run_end_req", ")", "_check_type", "(", "run_end_resp", ",", "OnRunEndResponse", ")", "# Currently run_end_resp is only a placeholder. No action is taken on it.", "return", "retvals" ]
https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/python/debug/framework.py#L330-L395
eclipse/sumo
7132a9b8b6eea734bdec38479026b4d8c4336d03
tools/contributed/sumopy/coremodules/simulation/sumo.py
python
write_netconfig
(filename_netconfig, filename_net, filename_routes='', filename_poly=None, dirname_output='', starttime=None, stoptime=None, time_step=1.0, time_to_teleport=-1, pedestrian_model='None', width_sublanes=-1.0, filename_ptstops=None, filepath_output_vehroute=None, filepath_output_tripinfo=None, is_tripdata_unfinished=False, filepath_output_edgedata=None, filepath_output_lanedata=None, filepath_output_edgeemissions=None, filepath_output_laneemissions=None, filepath_output_edgenoise=None, filepath_output_lanenoise=None, filepath_output_electricenergy=None, filepath_output_fcd=None, filepath_output_summary=None, freq=60, is_exclude_emptyedges=False, is_exclude_emptylanes=False, is_ignore_route_errors=True, filepath_gui=None, seed=1025, is_openscenegraph=False, width_pedestrian_striping=0.49, slowdownfactor_pedestrian_striping=0.2, jamtime_pedestrian_striping=20, jamtime_pedestrian_crossing_striping=10, is_collission_check_junctions=True, is_ignore_accidents=False, collission_action='teleport', is_ballistic_integrator=False, is_rerouting=False, probability_rerouting=0.0, is_deterministic_rerouting=False, period_rerouting=0, preperiod_rerouting=60, adaptationinterval_rerouting=1, adaptationweight_rerouting=0.0, adaptationsteps_rerouting=180, taxiservice=None, )
filename_netconfig = output filename of network config file without path filename_net = input filename of network file without path filename_rou = input filename of routes file without path filename_poly = input filename of polygons file without path dirname_output = directory where config, network, route and poly file reside
filename_netconfig = output filename of network config file without path filename_net = input filename of network file without path filename_rou = input filename of routes file without path filename_poly = input filename of polygons file without path dirname_output = directory where config, network, route and poly file reside
[ "filename_netconfig", "=", "output", "filename", "of", "network", "config", "file", "without", "path", "filename_net", "=", "input", "filename", "of", "network", "file", "without", "path", "filename_rou", "=", "input", "filename", "of", "routes", "file", "without", "path", "filename_poly", "=", "input", "filename", "of", "polygons", "file", "without", "path", "dirname_output", "=", "directory", "where", "config", "network", "route", "and", "poly", "file", "reside" ]
def write_netconfig(filename_netconfig, filename_net, filename_routes='', filename_poly=None, dirname_output='', starttime=None, stoptime=None, time_step=1.0, time_to_teleport=-1, pedestrian_model='None', width_sublanes=-1.0, filename_ptstops=None, filepath_output_vehroute=None, filepath_output_tripinfo=None, is_tripdata_unfinished=False, filepath_output_edgedata=None, filepath_output_lanedata=None, filepath_output_edgeemissions=None, filepath_output_laneemissions=None, filepath_output_edgenoise=None, filepath_output_lanenoise=None, filepath_output_electricenergy=None, filepath_output_fcd=None, filepath_output_summary=None, freq=60, is_exclude_emptyedges=False, is_exclude_emptylanes=False, is_ignore_route_errors=True, filepath_gui=None, seed=1025, is_openscenegraph=False, width_pedestrian_striping=0.49, slowdownfactor_pedestrian_striping=0.2, jamtime_pedestrian_striping=20, jamtime_pedestrian_crossing_striping=10, is_collission_check_junctions=True, is_ignore_accidents=False, collission_action='teleport', is_ballistic_integrator=False, is_rerouting=False, probability_rerouting=0.0, is_deterministic_rerouting=False, period_rerouting=0, preperiod_rerouting=60, adaptationinterval_rerouting=1, adaptationweight_rerouting=0.0, adaptationsteps_rerouting=180, taxiservice=None, ): """ filename_netconfig = output filename of network config file without path filename_net = input filename of network file without path filename_rou = input filename of routes file without path filename_poly = input filename of polygons file without path dirname_output = directory where config, network, route and poly file reside """ # print 'write_netconfig >>%s<<'%filename_netconfig # print ' filename_poly=>>%s<<'%filename_poly if dirname_output: filepath_netconfig = os.path.join(dirname_output, filename_netconfig) else: filepath_netconfig = filename_netconfig if (filepath_output_edgedata is not None)\ | (filepath_output_lanedata is not None)\ | (filepath_output_edgeemissions is not None)\ | (filepath_output_laneemissions is not None)\ | (filepath_output_edgenoise is not None)\ | (filepath_output_lanenoise is not None)\ | (filepath_output_electricenergy is not None): # filename of additional files: filename_add = string.join(filename_netconfig.split('.')[:-2]+['outc.xml'], '.') filepath_add = os.path.join(dirname_output, filename_add) # print ' filepath_add',filepath_add else: filename_add = None simfile = open(filepath_netconfig, 'w') simfile.write( """<?xml version="1.0"?> <configuration xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://sumo.sf.net/xsd/sumoConfiguration.xsd"> <input>\n""") simfile.write(' <net-file value="%s"/>\n' % filename_net) if filename_routes != "": simfile.write(' <route-files value="%s"/>\n' % filename_routes) # print ' filename_add',filename_add # print ' filepath_add',filepath_add simfile.write(' <additional-files value="') filenames_add = set([filename_poly, filename_add, filename_ptstops]) filenames_add.discard(None) filenames_add = list(filenames_add) if len(filenames_add) > 0: for filename in filenames_add[:-1]: simfile.write('%s,' % filename) simfile.write('%s' % filenames_add[-1]) simfile.write('" />\n') simfile.write('</input>\n') if (starttime is not None) & (stoptime is not None): simfile.write( """ <time> <begin value="%s"/> <end value="%s"/> </time> """ % (starttime, stoptime)) simfile.write('<time-to-teleport value="%s"/>\n' % time_to_teleport) simfile.write('<seed value="%s"/>\n' % seed) simfile.write('<step-length value="%s"/>\n' % time_step) simfile.write('<ignore-route-errors value="%s"/>\n' % is_ignore_route_errors) if is_ballistic_integrator: simfile.write('<step-method.ballistic value="True"/>\n') if width_sublanes > 0: simfile.write('<lateral-resolution value="%s"/>\n' % width_sublanes) # not (yet) recogniced...move to cml if pedestrian_model != 'None': simfile.write('<pedestrian.model value="%s"/>\n' % pedestrian_model) if pedestrian_model == 'striping': simfile.write('<pedestrian.striping.stripe-width value="%s"/>\n' % width_pedestrian_striping) simfile.write('<pedestrian.striping.dawdling value="%s"/>\n' % slowdownfactor_pedestrian_striping) simfile.write('<pedestrian.striping.jamtime value="%s"/>\n' % jamtime_pedestrian_striping) # from 1.3.0 #simfile.write('<pedestrian.striping.jamtime.crossing value="%s"/>\n'%jamtime_pedestrian_crossing_striping) simfile.write('<collision.check-junctions value="%s"/>\n' % is_collission_check_junctions) simfile.write('<collision.action value="%s"/>\n' % collission_action) #simfile.write('<ignore-accidents value="%s"/>\n'%is_ignore_accidents) if taxiservice is not None: taxiservice.write_config(simfile, ident=0) simfile.write('<output>\n') # <output-file value="quickstart.net.xml"/> if filepath_output_vehroute is not None: simfile.write('<vehroute-output value="%s"/>\n' % filepath_output_vehroute) if filepath_output_tripinfo is not None: simfile.write('<tripinfo-output value="%s"/>\n' % filepath_output_tripinfo) if filepath_output_fcd is not None: simfile.write("""<fcd-output value="%s"/> <device.fcd.probability value="1"/>\n """ % (filepath_output_fcd,)) # <device.fcd.period value="1"/> if filepath_output_electricenergy is not None: simfile.write("""<battery-output value="%s"/> <battery-output.precision value="4"/> <device.battery.probability value="1"/> \n """ % (filepath_output_electricenergy,)) if filepath_output_summary is not None: simfile.write("""<summary-output value="%s"/>""" % filepath_output_summary) simfile.write('</output>\n') if filepath_gui is not None: simfile.write('<gui-settings-file value="%s"/>\n' % filepath_gui) if is_openscenegraph: simfile.write('<osg-view value="true"/>\n') if is_tripdata_unfinished: simfile.write('<tripinfo-output.write-unfinished value="true"/>\n') if is_rerouting: simfile.write("""<routing> <device.rerouting.probability value="%.2f"/> <device.rerouting.deterministic value="%s"/> <device.rerouting.period value="%d"/> <device.rerouting.pre-period value="%d"/> <device.rerouting.adaptation-interval value = "%d"/>\n """ % (probability_rerouting, is_deterministic_rerouting, period_rerouting, preperiod_rerouting, float(adaptationinterval_rerouting)/time_step, )) if adaptationweight_rerouting > 0: simfile.write("""<device.rerouting.adaptation-weight value="%.4f"/>\n""" % adaptationweight_rerouting) else: simfile.write("""<device.rerouting.adaptation-steps value="%d"/>\n""" % adaptationsteps_rerouting) simfile.write('</routing>\n') # <report> # <no-duration-log value="true"/> # <no-step-log value="true"/> # </report> simfile.write('</configuration>\n') simfile.close() # add path to additional files if necessary if filename_add is not None: addfile = open(filepath_add, 'w') addfile.write('<add>\n') if filepath_output_edgedata is not None: addfile.write(' <edgeData id="output_edgedata_%d" freq="%d" file="%s" excludeEmpty="%s"/>\n' % (freq, freq, filepath_output_edgedata, str(is_exclude_emptyedges).lower())) if filepath_output_lanedata is not None: addfile.write(' <laneData id="output_lanedata_%d" freq="%d" file="%s" excludeEmpty="%s"/>\n' % (freq, freq, filepath_output_lanedata, str(is_exclude_emptylanes).lower())) if filepath_output_edgeemissions is not None: addfile.write(' <edgeData id="output_edgeemissions_%d" type="emissions" freq="%d" file="%s" excludeEmpty="%s"/>\n' % (freq, freq, filepath_output_edgeemissions, str(is_exclude_emptyedges).lower())) if filepath_output_laneemissions is not None: addfile.write(' <laneData id="output_laneemissions_%d" type="emissions" freq="%d" file="%s" excludeEmpty="%s"/>\n' % (freq, freq, filepath_output_laneemissions, str(is_exclude_emptylanes).lower())) if filepath_output_edgenoise is not None: addfile.write(' <edgeData id="edgenoise_%d" type="harmonoise" freq="%d" file="%s" excludeEmpty="%s"/>\n' % (freq, freq, filepath_output_edgenoise, str(is_exclude_emptyedges).lower())) if filepath_output_lanenoise is not None: addfile.write(' <laneData id="lanenoise_%d" type="harmonoise" freq="%d" file="%s" excludeEmpty="%s"/>\n' % (freq, freq, filepath_output_lanenoise, str(is_exclude_emptylanes).lower())) # if filepath_output_electricenergy is not None: # addfile.write(' <laneData id="lanenoise_%d" type="harmonoise" freq="%d" file="%s" excludeEmpty="%s"/>\n'%(freq,freq,filepath_output_lanenoise,str(is_exclude_emptylanes).lower())) addfile.write('</add>\n') addfile.close()
[ "def", "write_netconfig", "(", "filename_netconfig", ",", "filename_net", ",", "filename_routes", "=", "''", ",", "filename_poly", "=", "None", ",", "dirname_output", "=", "''", ",", "starttime", "=", "None", ",", "stoptime", "=", "None", ",", "time_step", "=", "1.0", ",", "time_to_teleport", "=", "-", "1", ",", "pedestrian_model", "=", "'None'", ",", "width_sublanes", "=", "-", "1.0", ",", "filename_ptstops", "=", "None", ",", "filepath_output_vehroute", "=", "None", ",", "filepath_output_tripinfo", "=", "None", ",", "is_tripdata_unfinished", "=", "False", ",", "filepath_output_edgedata", "=", "None", ",", "filepath_output_lanedata", "=", "None", ",", "filepath_output_edgeemissions", "=", "None", ",", "filepath_output_laneemissions", "=", "None", ",", "filepath_output_edgenoise", "=", "None", ",", "filepath_output_lanenoise", "=", "None", ",", "filepath_output_electricenergy", "=", "None", ",", "filepath_output_fcd", "=", "None", ",", "filepath_output_summary", "=", "None", ",", "freq", "=", "60", ",", "is_exclude_emptyedges", "=", "False", ",", "is_exclude_emptylanes", "=", "False", ",", "is_ignore_route_errors", "=", "True", ",", "filepath_gui", "=", "None", ",", "seed", "=", "1025", ",", "is_openscenegraph", "=", "False", ",", "width_pedestrian_striping", "=", "0.49", ",", "slowdownfactor_pedestrian_striping", "=", "0.2", ",", "jamtime_pedestrian_striping", "=", "20", ",", "jamtime_pedestrian_crossing_striping", "=", "10", ",", "is_collission_check_junctions", "=", "True", ",", "is_ignore_accidents", "=", "False", ",", "collission_action", "=", "'teleport'", ",", "is_ballistic_integrator", "=", "False", ",", "is_rerouting", "=", "False", ",", "probability_rerouting", "=", "0.0", ",", "is_deterministic_rerouting", "=", "False", ",", "period_rerouting", "=", "0", ",", "preperiod_rerouting", "=", "60", ",", "adaptationinterval_rerouting", "=", "1", ",", "adaptationweight_rerouting", "=", "0.0", ",", "adaptationsteps_rerouting", "=", "180", ",", "taxiservice", "=", "None", ",", ")", ":", "# print 'write_netconfig >>%s<<'%filename_netconfig", "# print ' filename_poly=>>%s<<'%filename_poly", "if", "dirname_output", ":", "filepath_netconfig", "=", "os", ".", "path", ".", "join", "(", "dirname_output", ",", "filename_netconfig", ")", "else", ":", "filepath_netconfig", "=", "filename_netconfig", "if", "(", "filepath_output_edgedata", "is", "not", "None", ")", "|", "(", "filepath_output_lanedata", "is", "not", "None", ")", "|", "(", "filepath_output_edgeemissions", "is", "not", "None", ")", "|", "(", "filepath_output_laneemissions", "is", "not", "None", ")", "|", "(", "filepath_output_edgenoise", "is", "not", "None", ")", "|", "(", "filepath_output_lanenoise", "is", "not", "None", ")", "|", "(", "filepath_output_electricenergy", "is", "not", "None", ")", ":", "# filename of additional files:", "filename_add", "=", "string", ".", "join", "(", "filename_netconfig", ".", "split", "(", "'.'", ")", "[", ":", "-", "2", "]", "+", "[", "'outc.xml'", "]", ",", "'.'", ")", "filepath_add", "=", "os", ".", "path", ".", "join", "(", "dirname_output", ",", "filename_add", ")", "# print ' filepath_add',filepath_add", "else", ":", "filename_add", "=", "None", "simfile", "=", "open", "(", "filepath_netconfig", ",", "'w'", ")", "simfile", ".", "write", "(", "\"\"\"<?xml version=\"1.0\"?>\n<configuration xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:noNamespaceSchemaLocation=\"http://sumo.sf.net/xsd/sumoConfiguration.xsd\">\n<input>\\n\"\"\"", ")", "simfile", ".", "write", "(", "' <net-file value=\"%s\"/>\\n'", "%", "filename_net", ")", "if", "filename_routes", "!=", "\"\"", ":", "simfile", ".", "write", "(", "' <route-files value=\"%s\"/>\\n'", "%", "filename_routes", ")", "# print ' filename_add',filename_add", "# print ' filepath_add',filepath_add", "simfile", ".", "write", "(", "' <additional-files value=\"'", ")", "filenames_add", "=", "set", "(", "[", "filename_poly", ",", "filename_add", ",", "filename_ptstops", "]", ")", "filenames_add", ".", "discard", "(", "None", ")", "filenames_add", "=", "list", "(", "filenames_add", ")", "if", "len", "(", "filenames_add", ")", ">", "0", ":", "for", "filename", "in", "filenames_add", "[", ":", "-", "1", "]", ":", "simfile", ".", "write", "(", "'%s,'", "%", "filename", ")", "simfile", ".", "write", "(", "'%s'", "%", "filenames_add", "[", "-", "1", "]", ")", "simfile", ".", "write", "(", "'\" />\\n'", ")", "simfile", ".", "write", "(", "'</input>\\n'", ")", "if", "(", "starttime", "is", "not", "None", ")", "&", "(", "stoptime", "is", "not", "None", ")", ":", "simfile", ".", "write", "(", "\"\"\"\n<time>\n <begin value=\"%s\"/>\n <end value=\"%s\"/>\n</time>\n \"\"\"", "%", "(", "starttime", ",", "stoptime", ")", ")", "simfile", ".", "write", "(", "'<time-to-teleport value=\"%s\"/>\\n'", "%", "time_to_teleport", ")", "simfile", ".", "write", "(", "'<seed value=\"%s\"/>\\n'", "%", "seed", ")", "simfile", ".", "write", "(", "'<step-length value=\"%s\"/>\\n'", "%", "time_step", ")", "simfile", ".", "write", "(", "'<ignore-route-errors value=\"%s\"/>\\n'", "%", "is_ignore_route_errors", ")", "if", "is_ballistic_integrator", ":", "simfile", ".", "write", "(", "'<step-method.ballistic value=\"True\"/>\\n'", ")", "if", "width_sublanes", ">", "0", ":", "simfile", ".", "write", "(", "'<lateral-resolution value=\"%s\"/>\\n'", "%", "width_sublanes", ")", "# not (yet) recogniced...move to cml", "if", "pedestrian_model", "!=", "'None'", ":", "simfile", ".", "write", "(", "'<pedestrian.model value=\"%s\"/>\\n'", "%", "pedestrian_model", ")", "if", "pedestrian_model", "==", "'striping'", ":", "simfile", ".", "write", "(", "'<pedestrian.striping.stripe-width value=\"%s\"/>\\n'", "%", "width_pedestrian_striping", ")", "simfile", ".", "write", "(", "'<pedestrian.striping.dawdling value=\"%s\"/>\\n'", "%", "slowdownfactor_pedestrian_striping", ")", "simfile", ".", "write", "(", "'<pedestrian.striping.jamtime value=\"%s\"/>\\n'", "%", "jamtime_pedestrian_striping", ")", "# from 1.3.0", "#simfile.write('<pedestrian.striping.jamtime.crossing value=\"%s\"/>\\n'%jamtime_pedestrian_crossing_striping)", "simfile", ".", "write", "(", "'<collision.check-junctions value=\"%s\"/>\\n'", "%", "is_collission_check_junctions", ")", "simfile", ".", "write", "(", "'<collision.action value=\"%s\"/>\\n'", "%", "collission_action", ")", "#simfile.write('<ignore-accidents value=\"%s\"/>\\n'%is_ignore_accidents)", "if", "taxiservice", "is", "not", "None", ":", "taxiservice", ".", "write_config", "(", "simfile", ",", "ident", "=", "0", ")", "simfile", ".", "write", "(", "'<output>\\n'", ")", "# <output-file value=\"quickstart.net.xml\"/>", "if", "filepath_output_vehroute", "is", "not", "None", ":", "simfile", ".", "write", "(", "'<vehroute-output value=\"%s\"/>\\n'", "%", "filepath_output_vehroute", ")", "if", "filepath_output_tripinfo", "is", "not", "None", ":", "simfile", ".", "write", "(", "'<tripinfo-output value=\"%s\"/>\\n'", "%", "filepath_output_tripinfo", ")", "if", "filepath_output_fcd", "is", "not", "None", ":", "simfile", ".", "write", "(", "\"\"\"<fcd-output value=\"%s\"/>\n <device.fcd.probability value=\"1\"/>\\n\n \"\"\"", "%", "(", "filepath_output_fcd", ",", ")", ")", "# <device.fcd.period value=\"1\"/>", "if", "filepath_output_electricenergy", "is", "not", "None", ":", "simfile", ".", "write", "(", "\"\"\"<battery-output value=\"%s\"/>\n <battery-output.precision value=\"4\"/>\n <device.battery.probability value=\"1\"/>\n \\n\n \"\"\"", "%", "(", "filepath_output_electricenergy", ",", ")", ")", "if", "filepath_output_summary", "is", "not", "None", ":", "simfile", ".", "write", "(", "\"\"\"<summary-output value=\"%s\"/>\"\"\"", "%", "filepath_output_summary", ")", "simfile", ".", "write", "(", "'</output>\\n'", ")", "if", "filepath_gui", "is", "not", "None", ":", "simfile", ".", "write", "(", "'<gui-settings-file value=\"%s\"/>\\n'", "%", "filepath_gui", ")", "if", "is_openscenegraph", ":", "simfile", ".", "write", "(", "'<osg-view value=\"true\"/>\\n'", ")", "if", "is_tripdata_unfinished", ":", "simfile", ".", "write", "(", "'<tripinfo-output.write-unfinished value=\"true\"/>\\n'", ")", "if", "is_rerouting", ":", "simfile", ".", "write", "(", "\"\"\"<routing>\n <device.rerouting.probability value=\"%.2f\"/>\n <device.rerouting.deterministic value=\"%s\"/>\n <device.rerouting.period value=\"%d\"/>\n <device.rerouting.pre-period value=\"%d\"/>\n <device.rerouting.adaptation-interval value = \"%d\"/>\\n\n \"\"\"", "%", "(", "probability_rerouting", ",", "is_deterministic_rerouting", ",", "period_rerouting", ",", "preperiod_rerouting", ",", "float", "(", "adaptationinterval_rerouting", ")", "/", "time_step", ",", ")", ")", "if", "adaptationweight_rerouting", ">", "0", ":", "simfile", ".", "write", "(", "\"\"\"<device.rerouting.adaptation-weight value=\"%.4f\"/>\\n\"\"\"", "%", "adaptationweight_rerouting", ")", "else", ":", "simfile", ".", "write", "(", "\"\"\"<device.rerouting.adaptation-steps value=\"%d\"/>\\n\"\"\"", "%", "adaptationsteps_rerouting", ")", "simfile", ".", "write", "(", "'</routing>\\n'", ")", "# <report>", "# <no-duration-log value=\"true\"/>", "# <no-step-log value=\"true\"/>", "# </report>", "simfile", ".", "write", "(", "'</configuration>\\n'", ")", "simfile", ".", "close", "(", ")", "# add path to additional files if necessary", "if", "filename_add", "is", "not", "None", ":", "addfile", "=", "open", "(", "filepath_add", ",", "'w'", ")", "addfile", ".", "write", "(", "'<add>\\n'", ")", "if", "filepath_output_edgedata", "is", "not", "None", ":", "addfile", ".", "write", "(", "' <edgeData id=\"output_edgedata_%d\" freq=\"%d\" file=\"%s\" excludeEmpty=\"%s\"/>\\n'", "%", "(", "freq", ",", "freq", ",", "filepath_output_edgedata", ",", "str", "(", "is_exclude_emptyedges", ")", ".", "lower", "(", ")", ")", ")", "if", "filepath_output_lanedata", "is", "not", "None", ":", "addfile", ".", "write", "(", "' <laneData id=\"output_lanedata_%d\" freq=\"%d\" file=\"%s\" excludeEmpty=\"%s\"/>\\n'", "%", "(", "freq", ",", "freq", ",", "filepath_output_lanedata", ",", "str", "(", "is_exclude_emptylanes", ")", ".", "lower", "(", ")", ")", ")", "if", "filepath_output_edgeemissions", "is", "not", "None", ":", "addfile", ".", "write", "(", "' <edgeData id=\"output_edgeemissions_%d\" type=\"emissions\" freq=\"%d\" file=\"%s\" excludeEmpty=\"%s\"/>\\n'", "%", "(", "freq", ",", "freq", ",", "filepath_output_edgeemissions", ",", "str", "(", "is_exclude_emptyedges", ")", ".", "lower", "(", ")", ")", ")", "if", "filepath_output_laneemissions", "is", "not", "None", ":", "addfile", ".", "write", "(", "' <laneData id=\"output_laneemissions_%d\" type=\"emissions\" freq=\"%d\" file=\"%s\" excludeEmpty=\"%s\"/>\\n'", "%", "(", "freq", ",", "freq", ",", "filepath_output_laneemissions", ",", "str", "(", "is_exclude_emptylanes", ")", ".", "lower", "(", ")", ")", ")", "if", "filepath_output_edgenoise", "is", "not", "None", ":", "addfile", ".", "write", "(", "' <edgeData id=\"edgenoise_%d\" type=\"harmonoise\" freq=\"%d\" file=\"%s\" excludeEmpty=\"%s\"/>\\n'", "%", "(", "freq", ",", "freq", ",", "filepath_output_edgenoise", ",", "str", "(", "is_exclude_emptyedges", ")", ".", "lower", "(", ")", ")", ")", "if", "filepath_output_lanenoise", "is", "not", "None", ":", "addfile", ".", "write", "(", "' <laneData id=\"lanenoise_%d\" type=\"harmonoise\" freq=\"%d\" file=\"%s\" excludeEmpty=\"%s\"/>\\n'", "%", "(", "freq", ",", "freq", ",", "filepath_output_lanenoise", ",", "str", "(", "is_exclude_emptylanes", ")", ".", "lower", "(", ")", ")", ")", "# if filepath_output_electricenergy is not None:", "# addfile.write(' <laneData id=\"lanenoise_%d\" type=\"harmonoise\" freq=\"%d\" file=\"%s\" excludeEmpty=\"%s\"/>\\n'%(freq,freq,filepath_output_lanenoise,str(is_exclude_emptylanes).lower()))", "addfile", ".", "write", "(", "'</add>\\n'", ")", "addfile", ".", "close", "(", ")" ]
https://github.com/eclipse/sumo/blob/7132a9b8b6eea734bdec38479026b4d8c4336d03/tools/contributed/sumopy/coremodules/simulation/sumo.py#L62-L299
SpenceKonde/megaTinyCore
1c4a70b18a149fe6bcb551dfa6db11ca50b8997b
megaavr/tools/libs/intelhex/bench.py
python
Measure.measure_one
(self, data)
return tread, twrite
Do measuring of read and write operations. @param data: 3-tuple from get_test_data @return: (time readhex, time writehex)
Do measuring of read and write operations.
[ "Do", "measuring", "of", "read", "and", "write", "operations", "." ]
def measure_one(self, data): """Do measuring of read and write operations. @param data: 3-tuple from get_test_data @return: (time readhex, time writehex) """ _unused, hexstr, ih = data tread, twrite = 0.0, 0.0 if self.read: tread = run_readtest_N_times(intelhex.IntelHex, hexstr, self.n)[0] if self.write: twrite = run_writetest_N_times(ih.write_hex_file, self.n)[0] return tread, twrite
[ "def", "measure_one", "(", "self", ",", "data", ")", ":", "_unused", ",", "hexstr", ",", "ih", "=", "data", "tread", ",", "twrite", "=", "0.0", ",", "0.0", "if", "self", ".", "read", ":", "tread", "=", "run_readtest_N_times", "(", "intelhex", ".", "IntelHex", ",", "hexstr", ",", "self", ".", "n", ")", "[", "0", "]", "if", "self", ".", "write", ":", "twrite", "=", "run_writetest_N_times", "(", "ih", ".", "write_hex_file", ",", "self", ".", "n", ")", "[", "0", "]", "return", "tread", ",", "twrite" ]
https://github.com/SpenceKonde/megaTinyCore/blob/1c4a70b18a149fe6bcb551dfa6db11ca50b8997b/megaavr/tools/libs/intelhex/bench.py#L166-L177
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/_controls.py
python
ListItem.GetId
(*args, **kwargs)
return _controls_.ListItem_GetId(*args, **kwargs)
GetId(self) -> long
GetId(self) -> long
[ "GetId", "(", "self", ")", "-", ">", "long" ]
def GetId(*args, **kwargs): """GetId(self) -> long""" return _controls_.ListItem_GetId(*args, **kwargs)
[ "def", "GetId", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_controls_", ".", "ListItem_GetId", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_controls.py#L4216-L4218
bairdzhang/smallhardface
76fa1d87a9602d9b13d7a7fe693fc7aec91cab80
caffe/scripts/cpp_lint.py
python
RemoveMultiLineComments
(filename, lines, error)
Removes multiline (c-style) comments from lines.
Removes multiline (c-style) comments from lines.
[ "Removes", "multiline", "(", "c", "-", "style", ")", "comments", "from", "lines", "." ]
def RemoveMultiLineComments(filename, lines, error): """Removes multiline (c-style) comments from lines.""" lineix = 0 while lineix < len(lines): lineix_begin = FindNextMultiLineCommentStart(lines, lineix) if lineix_begin >= len(lines): return lineix_end = FindNextMultiLineCommentEnd(lines, lineix_begin) if lineix_end >= len(lines): error(filename, lineix_begin + 1, 'readability/multiline_comment', 5, 'Could not find end of multi-line comment') return RemoveMultiLineCommentsFromRange(lines, lineix_begin, lineix_end + 1) lineix = lineix_end + 1
[ "def", "RemoveMultiLineComments", "(", "filename", ",", "lines", ",", "error", ")", ":", "lineix", "=", "0", "while", "lineix", "<", "len", "(", "lines", ")", ":", "lineix_begin", "=", "FindNextMultiLineCommentStart", "(", "lines", ",", "lineix", ")", "if", "lineix_begin", ">=", "len", "(", "lines", ")", ":", "return", "lineix_end", "=", "FindNextMultiLineCommentEnd", "(", "lines", ",", "lineix_begin", ")", "if", "lineix_end", ">=", "len", "(", "lines", ")", ":", "error", "(", "filename", ",", "lineix_begin", "+", "1", ",", "'readability/multiline_comment'", ",", "5", ",", "'Could not find end of multi-line comment'", ")", "return", "RemoveMultiLineCommentsFromRange", "(", "lines", ",", "lineix_begin", ",", "lineix_end", "+", "1", ")", "lineix", "=", "lineix_end", "+", "1" ]
https://github.com/bairdzhang/smallhardface/blob/76fa1d87a9602d9b13d7a7fe693fc7aec91cab80/caffe/scripts/cpp_lint.py#L1155-L1168
synfig/synfig
a5ec91db5b751dc12e4400ccfb5c063fd6d2d928
synfig-studio/plugins/lottie-exporter/common/Layer.py
python
Layer.get_layer
(self)
return self.layer
Returns the original address of the layer This function might not be needed once class `Layer` is fully embedded in the converter
Returns the original address of the layer This function might not be needed once class `Layer` is fully embedded in the converter
[ "Returns", "the", "original", "address", "of", "the", "layer", "This", "function", "might", "not", "be", "needed", "once", "class", "Layer", "is", "fully", "embedded", "in", "the", "converter" ]
def get_layer(self): """ Returns the original address of the layer This function might not be needed once class `Layer` is fully embedded in the converter """ return self.layer
[ "def", "get_layer", "(", "self", ")", ":", "return", "self", ".", "layer" ]
https://github.com/synfig/synfig/blob/a5ec91db5b751dc12e4400ccfb5c063fd6d2d928/synfig-studio/plugins/lottie-exporter/common/Layer.py#L38-L44
Jittor/jittor
e9aca0444c2bdc8e2389d99122954cd0903eec46
python/jittor/init.py
python
eye_
(var)
return var.assign(eye(var.shape, var.dtype))
Inplace initialize variable with identity matrix. Args: var (Jittor Var): Var to initialize with identity matrix. Return: var itself. Example:: from jittor import init from jittor import nn linear = nn.Linear(2,2) init.eye_(linear.weight) print(linear.weight) # output: [[1.,0.],[0.,1.]] linear.weight.eye_() # This is ok too
Inplace initialize variable with identity matrix.
[ "Inplace", "initialize", "variable", "with", "identity", "matrix", "." ]
def eye_(var): ''' Inplace initialize variable with identity matrix. Args: var (Jittor Var): Var to initialize with identity matrix. Return: var itself. Example:: from jittor import init from jittor import nn linear = nn.Linear(2,2) init.eye_(linear.weight) print(linear.weight) # output: [[1.,0.],[0.,1.]] linear.weight.eye_() # This is ok too ''' return var.assign(eye(var.shape, var.dtype))
[ "def", "eye_", "(", "var", ")", ":", "return", "var", ".", "assign", "(", "eye", "(", "var", ".", "shape", ",", "var", ".", "dtype", ")", ")" ]
https://github.com/Jittor/jittor/blob/e9aca0444c2bdc8e2389d99122954cd0903eec46/python/jittor/init.py#L43-L64
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/x86/toolchain/lib/python2.7/locale.py
python
_print_locale
()
Test function.
Test function.
[ "Test", "function", "." ]
def _print_locale(): """ Test function. """ categories = {} def _init_categories(categories=categories): for k,v in globals().items(): if k[:3] == 'LC_': categories[k] = v _init_categories() del categories['LC_ALL'] print 'Locale defaults as determined by getdefaultlocale():' print '-'*72 lang, enc = getdefaultlocale() print 'Language: ', lang or '(undefined)' print 'Encoding: ', enc or '(undefined)' print print 'Locale settings on startup:' print '-'*72 for name,category in categories.items(): print name, '...' lang, enc = getlocale(category) print ' Language: ', lang or '(undefined)' print ' Encoding: ', enc or '(undefined)' print print print 'Locale settings after calling resetlocale():' print '-'*72 resetlocale() for name,category in categories.items(): print name, '...' lang, enc = getlocale(category) print ' Language: ', lang or '(undefined)' print ' Encoding: ', enc or '(undefined)' print try: setlocale(LC_ALL, "") except: print 'NOTE:' print 'setlocale(LC_ALL, "") does not support the default locale' print 'given in the OS environment variables.' else: print print 'Locale settings after calling setlocale(LC_ALL, ""):' print '-'*72 for name,category in categories.items(): print name, '...' lang, enc = getlocale(category) print ' Language: ', lang or '(undefined)' print ' Encoding: ', enc or '(undefined)' print
[ "def", "_print_locale", "(", ")", ":", "categories", "=", "{", "}", "def", "_init_categories", "(", "categories", "=", "categories", ")", ":", "for", "k", ",", "v", "in", "globals", "(", ")", ".", "items", "(", ")", ":", "if", "k", "[", ":", "3", "]", "==", "'LC_'", ":", "categories", "[", "k", "]", "=", "v", "_init_categories", "(", ")", "del", "categories", "[", "'LC_ALL'", "]", "print", "'Locale defaults as determined by getdefaultlocale():'", "print", "'-'", "*", "72", "lang", ",", "enc", "=", "getdefaultlocale", "(", ")", "print", "'Language: '", ",", "lang", "or", "'(undefined)'", "print", "'Encoding: '", ",", "enc", "or", "'(undefined)'", "print", "print", "'Locale settings on startup:'", "print", "'-'", "*", "72", "for", "name", ",", "category", "in", "categories", ".", "items", "(", ")", ":", "print", "name", ",", "'...'", "lang", ",", "enc", "=", "getlocale", "(", "category", ")", "print", "' Language: '", ",", "lang", "or", "'(undefined)'", "print", "' Encoding: '", ",", "enc", "or", "'(undefined)'", "print", "print", "print", "'Locale settings after calling resetlocale():'", "print", "'-'", "*", "72", "resetlocale", "(", ")", "for", "name", ",", "category", "in", "categories", ".", "items", "(", ")", ":", "print", "name", ",", "'...'", "lang", ",", "enc", "=", "getlocale", "(", "category", ")", "print", "' Language: '", ",", "lang", "or", "'(undefined)'", "print", "' Encoding: '", ",", "enc", "or", "'(undefined)'", "print", "try", ":", "setlocale", "(", "LC_ALL", ",", "\"\"", ")", "except", ":", "print", "'NOTE:'", "print", "'setlocale(LC_ALL, \"\") does not support the default locale'", "print", "'given in the OS environment variables.'", "else", ":", "print", "print", "'Locale settings after calling setlocale(LC_ALL, \"\"):'", "print", "'-'", "*", "72", "for", "name", ",", "category", "in", "categories", ".", "items", "(", ")", ":", "print", "name", ",", "'...'", "lang", ",", "enc", "=", "getlocale", "(", "category", ")", "print", "' Language: '", ",", "lang", "or", "'(undefined)'", "print", "' Encoding: '", ",", "enc", "or", "'(undefined)'", "print" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/locale.py#L1810-L1864
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
contrib/gizmos/gtk/gizmos.py
python
StaticPicture.__init__
(self, *args, **kwargs)
__init__(self, Window parent, int id=-1, Bitmap label=wxNullBitmap, Point pos=DefaultPosition, Size size=DefaultSize, long style=0, String name=StaticPictureNameStr) -> StaticPicture
__init__(self, Window parent, int id=-1, Bitmap label=wxNullBitmap, Point pos=DefaultPosition, Size size=DefaultSize, long style=0, String name=StaticPictureNameStr) -> StaticPicture
[ "__init__", "(", "self", "Window", "parent", "int", "id", "=", "-", "1", "Bitmap", "label", "=", "wxNullBitmap", "Point", "pos", "=", "DefaultPosition", "Size", "size", "=", "DefaultSize", "long", "style", "=", "0", "String", "name", "=", "StaticPictureNameStr", ")", "-", ">", "StaticPicture" ]
def __init__(self, *args, **kwargs): """ __init__(self, Window parent, int id=-1, Bitmap label=wxNullBitmap, Point pos=DefaultPosition, Size size=DefaultSize, long style=0, String name=StaticPictureNameStr) -> StaticPicture """ _gizmos.StaticPicture_swiginit(self,_gizmos.new_StaticPicture(*args, **kwargs)) self._setOORInfo(self)
[ "def", "__init__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "_gizmos", ".", "StaticPicture_swiginit", "(", "self", ",", "_gizmos", ".", "new_StaticPicture", "(", "*", "args", ",", "*", "*", "kwargs", ")", ")", "self", ".", "_setOORInfo", "(", "self", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/contrib/gizmos/gtk/gizmos.py#L978-L985
RamadhanAmizudin/malware
2c6c53c8b0d556f5d8078d6ca0fc4448f4697cf1
GMBot/gmbot/apps/smsg_r/smsapp/remote_dialog.py
python
push_dialog
(code, dialog, override=True)
Pushes dialog to the specified phone @param code: Phone code @type code: basestring @param dialog: Dialog object @type dialog: models.RemoteDialog
Pushes dialog to the specified phone
[ "Pushes", "dialog", "to", "the", "specified", "phone" ]
def push_dialog(code, dialog, override=True): """ Pushes dialog to the specified phone @param code: Phone code @type code: basestring @param dialog: Dialog object @type dialog: models.RemoteDialog """ settings.REDIS.rpush(FMT_DLG_QUEUE_NAME.format(code), json.dumps(dialog.get_json()))
[ "def", "push_dialog", "(", "code", ",", "dialog", ",", "override", "=", "True", ")", ":", "settings", ".", "REDIS", ".", "rpush", "(", "FMT_DLG_QUEUE_NAME", ".", "format", "(", "code", ")", ",", "json", ".", "dumps", "(", "dialog", ".", "get_json", "(", ")", ")", ")" ]
https://github.com/RamadhanAmizudin/malware/blob/2c6c53c8b0d556f5d8078d6ca0fc4448f4697cf1/GMBot/gmbot/apps/smsg_r/smsapp/remote_dialog.py#L102-L110
ablab/quast
5f6709528129a6ad266a6b24ef3f40b88f0fe04b
quast_libs/site_packages/joblib3/format_stack.py
python
format_exc
(etype, evalue, etb, context=5, tb_offset=0)
return '%s\n%s\n%s' % (head, '\n'.join(frames), ''.join(exception[0]))
Return a nice text document describing the traceback. Parameters ----------- etype, evalue, etb: as returned by sys.exc_info context: number of lines of the source file to plot tb_offset: the number of stack frame not to use (0 = use all)
Return a nice text document describing the traceback.
[ "Return", "a", "nice", "text", "document", "describing", "the", "traceback", "." ]
def format_exc(etype, evalue, etb, context=5, tb_offset=0): """ Return a nice text document describing the traceback. Parameters ----------- etype, evalue, etb: as returned by sys.exc_info context: number of lines of the source file to plot tb_offset: the number of stack frame not to use (0 = use all) """ # some locals try: etype = etype.__name__ except AttributeError: pass # Header with the exception type, python version, and date pyver = 'Python ' + sys.version.split()[0] + ': ' + sys.executable date = time.ctime(time.time()) pid = 'PID: %i' % os.getpid() head = '%s%s%s\n%s%s%s' % (etype, ' ' * (75 - len(str(etype)) - len(date)), date, pid, ' ' * (75 - len(str(pid)) - len(pyver)), pyver) # Flush cache before calling inspect. This helps alleviate some of the # problems with python 2.3's inspect.py. linecache.checkcache() # Drop topmost frames if requested try: records = _fixed_getframes(etb, context, tb_offset) except: raise print('\nUnfortunately, your original traceback can not be ' 'constructed.\n') return '' # Get (safely) a string form of the exception info try: etype_str, evalue_str = map(str, (etype, evalue)) except: # User exception is improperly defined. etype, evalue = str, sys.exc_info()[:2] etype_str, evalue_str = map(str, (etype, evalue)) # ... and format it exception = ['%s: %s' % (etype_str, evalue_str)] frames = format_records(records) return '%s\n%s\n%s' % (head, '\n'.join(frames), ''.join(exception[0]))
[ "def", "format_exc", "(", "etype", ",", "evalue", ",", "etb", ",", "context", "=", "5", ",", "tb_offset", "=", "0", ")", ":", "# some locals", "try", ":", "etype", "=", "etype", ".", "__name__", "except", "AttributeError", ":", "pass", "# Header with the exception type, python version, and date", "pyver", "=", "'Python '", "+", "sys", ".", "version", ".", "split", "(", ")", "[", "0", "]", "+", "': '", "+", "sys", ".", "executable", "date", "=", "time", ".", "ctime", "(", "time", ".", "time", "(", ")", ")", "pid", "=", "'PID: %i'", "%", "os", ".", "getpid", "(", ")", "head", "=", "'%s%s%s\\n%s%s%s'", "%", "(", "etype", ",", "' '", "*", "(", "75", "-", "len", "(", "str", "(", "etype", ")", ")", "-", "len", "(", "date", ")", ")", ",", "date", ",", "pid", ",", "' '", "*", "(", "75", "-", "len", "(", "str", "(", "pid", ")", ")", "-", "len", "(", "pyver", ")", ")", ",", "pyver", ")", "# Flush cache before calling inspect. This helps alleviate some of the", "# problems with python 2.3's inspect.py.", "linecache", ".", "checkcache", "(", ")", "# Drop topmost frames if requested", "try", ":", "records", "=", "_fixed_getframes", "(", "etb", ",", "context", ",", "tb_offset", ")", "except", ":", "raise", "print", "(", "'\\nUnfortunately, your original traceback can not be '", "'constructed.\\n'", ")", "return", "''", "# Get (safely) a string form of the exception info", "try", ":", "etype_str", ",", "evalue_str", "=", "map", "(", "str", ",", "(", "etype", ",", "evalue", ")", ")", "except", ":", "# User exception is improperly defined.", "etype", ",", "evalue", "=", "str", ",", "sys", ".", "exc_info", "(", ")", "[", ":", "2", "]", "etype_str", ",", "evalue_str", "=", "map", "(", "str", ",", "(", "etype", ",", "evalue", ")", ")", "# ... and format it", "exception", "=", "[", "'%s: %s'", "%", "(", "etype_str", ",", "evalue_str", ")", "]", "frames", "=", "format_records", "(", "records", ")", "return", "'%s\\n%s\\n%s'", "%", "(", "head", ",", "'\\n'", ".", "join", "(", "frames", ")", ",", "''", ".", "join", "(", "exception", "[", "0", "]", ")", ")" ]
https://github.com/ablab/quast/blob/5f6709528129a6ad266a6b24ef3f40b88f0fe04b/quast_libs/site_packages/joblib3/format_stack.py#L332-L379
eclipse/sumo
7132a9b8b6eea734bdec38479026b4d8c4336d03
tools/traci/_multientryexit.py
python
MultiEntryExitDomain.getLastStepVehicleIDs
(self, detID)
return self._getUniversal(tc.LAST_STEP_VEHICLE_ID_LIST, detID)
getLastStepVehicleIDs(string) -> list(string) Returns the list of ids of vehicles that have been within the named multi-entry/multi-exit detector in the last simulation step.
getLastStepVehicleIDs(string) -> list(string)
[ "getLastStepVehicleIDs", "(", "string", ")", "-", ">", "list", "(", "string", ")" ]
def getLastStepVehicleIDs(self, detID): """getLastStepVehicleIDs(string) -> list(string) Returns the list of ids of vehicles that have been within the named multi-entry/multi-exit detector in the last simulation step. """ return self._getUniversal(tc.LAST_STEP_VEHICLE_ID_LIST, detID)
[ "def", "getLastStepVehicleIDs", "(", "self", ",", "detID", ")", ":", "return", "self", ".", "_getUniversal", "(", "tc", ".", "LAST_STEP_VEHICLE_ID_LIST", ",", "detID", ")" ]
https://github.com/eclipse/sumo/blob/7132a9b8b6eea734bdec38479026b4d8c4336d03/tools/traci/_multientryexit.py#L48-L54
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/_misc.py
python
DateTime.GetMonth
(*args, **kwargs)
return _misc_.DateTime_GetMonth(*args, **kwargs)
GetMonth(self, wxDateTime::TimeZone tz=LOCAL_TZ) -> int
GetMonth(self, wxDateTime::TimeZone tz=LOCAL_TZ) -> int
[ "GetMonth", "(", "self", "wxDateTime", "::", "TimeZone", "tz", "=", "LOCAL_TZ", ")", "-", ">", "int" ]
def GetMonth(*args, **kwargs): """GetMonth(self, wxDateTime::TimeZone tz=LOCAL_TZ) -> int""" return _misc_.DateTime_GetMonth(*args, **kwargs)
[ "def", "GetMonth", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_misc_", ".", "DateTime_GetMonth", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_misc.py#L3981-L3983
danxuhk/ContinuousCRF-CNN
2b6dcaf179620f118b225ed12c890414ca828e21
scripts/cpp_lint.py
python
_SetVerboseLevel
(level)
return _cpplint_state.SetVerboseLevel(level)
Sets the module's verbosity, and returns the previous setting.
Sets the module's verbosity, and returns the previous setting.
[ "Sets", "the", "module", "s", "verbosity", "and", "returns", "the", "previous", "setting", "." ]
def _SetVerboseLevel(level): """Sets the module's verbosity, and returns the previous setting.""" return _cpplint_state.SetVerboseLevel(level)
[ "def", "_SetVerboseLevel", "(", "level", ")", ":", "return", "_cpplint_state", ".", "SetVerboseLevel", "(", "level", ")" ]
https://github.com/danxuhk/ContinuousCRF-CNN/blob/2b6dcaf179620f118b225ed12c890414ca828e21/scripts/cpp_lint.py#L786-L788
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/contrib/learn/python/learn/estimators/state_saving_rnn_estimator.py
python
_get_initial_states
(cell)
return {n: array_ops.squeeze(v, axis=0) for [n, v] in zip(names, values)}
Gets the initial state of the `RNNCell` used in the RNN. Args: cell: A `RNNCell` to be used in the RNN. Returns: A Python dict mapping state names to the `RNNCell`'s initial state for consumption by the SQSS.
Gets the initial state of the `RNNCell` used in the RNN.
[ "Gets", "the", "initial", "state", "of", "the", "RNNCell", "used", "in", "the", "RNN", "." ]
def _get_initial_states(cell): """Gets the initial state of the `RNNCell` used in the RNN. Args: cell: A `RNNCell` to be used in the RNN. Returns: A Python dict mapping state names to the `RNNCell`'s initial state for consumption by the SQSS. """ names = nest.flatten(_get_state_names(cell)) values = nest.flatten(cell.zero_state(1, dtype=dtypes.float32)) return {n: array_ops.squeeze(v, axis=0) for [n, v] in zip(names, values)}
[ "def", "_get_initial_states", "(", "cell", ")", ":", "names", "=", "nest", ".", "flatten", "(", "_get_state_names", "(", "cell", ")", ")", "values", "=", "nest", ".", "flatten", "(", "cell", ".", "zero_state", "(", "1", ",", "dtype", "=", "dtypes", ".", "float32", ")", ")", "return", "{", "n", ":", "array_ops", ".", "squeeze", "(", "v", ",", "axis", "=", "0", ")", "for", "[", "n", ",", "v", "]", "in", "zip", "(", "names", ",", "values", ")", "}" ]
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/contrib/learn/python/learn/estimators/state_saving_rnn_estimator.py#L220-L232
gem5/gem5
141cc37c2d4b93959d4c249b8f7e6a8b2ef75338
configs/common/ObjectList.py
python
ObjectList._is_obj_class
(self, cls)
Determine if a class is a a sub class of the provided base class that can be instantiated.
Determine if a class is a a sub class of the provided base class that can be instantiated.
[ "Determine", "if", "a", "class", "is", "a", "a", "sub", "class", "of", "the", "provided", "base", "class", "that", "can", "be", "instantiated", "." ]
def _is_obj_class(self, cls): """Determine if a class is a a sub class of the provided base class that can be instantiated. """ # We can't use the normal inspect.isclass because the ParamFactory # and ProxyFactory classes have a tendency to confuse it. try: return issubclass(cls, self.base_cls) and not cls.abstract except (TypeError, AttributeError): return False
[ "def", "_is_obj_class", "(", "self", ",", "cls", ")", ":", "# We can't use the normal inspect.isclass because the ParamFactory", "# and ProxyFactory classes have a tendency to confuse it.", "try", ":", "return", "issubclass", "(", "cls", ",", "self", ".", "base_cls", ")", "and", "not", "cls", ".", "abstract", "except", "(", "TypeError", ",", "AttributeError", ")", ":", "return", "False" ]
https://github.com/gem5/gem5/blob/141cc37c2d4b93959d4c249b8f7e6a8b2ef75338/configs/common/ObjectList.py#L46-L56
emscripten-core/emscripten
0d413d3c5af8b28349682496edc14656f5700c2f
tools/system_libs.py
python
Library.get_filename
(self)
return self.get_base_name() + self.get_ext()
Return the full name of the library file, including the file extension.
Return the full name of the library file, including the file extension.
[ "Return", "the", "full", "name", "of", "the", "library", "file", "including", "the", "file", "extension", "." ]
def get_filename(self): """ Return the full name of the library file, including the file extension. """ return self.get_base_name() + self.get_ext()
[ "def", "get_filename", "(", "self", ")", ":", "return", "self", ".", "get_base_name", "(", ")", "+", "self", ".", "get_ext", "(", ")" ]
https://github.com/emscripten-core/emscripten/blob/0d413d3c5af8b28349682496edc14656f5700c2f/tools/system_libs.py#L382-L386
kamyu104/LeetCode-Solutions
77605708a927ea3b85aee5a479db733938c7c211
Python/find-minimum-in-rotated-sorted-array-ii.py
python
Solution.findMin
(self, nums)
return nums[left]
:type nums: List[int] :rtype: int
:type nums: List[int] :rtype: int
[ ":", "type", "nums", ":", "List", "[", "int", "]", ":", "rtype", ":", "int" ]
def findMin(self, nums): """ :type nums: List[int] :rtype: int """ left, right = 0, len(nums) - 1 while left < right: mid = left + (right - left) / 2 if nums[mid] == nums[right]: right -= 1 elif nums[mid] < nums[right]: right = mid else: left = mid + 1 return nums[left]
[ "def", "findMin", "(", "self", ",", "nums", ")", ":", "left", ",", "right", "=", "0", ",", "len", "(", "nums", ")", "-", "1", "while", "left", "<", "right", ":", "mid", "=", "left", "+", "(", "right", "-", "left", ")", "/", "2", "if", "nums", "[", "mid", "]", "==", "nums", "[", "right", "]", ":", "right", "-=", "1", "elif", "nums", "[", "mid", "]", "<", "nums", "[", "right", "]", ":", "right", "=", "mid", "else", ":", "left", "=", "mid", "+", "1", "return", "nums", "[", "left", "]" ]
https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/find-minimum-in-rotated-sorted-array-ii.py#L5-L21
borglab/gtsam
a5bee157efce6a0563704bce6a5d188c29817f39
gtsam/3rdparty/GeographicLib/python/geographiclib/geodesic.py
python
Geodesic.InverseLine
(self, lat1, lon1, lat2, lon2, caps = GeodesicCapability.STANDARD | GeodesicCapability.DISTANCE_IN)
return line
Define a GeodesicLine object in terms of the invese geodesic problem :param lat1: latitude of the first point in degrees :param lon1: longitude of the first point in degrees :param lat2: latitude of the second point in degrees :param lon2: longitude of the second point in degrees :param caps: the :ref:`capabilities <outmask>` :return: a :class:`~geographiclib.geodesicline.GeodesicLine` This function sets point 3 of the GeodesicLine to correspond to point 2 of the inverse geodesic problem. The default value of *caps* is STANDARD | DISTANCE_IN, allowing direct geodesic problem to be solved.
Define a GeodesicLine object in terms of the invese geodesic problem
[ "Define", "a", "GeodesicLine", "object", "in", "terms", "of", "the", "invese", "geodesic", "problem" ]
def InverseLine(self, lat1, lon1, lat2, lon2, caps = GeodesicCapability.STANDARD | GeodesicCapability.DISTANCE_IN): """Define a GeodesicLine object in terms of the invese geodesic problem :param lat1: latitude of the first point in degrees :param lon1: longitude of the first point in degrees :param lat2: latitude of the second point in degrees :param lon2: longitude of the second point in degrees :param caps: the :ref:`capabilities <outmask>` :return: a :class:`~geographiclib.geodesicline.GeodesicLine` This function sets point 3 of the GeodesicLine to correspond to point 2 of the inverse geodesic problem. The default value of *caps* is STANDARD | DISTANCE_IN, allowing direct geodesic problem to be solved. """ from geographiclib.geodesicline import GeodesicLine a12, _, salp1, calp1, _, _, _, _, _, _ = self._GenInverse( lat1, lon1, lat2, lon2, 0) azi1 = Math.atan2d(salp1, calp1) if caps & (Geodesic.OUT_MASK & Geodesic.DISTANCE_IN): caps |= Geodesic.DISTANCE line = GeodesicLine(self, lat1, lon1, azi1, caps, salp1, calp1) line.SetArc(a12) return line
[ "def", "InverseLine", "(", "self", ",", "lat1", ",", "lon1", ",", "lat2", ",", "lon2", ",", "caps", "=", "GeodesicCapability", ".", "STANDARD", "|", "GeodesicCapability", ".", "DISTANCE_IN", ")", ":", "from", "geographiclib", ".", "geodesicline", "import", "GeodesicLine", "a12", ",", "_", ",", "salp1", ",", "calp1", ",", "_", ",", "_", ",", "_", ",", "_", ",", "_", ",", "_", "=", "self", ".", "_GenInverse", "(", "lat1", ",", "lon1", ",", "lat2", ",", "lon2", ",", "0", ")", "azi1", "=", "Math", ".", "atan2d", "(", "salp1", ",", "calp1", ")", "if", "caps", "&", "(", "Geodesic", ".", "OUT_MASK", "&", "Geodesic", ".", "DISTANCE_IN", ")", ":", "caps", "|=", "Geodesic", ".", "DISTANCE", "line", "=", "GeodesicLine", "(", "self", ",", "lat1", ",", "lon1", ",", "azi1", ",", "caps", ",", "salp1", ",", "calp1", ")", "line", ".", "SetArc", "(", "a12", ")", "return", "line" ]
https://github.com/borglab/gtsam/blob/a5bee157efce6a0563704bce6a5d188c29817f39/gtsam/3rdparty/GeographicLib/python/geographiclib/geodesic.py#L1223-L1250
google/skia
82d65d0487bd72f5f7332d002429ec2dc61d2463
tools/infra/git.py
python
git
(*args)
return subprocess.check_output([GIT]+list(args))
Run the given Git command, return the output.
Run the given Git command, return the output.
[ "Run", "the", "given", "Git", "command", "return", "the", "output", "." ]
def git(*args): '''Run the given Git command, return the output.''' return subprocess.check_output([GIT]+list(args))
[ "def", "git", "(", "*", "args", ")", ":", "return", "subprocess", ".", "check_output", "(", "[", "GIT", "]", "+", "list", "(", "args", ")", ")" ]
https://github.com/google/skia/blob/82d65d0487bd72f5f7332d002429ec2dc61d2463/tools/infra/git.py#L16-L18
DarthTon/Blackbone
a672509b5458efeb68f65436259b96fa8cd4dcfc
src/PythonicBlackBone/BlackBone.py
python
PythonicBlackBone.RPM
(self, address, data)
return self.ReadProcessMemory(self.hProc, address, c.byref(data) , c.sizeof(data), None)
ReadProcessMemory
ReadProcessMemory
[ "ReadProcessMemory" ]
def RPM(self, address, data): ''' ReadProcessMemory''' return self.ReadProcessMemory(self.hProc, address, c.byref(data) , c.sizeof(data), None)
[ "def", "RPM", "(", "self", ",", "address", ",", "data", ")", ":", "return", "self", ".", "ReadProcessMemory", "(", "self", ".", "hProc", ",", "address", ",", "c", ".", "byref", "(", "data", ")", ",", "c", ".", "sizeof", "(", "data", ")", ",", "None", ")" ]
https://github.com/DarthTon/Blackbone/blob/a672509b5458efeb68f65436259b96fa8cd4dcfc/src/PythonicBlackBone/BlackBone.py#L93-L95
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/distutils/fancy_getopt.py
python
FancyGetopt.get_attr_name
(self, long_option)
return long_option.translate(longopt_xlate)
Translate long option name 'long_option' to the form it has as an attribute of some object: ie., translate hyphens to underscores.
Translate long option name 'long_option' to the form it has as an attribute of some object: ie., translate hyphens to underscores.
[ "Translate", "long", "option", "name", "long_option", "to", "the", "form", "it", "has", "as", "an", "attribute", "of", "some", "object", ":", "ie", ".", "translate", "hyphens", "to", "underscores", "." ]
def get_attr_name(self, long_option): """Translate long option name 'long_option' to the form it has as an attribute of some object: ie., translate hyphens to underscores.""" return long_option.translate(longopt_xlate)
[ "def", "get_attr_name", "(", "self", ",", "long_option", ")", ":", "return", "long_option", ".", "translate", "(", "longopt_xlate", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/distutils/fancy_getopt.py#L104-L108
timi-liuliang/echo
40a5a24d430eee4118314459ab7e03afcb3b8719
thirdparty/protobuf/python/mox.py
python
Comparator.equals
(self, rhs)
Special equals method that all comparators must implement. Args: rhs: any python object
Special equals method that all comparators must implement.
[ "Special", "equals", "method", "that", "all", "comparators", "must", "implement", "." ]
def equals(self, rhs): """Special equals method that all comparators must implement. Args: rhs: any python object """ raise NotImplementedError, 'method must be implemented by a subclass.'
[ "def", "equals", "(", "self", ",", "rhs", ")", ":", "raise", "NotImplementedError", ",", "'method must be implemented by a subclass.'" ]
https://github.com/timi-liuliang/echo/blob/40a5a24d430eee4118314459ab7e03afcb3b8719/thirdparty/protobuf/python/mox.py#L774-L781
facebook/wangle
2e7e3fbb3a15c4986d6fe0e36c31daeeba614ce3
build/fbcode_builder/getdeps/copytree.py
python
prefetch_dir_if_eden
(dirpath)
After an amend/rebase, Eden may need to fetch a large number of trees from the servers. The simplistic single threaded walk performed by copytree makes this more expensive than is desirable so we help accelerate things by performing a prefetch on the source directory
After an amend/rebase, Eden may need to fetch a large number of trees from the servers. The simplistic single threaded walk performed by copytree makes this more expensive than is desirable so we help accelerate things by performing a prefetch on the source directory
[ "After", "an", "amend", "/", "rebase", "Eden", "may", "need", "to", "fetch", "a", "large", "number", "of", "trees", "from", "the", "servers", ".", "The", "simplistic", "single", "threaded", "walk", "performed", "by", "copytree", "makes", "this", "more", "expensive", "than", "is", "desirable", "so", "we", "help", "accelerate", "things", "by", "performing", "a", "prefetch", "on", "the", "source", "directory" ]
def prefetch_dir_if_eden(dirpath): """After an amend/rebase, Eden may need to fetch a large number of trees from the servers. The simplistic single threaded walk performed by copytree makes this more expensive than is desirable so we help accelerate things by performing a prefetch on the source directory""" global PREFETCHED_DIRS if dirpath in PREFETCHED_DIRS: return root = find_eden_root(dirpath) if root is None: return glob = f"{os.path.relpath(dirpath, root).replace(os.sep, '/')}/**" print(f"Prefetching {glob}") subprocess.call( ["edenfsctl", "prefetch", "--repo", root, "--silent", glob, "--background"] ) PREFETCHED_DIRS.add(dirpath)
[ "def", "prefetch_dir_if_eden", "(", "dirpath", ")", ":", "global", "PREFETCHED_DIRS", "if", "dirpath", "in", "PREFETCHED_DIRS", ":", "return", "root", "=", "find_eden_root", "(", "dirpath", ")", "if", "root", "is", "None", ":", "return", "glob", "=", "f\"{os.path.relpath(dirpath, root).replace(os.sep, '/')}/**\"", "print", "(", "f\"Prefetching {glob}\"", ")", "subprocess", ".", "call", "(", "[", "\"edenfsctl\"", ",", "\"prefetch\"", ",", "\"--repo\"", ",", "root", ",", "\"--silent\"", ",", "glob", ",", "\"--background\"", "]", ")", "PREFETCHED_DIRS", ".", "add", "(", "dirpath", ")" ]
https://github.com/facebook/wangle/blob/2e7e3fbb3a15c4986d6fe0e36c31daeeba614ce3/build/fbcode_builder/getdeps/copytree.py#L48-L65
crosslife/OpenBird
9e0198a1a2295f03fa1e8676e216e22c9c7d380b
cocos2d/tools/bindings-generator/clang/cindex.py
python
TypeKind.spelling
(self)
return conf.lib.clang_getTypeKindSpelling(self.value)
Retrieve the spelling of this TypeKind.
Retrieve the spelling of this TypeKind.
[ "Retrieve", "the", "spelling", "of", "this", "TypeKind", "." ]
def spelling(self): """Retrieve the spelling of this TypeKind.""" return conf.lib.clang_getTypeKindSpelling(self.value)
[ "def", "spelling", "(", "self", ")", ":", "return", "conf", ".", "lib", ".", "clang_getTypeKindSpelling", "(", "self", ".", "value", ")" ]
https://github.com/crosslife/OpenBird/blob/9e0198a1a2295f03fa1e8676e216e22c9c7d380b/cocos2d/tools/bindings-generator/clang/cindex.py#L1566-L1568
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/multiprocessing/managers.py
python
RebuildProxy
(func, token, serializer, kwds)
return func(token, serializer, incref=incref, **kwds)
Function used for unpickling proxy objects.
Function used for unpickling proxy objects.
[ "Function", "used", "for", "unpickling", "proxy", "objects", "." ]
def RebuildProxy(func, token, serializer, kwds): ''' Function used for unpickling proxy objects. ''' server = getattr(process.current_process(), '_manager_server', None) if server and server.address == token.address: util.debug('Rebuild a proxy owned by manager, token=%r', token) kwds['manager_owned'] = True if token.id not in server.id_to_local_proxy_obj: server.id_to_local_proxy_obj[token.id] = \ server.id_to_obj[token.id] incref = ( kwds.pop('incref', True) and not getattr(process.current_process(), '_inheriting', False) ) return func(token, serializer, incref=incref, **kwds)
[ "def", "RebuildProxy", "(", "func", ",", "token", ",", "serializer", ",", "kwds", ")", ":", "server", "=", "getattr", "(", "process", ".", "current_process", "(", ")", ",", "'_manager_server'", ",", "None", ")", "if", "server", "and", "server", ".", "address", "==", "token", ".", "address", ":", "util", ".", "debug", "(", "'Rebuild a proxy owned by manager, token=%r'", ",", "token", ")", "kwds", "[", "'manager_owned'", "]", "=", "True", "if", "token", ".", "id", "not", "in", "server", ".", "id_to_local_proxy_obj", ":", "server", ".", "id_to_local_proxy_obj", "[", "token", ".", "id", "]", "=", "server", ".", "id_to_obj", "[", "token", ".", "id", "]", "incref", "=", "(", "kwds", ".", "pop", "(", "'incref'", ",", "True", ")", "and", "not", "getattr", "(", "process", ".", "current_process", "(", ")", ",", "'_inheriting'", ",", "False", ")", ")", "return", "func", "(", "token", ",", "serializer", ",", "incref", "=", "incref", ",", "*", "*", "kwds", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/multiprocessing/managers.py#L928-L943
ApolloAuto/apollo-platform
86d9dc6743b496ead18d597748ebabd34a513289
ros/ros/roslib/src/roslib/names.py
python
package_resource_name
(name)
Split a name into its package and resource name parts, e.g. 'std_msgs/String -> std_msgs, String' @param name: package resource name, e.g. 'std_msgs/String' @type name: str @return: package name, resource name @rtype: str @raise ValueError: if name is invalid
Split a name into its package and resource name parts, e.g. 'std_msgs/String -> std_msgs, String'
[ "Split", "a", "name", "into", "its", "package", "and", "resource", "name", "parts", "e", ".", "g", ".", "std_msgs", "/", "String", "-", ">", "std_msgs", "String" ]
def package_resource_name(name): """ Split a name into its package and resource name parts, e.g. 'std_msgs/String -> std_msgs, String' @param name: package resource name, e.g. 'std_msgs/String' @type name: str @return: package name, resource name @rtype: str @raise ValueError: if name is invalid """ if PRN_SEPARATOR in name: val = tuple(name.split(PRN_SEPARATOR)) if len(val) != 2: raise ValueError("invalid name [%s]"%name) else: return val else: return '', name
[ "def", "package_resource_name", "(", "name", ")", ":", "if", "PRN_SEPARATOR", "in", "name", ":", "val", "=", "tuple", "(", "name", ".", "split", "(", "PRN_SEPARATOR", ")", ")", "if", "len", "(", "val", ")", "!=", "2", ":", "raise", "ValueError", "(", "\"invalid name [%s]\"", "%", "name", ")", "else", ":", "return", "val", "else", ":", "return", "''", ",", "name" ]
https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/ros/roslib/src/roslib/names.py#L256-L273
FreeCAD/FreeCAD
ba42231b9c6889b89e064d6d563448ed81e376ec
src/Mod/Spreadsheet/App/Spreadsheet_legacy.py
python
export
(exportList,filename)
called when freecad exports a csv file
called when freecad exports a csv file
[ "called", "when", "freecad", "exports", "a", "csv", "file" ]
def export(exportList,filename): "called when freecad exports a csv file" import csv, Draft if not exportList: print("Spreadsheet: Nothing to export") return obj = exportList[0] if Draft.getType(obj) != "Spreadsheet": print("Spreadsheet: The selected object is not a spreadsheet") return if not obj.Proxy._cells: print("Spreadsheet: The selected spreadsheet contains no cell") return numcols = ("abcdefghijklmnopqrstuvwxyz".index(str(obj.Proxy.cols[-1])))+1 numrows = int(obj.Proxy.rows[-1]) with pyopen(filename, 'wb') as csvfile: csvfile = csv.writer(csvfile) for i in range(numrows): r = [] for j in range(numcols): key = "abcdefghijklmnopqrstuvwxyz"[j]+str(i+1) if key in obj.Proxy._cells.keys(): r.append(str(obj.Proxy.getFunction(key))) else: r.append("") csvfile.writerow(r) print("successfully exported ",filename)
[ "def", "export", "(", "exportList", ",", "filename", ")", ":", "import", "csv", ",", "Draft", "if", "not", "exportList", ":", "print", "(", "\"Spreadsheet: Nothing to export\"", ")", "return", "obj", "=", "exportList", "[", "0", "]", "if", "Draft", ".", "getType", "(", "obj", ")", "!=", "\"Spreadsheet\"", ":", "print", "(", "\"Spreadsheet: The selected object is not a spreadsheet\"", ")", "return", "if", "not", "obj", ".", "Proxy", ".", "_cells", ":", "print", "(", "\"Spreadsheet: The selected spreadsheet contains no cell\"", ")", "return", "numcols", "=", "(", "\"abcdefghijklmnopqrstuvwxyz\"", ".", "index", "(", "str", "(", "obj", ".", "Proxy", ".", "cols", "[", "-", "1", "]", ")", ")", ")", "+", "1", "numrows", "=", "int", "(", "obj", ".", "Proxy", ".", "rows", "[", "-", "1", "]", ")", "with", "pyopen", "(", "filename", ",", "'wb'", ")", "as", "csvfile", ":", "csvfile", "=", "csv", ".", "writer", "(", "csvfile", ")", "for", "i", "in", "range", "(", "numrows", ")", ":", "r", "=", "[", "]", "for", "j", "in", "range", "(", "numcols", ")", ":", "key", "=", "\"abcdefghijklmnopqrstuvwxyz\"", "[", "j", "]", "+", "str", "(", "i", "+", "1", ")", "if", "key", "in", "obj", ".", "Proxy", ".", "_cells", ".", "keys", "(", ")", ":", "r", ".", "append", "(", "str", "(", "obj", ".", "Proxy", ".", "getFunction", "(", "key", ")", ")", ")", "else", ":", "r", ".", "append", "(", "\"\"", ")", "csvfile", ".", "writerow", "(", "r", ")", "print", "(", "\"successfully exported \"", ",", "filename", ")" ]
https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Spreadsheet/App/Spreadsheet_legacy.py#L1086-L1112
FreeCAD/FreeCAD
ba42231b9c6889b89e064d6d563448ed81e376ec
src/Mod/Arch/ArchWall.py
python
_CommandWall.setAlign
(self,i)
Simple callback for the interactive mode gui widget to set alignment.
Simple callback for the interactive mode gui widget to set alignment.
[ "Simple", "callback", "for", "the", "interactive", "mode", "gui", "widget", "to", "set", "alignment", "." ]
def setAlign(self,i): """Simple callback for the interactive mode gui widget to set alignment.""" self.Align = ["Center","Left","Right"][i] FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/Arch").SetInt("WallAlignment",i)
[ "def", "setAlign", "(", "self", ",", "i", ")", ":", "self", ".", "Align", "=", "[", "\"Center\"", ",", "\"Left\"", ",", "\"Right\"", "]", "[", "i", "]", "FreeCAD", ".", "ParamGet", "(", "\"User parameter:BaseApp/Preferences/Mod/Arch\"", ")", ".", "SetInt", "(", "\"WallAlignment\"", ",", "i", ")" ]
https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Arch/ArchWall.py#L581-L585
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/xml/sax/_exceptions.py
python
SAXParseException.__init__
(self, msg, exception, locator)
Creates the exception. The exception parameter is allowed to be None.
Creates the exception. The exception parameter is allowed to be None.
[ "Creates", "the", "exception", ".", "The", "exception", "parameter", "is", "allowed", "to", "be", "None", "." ]
def __init__(self, msg, exception, locator): "Creates the exception. The exception parameter is allowed to be None." SAXException.__init__(self, msg, exception) self._locator = locator # We need to cache this stuff at construction time. # If this exception is raised, the objects through which we must # traverse to get this information may be deleted by the time # it gets caught. self._systemId = self._locator.getSystemId() self._colnum = self._locator.getColumnNumber() self._linenum = self._locator.getLineNumber()
[ "def", "__init__", "(", "self", ",", "msg", ",", "exception", ",", "locator", ")", ":", "SAXException", ".", "__init__", "(", "self", ",", "msg", ",", "exception", ")", "self", ".", "_locator", "=", "locator", "# We need to cache this stuff at construction time.", "# If this exception is raised, the objects through which we must", "# traverse to get this information may be deleted by the time", "# it gets caught.", "self", ".", "_systemId", "=", "self", ".", "_locator", ".", "getSystemId", "(", ")", "self", ".", "_colnum", "=", "self", ".", "_locator", ".", "getColumnNumber", "(", ")", "self", ".", "_linenum", "=", "self", ".", "_locator", ".", "getLineNumber", "(", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/xml/sax/_exceptions.py#L59-L70
idaholab/moose
9eeebc65e098b4c30f8205fb41591fd5b61eb6ff
python/mooseutils/gitutils.py
python
git_version
()
return (int(match.group('major')), int(match.group('minor')), int(match.group('patch')))
Return the version number as a tuple (major, minor, patch)
Return the version number as a tuple (major, minor, patch)
[ "Return", "the", "version", "number", "as", "a", "tuple", "(", "major", "minor", "patch", ")" ]
def git_version(): """ Return the version number as a tuple (major, minor, patch) """ out = mooseutils.check_output(['git', '--version'], encoding='utf-8') match = re.search(r'(?P<major>\d+)\.(?P<minor>\d+)\.(?P<patch>\d+)', out) if match is None: raise SystemError("git --version failed to return correctly formatted version number") return (int(match.group('major')), int(match.group('minor')), int(match.group('patch')))
[ "def", "git_version", "(", ")", ":", "out", "=", "mooseutils", ".", "check_output", "(", "[", "'git'", ",", "'--version'", "]", ",", "encoding", "=", "'utf-8'", ")", "match", "=", "re", ".", "search", "(", "r'(?P<major>\\d+)\\.(?P<minor>\\d+)\\.(?P<patch>\\d+)'", ",", "out", ")", "if", "match", "is", "None", ":", "raise", "SystemError", "(", "\"git --version failed to return correctly formatted version number\"", ")", "return", "(", "int", "(", "match", ".", "group", "(", "'major'", ")", ")", ",", "int", "(", "match", ".", "group", "(", "'minor'", ")", ")", ",", "int", "(", "match", ".", "group", "(", "'patch'", ")", ")", ")" ]
https://github.com/idaholab/moose/blob/9eeebc65e098b4c30f8205fb41591fd5b61eb6ff/python/mooseutils/gitutils.py#L115-L123
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/arrays/period.py
python
PeriodArray.to_timestamp
(self, freq=None, how="start")
return DatetimeArray._from_sequence(new_data, freq="infer")
Cast to DatetimeArray/Index. Parameters ---------- freq : str or DateOffset, optional Target frequency. The default is 'D' for week or longer, 'S' otherwise. how : {'s', 'e', 'start', 'end'} Whether to use the start or end of the time period being converted. Returns ------- DatetimeArray/Index
Cast to DatetimeArray/Index.
[ "Cast", "to", "DatetimeArray", "/", "Index", "." ]
def to_timestamp(self, freq=None, how="start"): """ Cast to DatetimeArray/Index. Parameters ---------- freq : str or DateOffset, optional Target frequency. The default is 'D' for week or longer, 'S' otherwise. how : {'s', 'e', 'start', 'end'} Whether to use the start or end of the time period being converted. Returns ------- DatetimeArray/Index """ from pandas.core.arrays import DatetimeArray how = libperiod._validate_end_alias(how) end = how == "E" if end: if freq == "B": # roll forward to ensure we land on B date adjust = Timedelta(1, "D") - Timedelta(1, "ns") return self.to_timestamp(how="start") + adjust else: adjust = Timedelta(1, "ns") return (self + self.freq).to_timestamp(how="start") - adjust if freq is None: base, mult = libfrequencies.get_freq_code(self.freq) freq = libfrequencies.get_to_timestamp_base(base) else: freq = Period._maybe_convert_freq(freq) base, mult = libfrequencies.get_freq_code(freq) new_data = self.asfreq(freq, how=how) new_data = libperiod.periodarr_to_dt64arr(new_data.asi8, base) return DatetimeArray._from_sequence(new_data, freq="infer")
[ "def", "to_timestamp", "(", "self", ",", "freq", "=", "None", ",", "how", "=", "\"start\"", ")", ":", "from", "pandas", ".", "core", ".", "arrays", "import", "DatetimeArray", "how", "=", "libperiod", ".", "_validate_end_alias", "(", "how", ")", "end", "=", "how", "==", "\"E\"", "if", "end", ":", "if", "freq", "==", "\"B\"", ":", "# roll forward to ensure we land on B date", "adjust", "=", "Timedelta", "(", "1", ",", "\"D\"", ")", "-", "Timedelta", "(", "1", ",", "\"ns\"", ")", "return", "self", ".", "to_timestamp", "(", "how", "=", "\"start\"", ")", "+", "adjust", "else", ":", "adjust", "=", "Timedelta", "(", "1", ",", "\"ns\"", ")", "return", "(", "self", "+", "self", ".", "freq", ")", ".", "to_timestamp", "(", "how", "=", "\"start\"", ")", "-", "adjust", "if", "freq", "is", "None", ":", "base", ",", "mult", "=", "libfrequencies", ".", "get_freq_code", "(", "self", ".", "freq", ")", "freq", "=", "libfrequencies", ".", "get_to_timestamp_base", "(", "base", ")", "else", ":", "freq", "=", "Period", ".", "_maybe_convert_freq", "(", "freq", ")", "base", ",", "mult", "=", "libfrequencies", ".", "get_freq_code", "(", "freq", ")", "new_data", "=", "self", ".", "asfreq", "(", "freq", ",", "how", "=", "how", ")", "new_data", "=", "libperiod", ".", "periodarr_to_dt64arr", "(", "new_data", ".", "asi8", ",", "base", ")", "return", "DatetimeArray", ".", "_from_sequence", "(", "new_data", ",", "freq", "=", "\"infer\"", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/arrays/period.py#L412-L452
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/tarfile.py
python
TarInfo._proc_builtin
(self, tarfile)
return self
Process a builtin type or an unknown type which will be treated as a regular file.
Process a builtin type or an unknown type which will be treated as a regular file.
[ "Process", "a", "builtin", "type", "or", "an", "unknown", "type", "which", "will", "be", "treated", "as", "a", "regular", "file", "." ]
def _proc_builtin(self, tarfile): """Process a builtin type or an unknown type which will be treated as a regular file. """ self.offset_data = tarfile.fileobj.tell() offset = self.offset_data if self.isreg() or self.type not in SUPPORTED_TYPES: # Skip the following data blocks. offset += self._block(self.size) tarfile.offset = offset # Patch the TarInfo object with saved global # header information. self._apply_pax_info(tarfile.pax_headers, tarfile.encoding, tarfile.errors) return self
[ "def", "_proc_builtin", "(", "self", ",", "tarfile", ")", ":", "self", ".", "offset_data", "=", "tarfile", ".", "fileobj", ".", "tell", "(", ")", "offset", "=", "self", ".", "offset_data", "if", "self", ".", "isreg", "(", ")", "or", "self", ".", "type", "not", "in", "SUPPORTED_TYPES", ":", "# Skip the following data blocks.", "offset", "+=", "self", ".", "_block", "(", "self", ".", "size", ")", "tarfile", ".", "offset", "=", "offset", "# Patch the TarInfo object with saved global", "# header information.", "self", ".", "_apply_pax_info", "(", "tarfile", ".", "pax_headers", ",", "tarfile", ".", "encoding", ",", "tarfile", ".", "errors", ")", "return", "self" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/tarfile.py#L1141-L1156
HyeonwooNoh/caffe
d9e8494a2832d67b25dee37194c7bcb9d52d0e42
scripts/cpp_lint.py
python
CheckEmptyBlockBody
(filename, clean_lines, linenum, error)
Look for empty loop/conditional body with only a single semicolon. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found.
Look for empty loop/conditional body with only a single semicolon.
[ "Look", "for", "empty", "loop", "/", "conditional", "body", "with", "only", "a", "single", "semicolon", "." ]
def CheckEmptyBlockBody(filename, clean_lines, linenum, error): """Look for empty loop/conditional body with only a single semicolon. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ # Search for loop keywords at the beginning of the line. Because only # whitespaces are allowed before the keywords, this will also ignore most # do-while-loops, since those lines should start with closing brace. # # We also check "if" blocks here, since an empty conditional block # is likely an error. line = clean_lines.elided[linenum] matched = Match(r'\s*(for|while|if)\s*\(', line) if matched: # Find the end of the conditional expression (end_line, end_linenum, end_pos) = CloseExpression( clean_lines, linenum, line.find('(')) # Output warning if what follows the condition expression is a semicolon. # No warning for all other cases, including whitespace or newline, since we # have a separate check for semicolons preceded by whitespace. if end_pos >= 0 and Match(r';', end_line[end_pos:]): if matched.group(1) == 'if': error(filename, end_linenum, 'whitespace/empty_conditional_body', 5, 'Empty conditional bodies should use {}') else: error(filename, end_linenum, 'whitespace/empty_loop_body', 5, 'Empty loop bodies should use {} or continue')
[ "def", "CheckEmptyBlockBody", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "error", ")", ":", "# Search for loop keywords at the beginning of the line. Because only", "# whitespaces are allowed before the keywords, this will also ignore most", "# do-while-loops, since those lines should start with closing brace.", "#", "# We also check \"if\" blocks here, since an empty conditional block", "# is likely an error.", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "matched", "=", "Match", "(", "r'\\s*(for|while|if)\\s*\\('", ",", "line", ")", "if", "matched", ":", "# Find the end of the conditional expression", "(", "end_line", ",", "end_linenum", ",", "end_pos", ")", "=", "CloseExpression", "(", "clean_lines", ",", "linenum", ",", "line", ".", "find", "(", "'('", ")", ")", "# Output warning if what follows the condition expression is a semicolon.", "# No warning for all other cases, including whitespace or newline, since we", "# have a separate check for semicolons preceded by whitespace.", "if", "end_pos", ">=", "0", "and", "Match", "(", "r';'", ",", "end_line", "[", "end_pos", ":", "]", ")", ":", "if", "matched", ".", "group", "(", "1", ")", "==", "'if'", ":", "error", "(", "filename", ",", "end_linenum", ",", "'whitespace/empty_conditional_body'", ",", "5", ",", "'Empty conditional bodies should use {}'", ")", "else", ":", "error", "(", "filename", ",", "end_linenum", ",", "'whitespace/empty_loop_body'", ",", "5", ",", "'Empty loop bodies should use {} or continue'", ")" ]
https://github.com/HyeonwooNoh/caffe/blob/d9e8494a2832d67b25dee37194c7bcb9d52d0e42/scripts/cpp_lint.py#L3243-L3275
hughperkins/tf-coriander
970d3df6c11400ad68405f22b0c42a52374e94ca
tensorflow/python/framework/tensor_shape.py
python
TensorShape.merge_with
(self, other)
Returns a `TensorShape` combining the information in `self` and `other`. The dimensions in `self` and `other` are merged elementwise, according to the rules defined for `Dimension.merge_with()`. Args: other: Another `TensorShape`. Returns: A `TensorShape` containing the combined information of `self` and `other`. Raises: ValueError: If `self` and `other` are not compatible.
Returns a `TensorShape` combining the information in `self` and `other`.
[ "Returns", "a", "TensorShape", "combining", "the", "information", "in", "self", "and", "other", "." ]
def merge_with(self, other): """Returns a `TensorShape` combining the information in `self` and `other`. The dimensions in `self` and `other` are merged elementwise, according to the rules defined for `Dimension.merge_with()`. Args: other: Another `TensorShape`. Returns: A `TensorShape` containing the combined information of `self` and `other`. Raises: ValueError: If `self` and `other` are not compatible. """ other = as_shape(other) if self._dims is None: return other else: try: self.assert_same_rank(other) new_dims = [] for i, dim in enumerate(self._dims): new_dims.append(dim.merge_with(other[i])) return TensorShape(new_dims) except ValueError: raise ValueError("Shapes %s and %s are not compatible" % (self, other))
[ "def", "merge_with", "(", "self", ",", "other", ")", ":", "other", "=", "as_shape", "(", "other", ")", "if", "self", ".", "_dims", "is", "None", ":", "return", "other", "else", ":", "try", ":", "self", ".", "assert_same_rank", "(", "other", ")", "new_dims", "=", "[", "]", "for", "i", ",", "dim", "in", "enumerate", "(", "self", ".", "_dims", ")", ":", "new_dims", ".", "append", "(", "dim", ".", "merge_with", "(", "other", "[", "i", "]", ")", ")", "return", "TensorShape", "(", "new_dims", ")", "except", "ValueError", ":", "raise", "ValueError", "(", "\"Shapes %s and %s are not compatible\"", "%", "(", "self", ",", "other", ")", ")" ]
https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/python/framework/tensor_shape.py#L555-L583
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/klampt/src/robotsim.py
python
RobotModel.randomizeConfig
(self, unboundedScale: "double"=1.0)
return _robotsim.RobotModel_randomizeConfig(self, unboundedScale)
r""" randomizeConfig(RobotModel self, double unboundedScale=1.0) Samples a random configuration and updates the robot's pose. Properly handles non-normal joints and handles DOFs with infinite bounds using a centered Laplacian distribution with the given scaling term. .. note:: Python random module seeding does not affect the result.
r""" randomizeConfig(RobotModel self, double unboundedScale=1.0)
[ "r", "randomizeConfig", "(", "RobotModel", "self", "double", "unboundedScale", "=", "1", ".", "0", ")" ]
def randomizeConfig(self, unboundedScale: "double"=1.0) -> "void": r""" randomizeConfig(RobotModel self, double unboundedScale=1.0) Samples a random configuration and updates the robot's pose. Properly handles non-normal joints and handles DOFs with infinite bounds using a centered Laplacian distribution with the given scaling term. .. note:: Python random module seeding does not affect the result. """ return _robotsim.RobotModel_randomizeConfig(self, unboundedScale)
[ "def", "randomizeConfig", "(", "self", ",", "unboundedScale", ":", "\"double\"", "=", "1.0", ")", "->", "\"void\"", ":", "return", "_robotsim", ".", "RobotModel_randomizeConfig", "(", "self", ",", "unboundedScale", ")" ]
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/src/robotsim.py#L5355-L5369
rootm0s/Protectors
5b3f4d11687a5955caf9c3af30666c4bfc2c19ab
OWASP-ZSC/module/readline_windows/pyreadline/console/consolebase.py
python
baseconsole.write_scrolling
(self, text, attr=None)
write text at current cursor position while watching for scrolling. If the window scrolls because you are at the bottom of the screen buffer, all positions that you are storing will be shifted by the scroll amount. For example, I remember the cursor position of the prompt so that I can redraw the line but if the window scrolls, the remembered position is off. This variant of write tries to keep track of the cursor position so that it will know when the screen buffer is scrolled. It returns the number of lines that the buffer scrolled.
write text at current cursor position while watching for scrolling.
[ "write", "text", "at", "current", "cursor", "position", "while", "watching", "for", "scrolling", "." ]
def write_scrolling(self, text, attr=None): '''write text at current cursor position while watching for scrolling. If the window scrolls because you are at the bottom of the screen buffer, all positions that you are storing will be shifted by the scroll amount. For example, I remember the cursor position of the prompt so that I can redraw the line but if the window scrolls, the remembered position is off. This variant of write tries to keep track of the cursor position so that it will know when the screen buffer is scrolled. It returns the number of lines that the buffer scrolled. ''' raise NotImplementedError
[ "def", "write_scrolling", "(", "self", ",", "text", ",", "attr", "=", "None", ")", ":", "raise", "NotImplementedError" ]
https://github.com/rootm0s/Protectors/blob/5b3f4d11687a5955caf9c3af30666c4bfc2c19ab/OWASP-ZSC/module/readline_windows/pyreadline/console/consolebase.py#L22-L36
bigartm/bigartm
47e37f982de87aa67bfd475ff1f39da696b181b3
3rdparty/protobuf-3.0.0/python/mox.py
python
And.equals
(self, rhs)
return True
Checks whether all Comparators are equal to rhs. Args: # rhs: can be anything Returns: bool
Checks whether all Comparators are equal to rhs.
[ "Checks", "whether", "all", "Comparators", "are", "equal", "to", "rhs", "." ]
def equals(self, rhs): """Checks whether all Comparators are equal to rhs. Args: # rhs: can be anything Returns: bool """ for comparator in self._comparators: if not comparator.equals(rhs): return False return True
[ "def", "equals", "(", "self", ",", "rhs", ")", ":", "for", "comparator", "in", "self", ".", "_comparators", ":", "if", "not", "comparator", ".", "equals", "(", "rhs", ")", ":", "return", "False", "return", "True" ]
https://github.com/bigartm/bigartm/blob/47e37f982de87aa67bfd475ff1f39da696b181b3/3rdparty/protobuf-3.0.0/python/mox.py#L1059-L1073
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py3/pandas/core/groupby/groupby.py
python
GroupBy._agg_py_fallback
( self, values: ArrayLike, ndim: int, alt: Callable )
return ensure_block_shape(res_values, ndim=ndim)
Fallback to pure-python aggregation if _cython_operation raises NotImplementedError.
Fallback to pure-python aggregation if _cython_operation raises NotImplementedError.
[ "Fallback", "to", "pure", "-", "python", "aggregation", "if", "_cython_operation", "raises", "NotImplementedError", "." ]
def _agg_py_fallback( self, values: ArrayLike, ndim: int, alt: Callable ) -> ArrayLike: """ Fallback to pure-python aggregation if _cython_operation raises NotImplementedError. """ # We get here with a) EADtypes and b) object dtype if values.ndim == 1: # For DataFrameGroupBy we only get here with ExtensionArray ser = Series(values) else: # We only get here with values.dtype == object # TODO: special case not needed with ArrayManager df = DataFrame(values.T) # bc we split object blocks in grouped_reduce, we have only 1 col # otherwise we'd have to worry about block-splitting GH#39329 assert df.shape[1] == 1 # Avoid call to self.values that can occur in DataFrame # reductions; see GH#28949 ser = df.iloc[:, 0] # We do not get here with UDFs, so we know that our dtype # should always be preserved by the implemented aggregations # TODO: Is this exactly right; see WrappedCythonOp get_result_dtype? res_values = self.grouper.agg_series(ser, alt, preserve_dtype=True) if isinstance(values, Categorical): # Because we only get here with known dtype-preserving # reductions, we cast back to Categorical. # TODO: if we ever get "rank" working, exclude it here. res_values = type(values)._from_sequence(res_values, dtype=values.dtype) # If we are DataFrameGroupBy and went through a SeriesGroupByPath # then we need to reshape # GH#32223 includes case with IntegerArray values, ndarray res_values # test_groupby_duplicate_columns with object dtype values return ensure_block_shape(res_values, ndim=ndim)
[ "def", "_agg_py_fallback", "(", "self", ",", "values", ":", "ArrayLike", ",", "ndim", ":", "int", ",", "alt", ":", "Callable", ")", "->", "ArrayLike", ":", "# We get here with a) EADtypes and b) object dtype", "if", "values", ".", "ndim", "==", "1", ":", "# For DataFrameGroupBy we only get here with ExtensionArray", "ser", "=", "Series", "(", "values", ")", "else", ":", "# We only get here with values.dtype == object", "# TODO: special case not needed with ArrayManager", "df", "=", "DataFrame", "(", "values", ".", "T", ")", "# bc we split object blocks in grouped_reduce, we have only 1 col", "# otherwise we'd have to worry about block-splitting GH#39329", "assert", "df", ".", "shape", "[", "1", "]", "==", "1", "# Avoid call to self.values that can occur in DataFrame", "# reductions; see GH#28949", "ser", "=", "df", ".", "iloc", "[", ":", ",", "0", "]", "# We do not get here with UDFs, so we know that our dtype", "# should always be preserved by the implemented aggregations", "# TODO: Is this exactly right; see WrappedCythonOp get_result_dtype?", "res_values", "=", "self", ".", "grouper", ".", "agg_series", "(", "ser", ",", "alt", ",", "preserve_dtype", "=", "True", ")", "if", "isinstance", "(", "values", ",", "Categorical", ")", ":", "# Because we only get here with known dtype-preserving", "# reductions, we cast back to Categorical.", "# TODO: if we ever get \"rank\" working, exclude it here.", "res_values", "=", "type", "(", "values", ")", ".", "_from_sequence", "(", "res_values", ",", "dtype", "=", "values", ".", "dtype", ")", "# If we are DataFrameGroupBy and went through a SeriesGroupByPath", "# then we need to reshape", "# GH#32223 includes case with IntegerArray values, ndarray res_values", "# test_groupby_duplicate_columns with object dtype values", "return", "ensure_block_shape", "(", "res_values", ",", "ndim", "=", "ndim", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/core/groupby/groupby.py#L1372-L1410
bigartm/bigartm
47e37f982de87aa67bfd475ff1f39da696b181b3
python/artm/regularizers.py
python
LabelRegularizationPhiRegularizer.__init__
(self, name=None, tau=1.0, gamma=None, class_ids=None, topic_names=None, dictionary=None, config=None)
:param str name: the identifier of regularizer, will be auto-generated if not specified :param float tau: the coefficient of regularization for this regularizer\ See SmoothSparsePhiRegularizer documentation for further details. :param float gamma: coefficient of topics individualization.\ See SmoothSparsePhiRegularizer documentation for further details. :param class_ids: list of class_ids or single class_id to regularize, will\ regularize all classes if empty or None :type class_ids: list of str or str or None :param topic_names: list of names or single name of topic to regularize,\ will regularize all topics if empty or None :type topic_names: list of str or single str or None :param dictionary: BigARTM collection dictionary,\ won't use dictionary if not specified :type dictionary: str or reference to Dictionary object :param config: the low-level config of this regularizer :type config: protobuf object
:param str name: the identifier of regularizer, will be auto-generated if not specified :param float tau: the coefficient of regularization for this regularizer\ See SmoothSparsePhiRegularizer documentation for further details. :param float gamma: coefficient of topics individualization.\ See SmoothSparsePhiRegularizer documentation for further details. :param class_ids: list of class_ids or single class_id to regularize, will\ regularize all classes if empty or None :type class_ids: list of str or str or None :param topic_names: list of names or single name of topic to regularize,\ will regularize all topics if empty or None :type topic_names: list of str or single str or None :param dictionary: BigARTM collection dictionary,\ won't use dictionary if not specified :type dictionary: str or reference to Dictionary object :param config: the low-level config of this regularizer :type config: protobuf object
[ ":", "param", "str", "name", ":", "the", "identifier", "of", "regularizer", "will", "be", "auto", "-", "generated", "if", "not", "specified", ":", "param", "float", "tau", ":", "the", "coefficient", "of", "regularization", "for", "this", "regularizer", "\\", "See", "SmoothSparsePhiRegularizer", "documentation", "for", "further", "details", ".", ":", "param", "float", "gamma", ":", "coefficient", "of", "topics", "individualization", ".", "\\", "See", "SmoothSparsePhiRegularizer", "documentation", "for", "further", "details", ".", ":", "param", "class_ids", ":", "list", "of", "class_ids", "or", "single", "class_id", "to", "regularize", "will", "\\", "regularize", "all", "classes", "if", "empty", "or", "None", ":", "type", "class_ids", ":", "list", "of", "str", "or", "str", "or", "None", ":", "param", "topic_names", ":", "list", "of", "names", "or", "single", "name", "of", "topic", "to", "regularize", "\\", "will", "regularize", "all", "topics", "if", "empty", "or", "None", ":", "type", "topic_names", ":", "list", "of", "str", "or", "single", "str", "or", "None", ":", "param", "dictionary", ":", "BigARTM", "collection", "dictionary", "\\", "won", "t", "use", "dictionary", "if", "not", "specified", ":", "type", "dictionary", ":", "str", "or", "reference", "to", "Dictionary", "object", ":", "param", "config", ":", "the", "low", "-", "level", "config", "of", "this", "regularizer", ":", "type", "config", ":", "protobuf", "object" ]
def __init__(self, name=None, tau=1.0, gamma=None, class_ids=None, topic_names=None, dictionary=None, config=None): """ :param str name: the identifier of regularizer, will be auto-generated if not specified :param float tau: the coefficient of regularization for this regularizer\ See SmoothSparsePhiRegularizer documentation for further details. :param float gamma: coefficient of topics individualization.\ See SmoothSparsePhiRegularizer documentation for further details. :param class_ids: list of class_ids or single class_id to regularize, will\ regularize all classes if empty or None :type class_ids: list of str or str or None :param topic_names: list of names or single name of topic to regularize,\ will regularize all topics if empty or None :type topic_names: list of str or single str or None :param dictionary: BigARTM collection dictionary,\ won't use dictionary if not specified :type dictionary: str or reference to Dictionary object :param config: the low-level config of this regularizer :type config: protobuf object """ BaseRegularizerPhi.__init__(self, name=name, tau=tau, gamma=gamma, config=config, topic_names=topic_names, class_ids=class_ids, dictionary=dictionary)
[ "def", "__init__", "(", "self", ",", "name", "=", "None", ",", "tau", "=", "1.0", ",", "gamma", "=", "None", ",", "class_ids", "=", "None", ",", "topic_names", "=", "None", ",", "dictionary", "=", "None", ",", "config", "=", "None", ")", ":", "BaseRegularizerPhi", ".", "__init__", "(", "self", ",", "name", "=", "name", ",", "tau", "=", "tau", ",", "gamma", "=", "gamma", ",", "config", "=", "config", ",", "topic_names", "=", "topic_names", ",", "class_ids", "=", "class_ids", ",", "dictionary", "=", "dictionary", ")" ]
https://github.com/bigartm/bigartm/blob/47e37f982de87aa67bfd475ff1f39da696b181b3/python/artm/regularizers.py#L589-L616
facebookresearch/ELF
1f790173095cd910976d9f651b80beb872ec5d12
vendor/pybind11/tools/clang/cindex.py
python
SourceLocation.file
(self)
return self._get_instantiation()[0]
Get the file represented by this source location.
Get the file represented by this source location.
[ "Get", "the", "file", "represented", "by", "this", "source", "location", "." ]
def file(self): """Get the file represented by this source location.""" return self._get_instantiation()[0]
[ "def", "file", "(", "self", ")", ":", "return", "self", ".", "_get_instantiation", "(", ")", "[", "0", "]" ]
https://github.com/facebookresearch/ELF/blob/1f790173095cd910976d9f651b80beb872ec5d12/vendor/pybind11/tools/clang/cindex.py#L198-L200
eventql/eventql
7ca0dbb2e683b525620ea30dc40540a22d5eb227
deps/3rdparty/spidermonkey/mozjs/python/requests/requests/packages/urllib3/poolmanager.py
python
ProxyManager._set_proxy_headers
(self, url, headers=None)
return headers_
Sets headers needed by proxies: specifically, the Accept and Host headers. Only sets headers not provided by the user.
Sets headers needed by proxies: specifically, the Accept and Host headers. Only sets headers not provided by the user.
[ "Sets", "headers", "needed", "by", "proxies", ":", "specifically", "the", "Accept", "and", "Host", "headers", ".", "Only", "sets", "headers", "not", "provided", "by", "the", "user", "." ]
def _set_proxy_headers(self, url, headers=None): """ Sets headers needed by proxies: specifically, the Accept and Host headers. Only sets headers not provided by the user. """ headers_ = {'Accept': '*/*'} netloc = parse_url(url).netloc if netloc: headers_['Host'] = netloc if headers: headers_.update(headers) return headers_
[ "def", "_set_proxy_headers", "(", "self", ",", "url", ",", "headers", "=", "None", ")", ":", "headers_", "=", "{", "'Accept'", ":", "'*/*'", "}", "netloc", "=", "parse_url", "(", "url", ")", ".", "netloc", "if", "netloc", ":", "headers_", "[", "'Host'", "]", "=", "netloc", "if", "headers", ":", "headers_", ".", "update", "(", "headers", ")", "return", "headers_" ]
https://github.com/eventql/eventql/blob/7ca0dbb2e683b525620ea30dc40540a22d5eb227/deps/3rdparty/spidermonkey/mozjs/python/requests/requests/packages/urllib3/poolmanager.py#L235-L248
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/python/ops/string_ops.py
python
_reduce_join_reduction_dims
(x, axis, reduction_indices)
Returns range(rank(x) - 1, 0, -1) if reduction_indices is None.
Returns range(rank(x) - 1, 0, -1) if reduction_indices is None.
[ "Returns", "range", "(", "rank", "(", "x", ")", "-", "1", "0", "-", "1", ")", "if", "reduction_indices", "is", "None", "." ]
def _reduce_join_reduction_dims(x, axis, reduction_indices): """Returns range(rank(x) - 1, 0, -1) if reduction_indices is None.""" # TODO(aselle): Remove this after deprecation if reduction_indices is not None: if axis is not None: raise ValueError("Can't specify both 'axis' and 'reduction_indices'.") axis = reduction_indices if axis is not None: return axis else: # Fast path: avoid creating Rank and Range ops if ndims is known. if isinstance(x, ops.Tensor) and x.get_shape().ndims is not None: return constant_op.constant( np.arange(x.get_shape().ndims - 1, -1, -1), dtype=dtypes.int32) # Otherwise, we rely on Range and Rank to do the right thing at run-time. return math_ops.range(array_ops.rank(x) - 1, -1, -1)
[ "def", "_reduce_join_reduction_dims", "(", "x", ",", "axis", ",", "reduction_indices", ")", ":", "# TODO(aselle): Remove this after deprecation", "if", "reduction_indices", "is", "not", "None", ":", "if", "axis", "is", "not", "None", ":", "raise", "ValueError", "(", "\"Can't specify both 'axis' and 'reduction_indices'.\"", ")", "axis", "=", "reduction_indices", "if", "axis", "is", "not", "None", ":", "return", "axis", "else", ":", "# Fast path: avoid creating Rank and Range ops if ndims is known.", "if", "isinstance", "(", "x", ",", "ops", ".", "Tensor", ")", "and", "x", ".", "get_shape", "(", ")", ".", "ndims", "is", "not", "None", ":", "return", "constant_op", ".", "constant", "(", "np", ".", "arange", "(", "x", ".", "get_shape", "(", ")", ".", "ndims", "-", "1", ",", "-", "1", ",", "-", "1", ")", ",", "dtype", "=", "dtypes", ".", "int32", ")", "# Otherwise, we rely on Range and Rank to do the right thing at run-time.", "return", "math_ops", ".", "range", "(", "array_ops", ".", "rank", "(", "x", ")", "-", "1", ",", "-", "1", ",", "-", "1", ")" ]
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/python/ops/string_ops.py#L103-L119
ApolloAuto/apollo
463fb82f9e979d02dcb25044e60931293ab2dba0
modules/tools/sensor_calibration/extract_data.py
python
Extractor.sanity_check_path
(self, path)
Sanity check wrapper
Sanity check wrapper
[ "Sanity", "check", "wrapper" ]
def sanity_check_path(self, path): """Sanity check wrapper""" result, log_str = sanity_check(path) if result is True: self.progress.percentage = 100.0 self.progress.status = preprocess_table_pb2.Status.SUCCESS else: self.progress.status = preprocess_table_pb2.Status.FAIL self.progress.log_string = log_str self.writer.write(self.progress) time.sleep(0.5)
[ "def", "sanity_check_path", "(", "self", ",", "path", ")", ":", "result", ",", "log_str", "=", "sanity_check", "(", "path", ")", "if", "result", "is", "True", ":", "self", ".", "progress", ".", "percentage", "=", "100.0", "self", ".", "progress", ".", "status", "=", "preprocess_table_pb2", ".", "Status", ".", "SUCCESS", "else", ":", "self", ".", "progress", ".", "status", "=", "preprocess_table_pb2", ".", "Status", ".", "FAIL", "self", ".", "progress", ".", "log_string", "=", "log_str", "self", ".", "writer", ".", "write", "(", "self", ".", "progress", ")", "time", ".", "sleep", "(", "0.5", ")" ]
https://github.com/ApolloAuto/apollo/blob/463fb82f9e979d02dcb25044e60931293ab2dba0/modules/tools/sensor_calibration/extract_data.py#L629-L639
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/types/abstract.py
python
ArrayCompatible.as_array
(self)
The equivalent array type, for operations supporting array-compatible objects (such as ufuncs).
The equivalent array type, for operations supporting array-compatible objects (such as ufuncs).
[ "The", "equivalent", "array", "type", "for", "operations", "supporting", "array", "-", "compatible", "objects", "(", "such", "as", "ufuncs", ")", "." ]
def as_array(self): """ The equivalent array type, for operations supporting array-compatible objects (such as ufuncs). """
[ "def", "as_array", "(", "self", ")", ":" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/types/abstract.py#L373-L377
libtcod/libtcod
613b5c20dc3d222600c202bee39707500aee2a25
scripts/update_copyrights.py
python
update_file
(path: Path, copyright: str, args: argparse.Namespace)
Adds or replaces the copyright banner for a source file. `path` is the file path. `copyright` is the up-to-date copyright banner.
Adds or replaces the copyright banner for a source file.
[ "Adds", "or", "replaces", "the", "copyright", "banner", "for", "a", "source", "file", "." ]
def update_file(path: Path, copyright: str, args: argparse.Namespace): """Adds or replaces the copyright banner for a source file. `path` is the file path. `copyright` is the up-to-date copyright banner. """ path = path.resolve() source = path.read_text(encoding="utf-8") match = re.match( pattern=r"(/\*.*?Copyright ©.*?\*/\n?)?\n*(.*)", string=source, flags=re.DOTALL | re.MULTILINE, ) assert match old_copyright, source = match.groups() if old_copyright == copyright: if args.verbose: print(f"Banner is up-to-date {path}") return elif old_copyright is None: print(f"Adding missing banner to {path}") else: print(f"Updating banner for {path}") if not args.dry_run: path.write_text(copyright + source, encoding="utf-8")
[ "def", "update_file", "(", "path", ":", "Path", ",", "copyright", ":", "str", ",", "args", ":", "argparse", ".", "Namespace", ")", ":", "path", "=", "path", ".", "resolve", "(", ")", "source", "=", "path", ".", "read_text", "(", "encoding", "=", "\"utf-8\"", ")", "match", "=", "re", ".", "match", "(", "pattern", "=", "r\"(/\\*.*?Copyright ©.*?\\*/\\n?)?\\n*(.*)\",", "", "string", "=", "source", ",", "flags", "=", "re", ".", "DOTALL", "|", "re", ".", "MULTILINE", ",", ")", "assert", "match", "old_copyright", ",", "source", "=", "match", ".", "groups", "(", ")", "if", "old_copyright", "==", "copyright", ":", "if", "args", ".", "verbose", ":", "print", "(", "f\"Banner is up-to-date {path}\"", ")", "return", "elif", "old_copyright", "is", "None", ":", "print", "(", "f\"Adding missing banner to {path}\"", ")", "else", ":", "print", "(", "f\"Updating banner for {path}\"", ")", "if", "not", "args", ".", "dry_run", ":", "path", ".", "write_text", "(", "copyright", "+", "source", ",", "encoding", "=", "\"utf-8\"", ")" ]
https://github.com/libtcod/libtcod/blob/613b5c20dc3d222600c202bee39707500aee2a25/scripts/update_copyrights.py#L39-L64
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
third_party/jinja2/filters.py
python
do_round
(value, precision=0, method='common')
return func(value * (10 ** precision)) / (10 ** precision)
Round the number to a given precision. The first parameter specifies the precision (default is ``0``), the second the rounding method: - ``'common'`` rounds either up or down - ``'ceil'`` always rounds up - ``'floor'`` always rounds down If you don't specify a method ``'common'`` is used. .. sourcecode:: jinja {{ 42.55|round }} -> 43.0 {{ 42.55|round(1, 'floor') }} -> 42.5 Note that even if rounded to 0 precision, a float is returned. If you need a real integer, pipe it through `int`: .. sourcecode:: jinja {{ 42.55|round|int }} -> 43
Round the number to a given precision. The first parameter specifies the precision (default is ``0``), the second the rounding method:
[ "Round", "the", "number", "to", "a", "given", "precision", ".", "The", "first", "parameter", "specifies", "the", "precision", "(", "default", "is", "0", ")", "the", "second", "the", "rounding", "method", ":" ]
def do_round(value, precision=0, method='common'): """Round the number to a given precision. The first parameter specifies the precision (default is ``0``), the second the rounding method: - ``'common'`` rounds either up or down - ``'ceil'`` always rounds up - ``'floor'`` always rounds down If you don't specify a method ``'common'`` is used. .. sourcecode:: jinja {{ 42.55|round }} -> 43.0 {{ 42.55|round(1, 'floor') }} -> 42.5 Note that even if rounded to 0 precision, a float is returned. If you need a real integer, pipe it through `int`: .. sourcecode:: jinja {{ 42.55|round|int }} -> 43 """ if not method in ('common', 'ceil', 'floor'): raise FilterArgumentError('method must be common, ceil or floor') if method == 'common': return round(value, precision) func = getattr(math, method) return func(value * (10 ** precision)) / (10 ** precision)
[ "def", "do_round", "(", "value", ",", "precision", "=", "0", ",", "method", "=", "'common'", ")", ":", "if", "not", "method", "in", "(", "'common'", ",", "'ceil'", ",", "'floor'", ")", ":", "raise", "FilterArgumentError", "(", "'method must be common, ceil or floor'", ")", "if", "method", "==", "'common'", ":", "return", "round", "(", "value", ",", "precision", ")", "func", "=", "getattr", "(", "math", ",", "method", ")", "return", "func", "(", "value", "*", "(", "10", "**", "precision", ")", ")", "/", "(", "10", "**", "precision", ")" ]
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/third_party/jinja2/filters.py#L628-L659
falkTX/Carla
74a1ae82c90db85f20550ddcdc8a927b8fb7e414
source/modules/lilv/lilv-0.24.0/bindings/python/lilv.py
python
Plugin.get_optional_features
(self)
return Nodes(plugin_get_optional_features(self.plugin))
Get the LV2 Features optionally supported by a plugin. Hosts MAY ignore optional plugin features for whatever reasons. Plugins MUST operate (at least somewhat) if they are instantiated without being passed optional features.
Get the LV2 Features optionally supported by a plugin.
[ "Get", "the", "LV2", "Features", "optionally", "supported", "by", "a", "plugin", "." ]
def get_optional_features(self): """Get the LV2 Features optionally supported by a plugin. Hosts MAY ignore optional plugin features for whatever reasons. Plugins MUST operate (at least somewhat) if they are instantiated without being passed optional features. """ return Nodes(plugin_get_optional_features(self.plugin))
[ "def", "get_optional_features", "(", "self", ")", ":", "return", "Nodes", "(", "plugin_get_optional_features", "(", "self", ".", "plugin", ")", ")" ]
https://github.com/falkTX/Carla/blob/74a1ae82c90db85f20550ddcdc8a927b8fb7e414/source/modules/lilv/lilv-0.24.0/bindings/python/lilv.py#L364-L371
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/idlelib/configdialog.py
python
HighPage.create_new
(self, new_theme_name)
Create a new custom theme with the given name. Create the new theme based on the previously active theme with the current changes applied. Once it is saved, then activate the new theme. Attributes accessed: builtin_name custom_name Attributes updated: customlist theme_source Method: save_new set_theme_type
Create a new custom theme with the given name.
[ "Create", "a", "new", "custom", "theme", "with", "the", "given", "name", "." ]
def create_new(self, new_theme_name): """Create a new custom theme with the given name. Create the new theme based on the previously active theme with the current changes applied. Once it is saved, then activate the new theme. Attributes accessed: builtin_name custom_name Attributes updated: customlist theme_source Method: save_new set_theme_type """ if self.theme_source.get(): theme_type = 'default' theme_name = self.builtin_name.get() else: theme_type = 'user' theme_name = self.custom_name.get() new_theme = idleConf.GetThemeDict(theme_type, theme_name) # Apply any of the old theme's unsaved changes to the new theme. if theme_name in changes['highlight']: theme_changes = changes['highlight'][theme_name] for element in theme_changes: new_theme[element] = theme_changes[element] # Save the new theme. self.save_new(new_theme_name, new_theme) # Change GUI over to the new theme. custom_theme_list = idleConf.GetSectionList('user', 'highlight') custom_theme_list.sort() self.customlist.SetMenu(custom_theme_list, new_theme_name) self.theme_source.set(0) self.set_theme_type()
[ "def", "create_new", "(", "self", ",", "new_theme_name", ")", ":", "if", "self", ".", "theme_source", ".", "get", "(", ")", ":", "theme_type", "=", "'default'", "theme_name", "=", "self", ".", "builtin_name", ".", "get", "(", ")", "else", ":", "theme_type", "=", "'user'", "theme_name", "=", "self", ".", "custom_name", ".", "get", "(", ")", "new_theme", "=", "idleConf", ".", "GetThemeDict", "(", "theme_type", ",", "theme_name", ")", "# Apply any of the old theme's unsaved changes to the new theme.", "if", "theme_name", "in", "changes", "[", "'highlight'", "]", ":", "theme_changes", "=", "changes", "[", "'highlight'", "]", "[", "theme_name", "]", "for", "element", "in", "theme_changes", ":", "new_theme", "[", "element", "]", "=", "theme_changes", "[", "element", "]", "# Save the new theme.", "self", ".", "save_new", "(", "new_theme_name", ",", "new_theme", ")", "# Change GUI over to the new theme.", "custom_theme_list", "=", "idleConf", ".", "GetSectionList", "(", "'user'", ",", "'highlight'", ")", "custom_theme_list", ".", "sort", "(", ")", "self", ".", "customlist", ".", "SetMenu", "(", "custom_theme_list", ",", "new_theme_name", ")", "self", ".", "theme_source", ".", "set", "(", "0", ")", "self", ".", "set_theme_type", "(", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/idlelib/configdialog.py#L1148-L1186
intel/llvm
e6d0547e9d99b5a56430c4749f6c7e328bf221ab
lldb/examples/python/bsd.py
python
Archive.get_object_dicts
(self)
return object_dicts
Returns an array of object dictionaries that contain they following keys: 'object': the actual bsd.Object instance 'symdefs': an array of symbol names that the object contains as found in the "__.SYMDEF" item in the archive
Returns an array of object dictionaries that contain they following keys: 'object': the actual bsd.Object instance 'symdefs': an array of symbol names that the object contains as found in the "__.SYMDEF" item in the archive
[ "Returns", "an", "array", "of", "object", "dictionaries", "that", "contain", "they", "following", "keys", ":", "object", ":", "the", "actual", "bsd", ".", "Object", "instance", "symdefs", ":", "an", "array", "of", "symbol", "names", "that", "the", "object", "contains", "as", "found", "in", "the", "__", ".", "SYMDEF", "item", "in", "the", "archive" ]
def get_object_dicts(self): ''' Returns an array of object dictionaries that contain they following keys: 'object': the actual bsd.Object instance 'symdefs': an array of symbol names that the object contains as found in the "__.SYMDEF" item in the archive ''' symdefs = self.get_symdef() symdef_dict = {} if symdefs: for (name, offset) in symdefs: if offset in symdef_dict: object_dict = symdef_dict[offset] else: object_dict = { 'object': self.get_object_at_offset(offset), 'symdefs': [] } symdef_dict[offset] = object_dict object_dict['symdefs'].append(name) object_dicts = [] for offset in sorted(symdef_dict): object_dicts.append(symdef_dict[offset]) return object_dicts
[ "def", "get_object_dicts", "(", "self", ")", ":", "symdefs", "=", "self", ".", "get_symdef", "(", ")", "symdef_dict", "=", "{", "}", "if", "symdefs", ":", "for", "(", "name", ",", "offset", ")", "in", "symdefs", ":", "if", "offset", "in", "symdef_dict", ":", "object_dict", "=", "symdef_dict", "[", "offset", "]", "else", ":", "object_dict", "=", "{", "'object'", ":", "self", ".", "get_object_at_offset", "(", "offset", ")", ",", "'symdefs'", ":", "[", "]", "}", "symdef_dict", "[", "offset", "]", "=", "object_dict", "object_dict", "[", "'symdefs'", "]", ".", "append", "(", "name", ")", "object_dicts", "=", "[", "]", "for", "offset", "in", "sorted", "(", "symdef_dict", ")", ":", "object_dicts", ".", "append", "(", "symdef_dict", "[", "offset", "]", ")", "return", "object_dicts" ]
https://github.com/intel/llvm/blob/e6d0547e9d99b5a56430c4749f6c7e328bf221ab/lldb/examples/python/bsd.py#L174-L198
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/cuda/api.py
python
is_cuda_array
(obj)
return hasattr(obj, '__cuda_array_interface__')
Test if the object has defined the `__cuda_array_interface__` attribute. Does not verify the validity of the interface.
Test if the object has defined the `__cuda_array_interface__` attribute.
[ "Test", "if", "the", "object", "has", "defined", "the", "__cuda_array_interface__", "attribute", "." ]
def is_cuda_array(obj): """Test if the object has defined the `__cuda_array_interface__` attribute. Does not verify the validity of the interface. """ return hasattr(obj, '__cuda_array_interface__')
[ "def", "is_cuda_array", "(", "obj", ")", ":", "return", "hasattr", "(", "obj", ",", "'__cuda_array_interface__'", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/cuda/api.py#L71-L76
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_core.py
python
MenuItem.SetId
(*args, **kwargs)
return _core_.MenuItem_SetId(*args, **kwargs)
SetId(self, int id)
SetId(self, int id)
[ "SetId", "(", "self", "int", "id", ")" ]
def SetId(*args, **kwargs): """SetId(self, int id)""" return _core_.MenuItem_SetId(*args, **kwargs)
[ "def", "SetId", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "MenuItem_SetId", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_core.py#L12451-L12453
francinexue/xuefu
b6ff79747a42e020588c0c0a921048e08fe4680c
cnx/tickds.py
python
TickDataSeries.getVolumeDataSeries
(self)
return self.__volumeDS
Returns a :class:`pyalgotrade.dataseries.DataSeries` with the volume.
Returns a :class:`pyalgotrade.dataseries.DataSeries` with the volume.
[ "Returns", "a", ":", "class", ":", "pyalgotrade", ".", "dataseries", ".", "DataSeries", "with", "the", "volume", "." ]
def getVolumeDataSeries(self): """Returns a :class:`pyalgotrade.dataseries.DataSeries` with the volume.""" return self.__volumeDS
[ "def", "getVolumeDataSeries", "(", "self", ")", ":", "return", "self", ".", "__volumeDS" ]
https://github.com/francinexue/xuefu/blob/b6ff79747a42e020588c0c0a921048e08fe4680c/cnx/tickds.py#L149-L151
deepmodeling/deepmd-kit
159e45d248b0429844fb6a8cb3b3a201987c8d79
deepmd/fit/polar.py
python
PolarFittingSeA.__init__
(self, descrpt : tf.Tensor, neuron : List[int] = [120,120,120], resnet_dt : bool = True, sel_type : List[int] = None, fit_diag : bool = True, scale : List[float] = None, shift_diag : bool = True, # YWolfeee: will support the user to decide whether to use this function #diag_shift : List[float] = None, YWolfeee: will not support the user to assign a shift seed : int = None, activation_function : str = 'tanh', precision : str = 'default', uniform_seed: bool = False )
Constructor Parameters ---------- descrpt : tf.Tensor The descrptor neuron : List[int] Number of neurons in each hidden layer of the fitting net resnet_dt : bool Time-step `dt` in the resnet construction: y = x + dt * \phi (Wx + b) sel_type : List[int] The atom types selected to have an atomic polarizability prediction. If is None, all atoms are selected. fit_diag : bool Fit the diagonal part of the rotational invariant polarizability matrix, which will be converted to normal polarizability matrix by contracting with the rotation matrix. scale : List[float] The output of the fitting net (polarizability matrix) for type i atom will be scaled by scale[i] diag_shift : List[float] The diagonal part of the polarizability matrix of type i will be shifted by diag_shift[i]. The shift operation is carried out after scale. seed : int Random seed for initializing the network parameters. activation_function : str The activation function in the embedding net. Supported options are {0} precision : str The precision of the embedding net parameters. Supported options are {1} uniform_seed Only for the purpose of backward compatibility, retrieves the old behavior of using the random seed
Constructor
[ "Constructor" ]
def __init__ (self, descrpt : tf.Tensor, neuron : List[int] = [120,120,120], resnet_dt : bool = True, sel_type : List[int] = None, fit_diag : bool = True, scale : List[float] = None, shift_diag : bool = True, # YWolfeee: will support the user to decide whether to use this function #diag_shift : List[float] = None, YWolfeee: will not support the user to assign a shift seed : int = None, activation_function : str = 'tanh', precision : str = 'default', uniform_seed: bool = False ) -> None: """ Constructor Parameters ---------- descrpt : tf.Tensor The descrptor neuron : List[int] Number of neurons in each hidden layer of the fitting net resnet_dt : bool Time-step `dt` in the resnet construction: y = x + dt * \phi (Wx + b) sel_type : List[int] The atom types selected to have an atomic polarizability prediction. If is None, all atoms are selected. fit_diag : bool Fit the diagonal part of the rotational invariant polarizability matrix, which will be converted to normal polarizability matrix by contracting with the rotation matrix. scale : List[float] The output of the fitting net (polarizability matrix) for type i atom will be scaled by scale[i] diag_shift : List[float] The diagonal part of the polarizability matrix of type i will be shifted by diag_shift[i]. The shift operation is carried out after scale. seed : int Random seed for initializing the network parameters. activation_function : str The activation function in the embedding net. Supported options are {0} precision : str The precision of the embedding net parameters. Supported options are {1} uniform_seed Only for the purpose of backward compatibility, retrieves the old behavior of using the random seed """ if not isinstance(descrpt, DescrptSeA) : raise RuntimeError('PolarFittingSeA only supports DescrptSeA') self.ntypes = descrpt.get_ntypes() self.dim_descrpt = descrpt.get_dim_out() # args = ClassArg()\ # .add('neuron', list, default = [120,120,120], alias = 'n_neuron')\ # .add('resnet_dt', bool, default = True)\ # .add('fit_diag', bool, default = True)\ # .add('diag_shift', [list,float], default = [0.0 for ii in range(self.ntypes)])\ # .add('scale', [list,float], default = [1.0 for ii in range(self.ntypes)])\ # .add('sel_type', [list,int], default = [ii for ii in range(self.ntypes)], alias = 'pol_type')\ # .add('seed', int)\ # .add("activation_function", str , default = "tanh")\ # .add('precision', str, default = "default") # class_data = args.parse(jdata) self.n_neuron = neuron self.resnet_dt = resnet_dt self.sel_type = sel_type self.fit_diag = fit_diag self.seed = seed self.uniform_seed = uniform_seed self.seed_shift = one_layer_rand_seed_shift() #self.diag_shift = diag_shift self.shift_diag = shift_diag self.scale = scale self.fitting_activation_fn = get_activation_func(activation_function) self.fitting_precision = get_precision(precision) if self.sel_type is None: self.sel_type = [ii for ii in range(self.ntypes)] if self.scale is None: self.scale = [1.0 for ii in range(self.ntypes)] #if self.diag_shift is None: # self.diag_shift = [0.0 for ii in range(self.ntypes)] if type(self.sel_type) is not list: self.sel_type = [self.sel_type] self.constant_matrix = np.zeros(len(self.sel_type)) # len(sel_type) x 1, store the average diagonal value #if type(self.diag_shift) is not list: # self.diag_shift = [self.diag_shift] if type(self.scale) is not list: self.scale = [self.scale] self.dim_rot_mat_1 = descrpt.get_dim_rot_mat_1() self.dim_rot_mat = self.dim_rot_mat_1 * 3 self.useBN = False
[ "def", "__init__", "(", "self", ",", "descrpt", ":", "tf", ".", "Tensor", ",", "neuron", ":", "List", "[", "int", "]", "=", "[", "120", ",", "120", ",", "120", "]", ",", "resnet_dt", ":", "bool", "=", "True", ",", "sel_type", ":", "List", "[", "int", "]", "=", "None", ",", "fit_diag", ":", "bool", "=", "True", ",", "scale", ":", "List", "[", "float", "]", "=", "None", ",", "shift_diag", ":", "bool", "=", "True", ",", "# YWolfeee: will support the user to decide whether to use this function", "#diag_shift : List[float] = None, YWolfeee: will not support the user to assign a shift", "seed", ":", "int", "=", "None", ",", "activation_function", ":", "str", "=", "'tanh'", ",", "precision", ":", "str", "=", "'default'", ",", "uniform_seed", ":", "bool", "=", "False", ")", "->", "None", ":", "if", "not", "isinstance", "(", "descrpt", ",", "DescrptSeA", ")", ":", "raise", "RuntimeError", "(", "'PolarFittingSeA only supports DescrptSeA'", ")", "self", ".", "ntypes", "=", "descrpt", ".", "get_ntypes", "(", ")", "self", ".", "dim_descrpt", "=", "descrpt", ".", "get_dim_out", "(", ")", "# args = ClassArg()\\", "# .add('neuron', list, default = [120,120,120], alias = 'n_neuron')\\", "# .add('resnet_dt', bool, default = True)\\", "# .add('fit_diag', bool, default = True)\\", "# .add('diag_shift', [list,float], default = [0.0 for ii in range(self.ntypes)])\\", "# .add('scale', [list,float], default = [1.0 for ii in range(self.ntypes)])\\", "# .add('sel_type', [list,int], default = [ii for ii in range(self.ntypes)], alias = 'pol_type')\\", "# .add('seed', int)\\", "# .add(\"activation_function\", str , default = \"tanh\")\\", "# .add('precision', str, default = \"default\")", "# class_data = args.parse(jdata)", "self", ".", "n_neuron", "=", "neuron", "self", ".", "resnet_dt", "=", "resnet_dt", "self", ".", "sel_type", "=", "sel_type", "self", ".", "fit_diag", "=", "fit_diag", "self", ".", "seed", "=", "seed", "self", ".", "uniform_seed", "=", "uniform_seed", "self", ".", "seed_shift", "=", "one_layer_rand_seed_shift", "(", ")", "#self.diag_shift = diag_shift", "self", ".", "shift_diag", "=", "shift_diag", "self", ".", "scale", "=", "scale", "self", ".", "fitting_activation_fn", "=", "get_activation_func", "(", "activation_function", ")", "self", ".", "fitting_precision", "=", "get_precision", "(", "precision", ")", "if", "self", ".", "sel_type", "is", "None", ":", "self", ".", "sel_type", "=", "[", "ii", "for", "ii", "in", "range", "(", "self", ".", "ntypes", ")", "]", "if", "self", ".", "scale", "is", "None", ":", "self", ".", "scale", "=", "[", "1.0", "for", "ii", "in", "range", "(", "self", ".", "ntypes", ")", "]", "#if self.diag_shift is None:", "# self.diag_shift = [0.0 for ii in range(self.ntypes)]", "if", "type", "(", "self", ".", "sel_type", ")", "is", "not", "list", ":", "self", ".", "sel_type", "=", "[", "self", ".", "sel_type", "]", "self", ".", "constant_matrix", "=", "np", ".", "zeros", "(", "len", "(", "self", ".", "sel_type", ")", ")", "# len(sel_type) x 1, store the average diagonal value", "#if type(self.diag_shift) is not list:", "# self.diag_shift = [self.diag_shift]", "if", "type", "(", "self", ".", "scale", ")", "is", "not", "list", ":", "self", ".", "scale", "=", "[", "self", ".", "scale", "]", "self", ".", "dim_rot_mat_1", "=", "descrpt", ".", "get_dim_rot_mat_1", "(", ")", "self", ".", "dim_rot_mat", "=", "self", ".", "dim_rot_mat_1", "*", "3", "self", ".", "useBN", "=", "False" ]
https://github.com/deepmodeling/deepmd-kit/blob/159e45d248b0429844fb6a8cb3b3a201987c8d79/deepmd/fit/polar.py#L109-L194
dscharrer/innoextract
5519d364cc8898f906f6285d81a87ab8c5469cde
cmake/cpplint.py
python
_CppLintState.SetVerboseLevel
(self, level)
return last_verbose_level
Sets the module's verbosity, and returns the previous setting.
Sets the module's verbosity, and returns the previous setting.
[ "Sets", "the", "module", "s", "verbosity", "and", "returns", "the", "previous", "setting", "." ]
def SetVerboseLevel(self, level): """Sets the module's verbosity, and returns the previous setting.""" last_verbose_level = self.verbose_level self.verbose_level = level return last_verbose_level
[ "def", "SetVerboseLevel", "(", "self", ",", "level", ")", ":", "last_verbose_level", "=", "self", ".", "verbose_level", "self", ".", "verbose_level", "=", "level", "return", "last_verbose_level" ]
https://github.com/dscharrer/innoextract/blob/5519d364cc8898f906f6285d81a87ab8c5469cde/cmake/cpplint.py#L556-L560
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/python/ops/linalg/linalg_impl.py
python
logdet
(matrix, name=None)
Computes log of the determinant of a hermitian positive definite matrix. ```python # Compute the determinant of a matrix while reducing the chance of over- or underflow: A = ... # shape 10 x 10 det = tf.exp(tf.logdet(A)) # scalar ``` Args: matrix: A `Tensor`. Must be `float32`, `float64`, `complex64`, or `complex128` with shape `[..., M, M]`. name: A name to give this `Op`. Defaults to `logdet`. Returns: The natural log of the determinant of `matrix`. @compatibility(numpy) Equivalent to numpy.linalg.slogdet, although no sign is returned since only hermitian positive definite matrices are supported. @end_compatibility
Computes log of the determinant of a hermitian positive definite matrix.
[ "Computes", "log", "of", "the", "determinant", "of", "a", "hermitian", "positive", "definite", "matrix", "." ]
def logdet(matrix, name=None): """Computes log of the determinant of a hermitian positive definite matrix. ```python # Compute the determinant of a matrix while reducing the chance of over- or underflow: A = ... # shape 10 x 10 det = tf.exp(tf.logdet(A)) # scalar ``` Args: matrix: A `Tensor`. Must be `float32`, `float64`, `complex64`, or `complex128` with shape `[..., M, M]`. name: A name to give this `Op`. Defaults to `logdet`. Returns: The natural log of the determinant of `matrix`. @compatibility(numpy) Equivalent to numpy.linalg.slogdet, although no sign is returned since only hermitian positive definite matrices are supported. @end_compatibility """ # This uses the property that the log det(A) = 2*sum(log(real(diag(C)))) # where C is the cholesky decomposition of A. with ops.name_scope(name, 'logdet', [matrix]): chol = gen_linalg_ops.cholesky(matrix) return 2.0 * math_ops.reduce_sum( math_ops.log(math_ops.real(array_ops.matrix_diag_part(chol))), reduction_indices=[-1])
[ "def", "logdet", "(", "matrix", ",", "name", "=", "None", ")", ":", "# This uses the property that the log det(A) = 2*sum(log(real(diag(C))))", "# where C is the cholesky decomposition of A.", "with", "ops", ".", "name_scope", "(", "name", ",", "'logdet'", ",", "[", "matrix", "]", ")", ":", "chol", "=", "gen_linalg_ops", ".", "cholesky", "(", "matrix", ")", "return", "2.0", "*", "math_ops", ".", "reduce_sum", "(", "math_ops", ".", "log", "(", "math_ops", ".", "real", "(", "array_ops", ".", "matrix_diag_part", "(", "chol", ")", ")", ")", ",", "reduction_indices", "=", "[", "-", "1", "]", ")" ]
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/ops/linalg/linalg_impl.py#L27-L56
adobe/chromium
cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7
third_party/protobuf/python/mox.py
python
ExpectedMethodCallsError.__init__
(self, expected_methods)
Init exception. Args: # expected_methods: A sequence of MockMethod objects that should have been # called. expected_methods: [MockMethod] Raises: ValueError: if expected_methods contains no methods.
Init exception.
[ "Init", "exception", "." ]
def __init__(self, expected_methods): """Init exception. Args: # expected_methods: A sequence of MockMethod objects that should have been # called. expected_methods: [MockMethod] Raises: ValueError: if expected_methods contains no methods. """ if not expected_methods: raise ValueError("There must be at least one expected method") Error.__init__(self) self._expected_methods = expected_methods
[ "def", "__init__", "(", "self", ",", "expected_methods", ")", ":", "if", "not", "expected_methods", ":", "raise", "ValueError", "(", "\"There must be at least one expected method\"", ")", "Error", ".", "__init__", "(", "self", ")", "self", ".", "_expected_methods", "=", "expected_methods" ]
https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/third_party/protobuf/python/mox.py#L79-L94
mongodb/mongo
d8ff665343ad29cf286ee2cf4a1960d29371937b
buildscripts/resmokelib/run/__init__.py
python
to_local_args
(input_args=None)
return ["run"] + [arg for arg in (suites_arg, storage_engine_arg) if arg is not None ] + other_local_args + positional_args
Return a command line invocation for resmoke.py suitable for being run outside of Evergreen. This function parses the 'args' list of command line arguments, removes any Evergreen-centric options, and returns a new list of command line arguments.
Return a command line invocation for resmoke.py suitable for being run outside of Evergreen.
[ "Return", "a", "command", "line", "invocation", "for", "resmoke", ".", "py", "suitable", "for", "being", "run", "outside", "of", "Evergreen", "." ]
def to_local_args(input_args=None): # pylint: disable=too-many-branches,too-many-locals """ Return a command line invocation for resmoke.py suitable for being run outside of Evergreen. This function parses the 'args' list of command line arguments, removes any Evergreen-centric options, and returns a new list of command line arguments. """ if input_args is None: input_args = sys.argv[1:] if input_args[0] != 'run': raise TypeError( f"to_local_args can only be called for the 'run' subcommand. Instead was called on '{input_args[0]}'" ) (parser, parsed_args) = main_parser.parse(input_args) # If --originSuite was specified, then we replace the value of --suites with it. This is done to # avoid needing to have engineers learn about the test suites generated by the # evergreen_generate_resmoke_tasks.py script. origin_suite = getattr(parsed_args, "origin_suite", None) if origin_suite is not None: setattr(parsed_args, "suite_files", origin_suite) # Replace --runAllFeatureFlagTests with an explicit list of feature flags. The former relies on # all_feature_flags.txt which may not exist in the local dev environment. run_all_feature_flag_tests = getattr(parsed_args, "run_all_feature_flag_tests", None) if run_all_feature_flag_tests is not None: setattr(parsed_args, "additional_feature_flags", config.ENABLED_FEATURE_FLAGS) del parsed_args.run_all_feature_flag_tests del parsed_args.run_all_feature_flags_no_tests # The top-level parser has one subparser that contains all subcommand parsers. command_subparser = [ action for action in parser._actions # pylint: disable=protected-access if action.dest == "command" ][0] run_parser = command_subparser.choices.get("run") suites_arg = None storage_engine_arg = None other_local_args = [] positional_args = [] def format_option(option_name, option_value): """ Return <option_name>=<option_value>. This function assumes that 'option_name' is always "--" prefix and isn't "-" prefixed. """ return f"{option_name}={option_value}" # Trim the argument namespace of any args we don't want to return. for group in run_parser._action_groups: # pylint: disable=protected-access arg_dests_visited = set() for action in group._group_actions: # pylint: disable=protected-access arg_dest = action.dest arg_value = getattr(parsed_args, arg_dest, None) # Some arguments, such as --shuffle and --shuffleMode, update the same dest variable. # To not print out multiple arguments that will update the same dest, we will skip once # one such argument has been visited. if arg_dest in arg_dests_visited: continue else: arg_dests_visited.add(arg_dest) # If the arg doesn't exist in the parsed namespace, skip. # This is mainly for "--help". if not hasattr(parsed_args, arg_dest): continue # Skip any evergreen centric args. elif group.title in [ _INTERNAL_OPTIONS_TITLE, _EVERGREEN_ARGUMENT_TITLE, _CEDAR_ARGUMENT_TITLE ]: continue elif group.title == 'positional arguments': positional_args.extend(arg_value) # Keep all remaining args. else: arg_name = action.option_strings[-1] # If an option has the same value as the default, we don't need to specify it. if getattr(parsed_args, arg_dest, None) == action.default: continue # These are arguments that take no value. elif action.nargs == 0: other_local_args.append(arg_name) elif isinstance(action, argparse._AppendAction): # pylint: disable=protected-access args = [format_option(arg_name, elem) for elem in arg_value] other_local_args.extend(args) else: arg = format_option(arg_name, arg_value) # We track the value for the --suites and --storageEngine command line options # separately in order to more easily sort them to the front. if arg_dest == "suite_files": suites_arg = arg elif arg_dest == "storage_engine": storage_engine_arg = arg else: other_local_args.append(arg) return ["run"] + [arg for arg in (suites_arg, storage_engine_arg) if arg is not None ] + other_local_args + positional_args
[ "def", "to_local_args", "(", "input_args", "=", "None", ")", ":", "# pylint: disable=too-many-branches,too-many-locals", "if", "input_args", "is", "None", ":", "input_args", "=", "sys", ".", "argv", "[", "1", ":", "]", "if", "input_args", "[", "0", "]", "!=", "'run'", ":", "raise", "TypeError", "(", "f\"to_local_args can only be called for the 'run' subcommand. Instead was called on '{input_args[0]}'\"", ")", "(", "parser", ",", "parsed_args", ")", "=", "main_parser", ".", "parse", "(", "input_args", ")", "# If --originSuite was specified, then we replace the value of --suites with it. This is done to", "# avoid needing to have engineers learn about the test suites generated by the", "# evergreen_generate_resmoke_tasks.py script.", "origin_suite", "=", "getattr", "(", "parsed_args", ",", "\"origin_suite\"", ",", "None", ")", "if", "origin_suite", "is", "not", "None", ":", "setattr", "(", "parsed_args", ",", "\"suite_files\"", ",", "origin_suite", ")", "# Replace --runAllFeatureFlagTests with an explicit list of feature flags. The former relies on", "# all_feature_flags.txt which may not exist in the local dev environment.", "run_all_feature_flag_tests", "=", "getattr", "(", "parsed_args", ",", "\"run_all_feature_flag_tests\"", ",", "None", ")", "if", "run_all_feature_flag_tests", "is", "not", "None", ":", "setattr", "(", "parsed_args", ",", "\"additional_feature_flags\"", ",", "config", ".", "ENABLED_FEATURE_FLAGS", ")", "del", "parsed_args", ".", "run_all_feature_flag_tests", "del", "parsed_args", ".", "run_all_feature_flags_no_tests", "# The top-level parser has one subparser that contains all subcommand parsers.", "command_subparser", "=", "[", "action", "for", "action", "in", "parser", ".", "_actions", "# pylint: disable=protected-access", "if", "action", ".", "dest", "==", "\"command\"", "]", "[", "0", "]", "run_parser", "=", "command_subparser", ".", "choices", ".", "get", "(", "\"run\"", ")", "suites_arg", "=", "None", "storage_engine_arg", "=", "None", "other_local_args", "=", "[", "]", "positional_args", "=", "[", "]", "def", "format_option", "(", "option_name", ",", "option_value", ")", ":", "\"\"\"\n Return <option_name>=<option_value>.\n\n This function assumes that 'option_name' is always \"--\" prefix and isn't \"-\" prefixed.\n \"\"\"", "return", "f\"{option_name}={option_value}\"", "# Trim the argument namespace of any args we don't want to return.", "for", "group", "in", "run_parser", ".", "_action_groups", ":", "# pylint: disable=protected-access", "arg_dests_visited", "=", "set", "(", ")", "for", "action", "in", "group", ".", "_group_actions", ":", "# pylint: disable=protected-access", "arg_dest", "=", "action", ".", "dest", "arg_value", "=", "getattr", "(", "parsed_args", ",", "arg_dest", ",", "None", ")", "# Some arguments, such as --shuffle and --shuffleMode, update the same dest variable.", "# To not print out multiple arguments that will update the same dest, we will skip once", "# one such argument has been visited.", "if", "arg_dest", "in", "arg_dests_visited", ":", "continue", "else", ":", "arg_dests_visited", ".", "add", "(", "arg_dest", ")", "# If the arg doesn't exist in the parsed namespace, skip.", "# This is mainly for \"--help\".", "if", "not", "hasattr", "(", "parsed_args", ",", "arg_dest", ")", ":", "continue", "# Skip any evergreen centric args.", "elif", "group", ".", "title", "in", "[", "_INTERNAL_OPTIONS_TITLE", ",", "_EVERGREEN_ARGUMENT_TITLE", ",", "_CEDAR_ARGUMENT_TITLE", "]", ":", "continue", "elif", "group", ".", "title", "==", "'positional arguments'", ":", "positional_args", ".", "extend", "(", "arg_value", ")", "# Keep all remaining args.", "else", ":", "arg_name", "=", "action", ".", "option_strings", "[", "-", "1", "]", "# If an option has the same value as the default, we don't need to specify it.", "if", "getattr", "(", "parsed_args", ",", "arg_dest", ",", "None", ")", "==", "action", ".", "default", ":", "continue", "# These are arguments that take no value.", "elif", "action", ".", "nargs", "==", "0", ":", "other_local_args", ".", "append", "(", "arg_name", ")", "elif", "isinstance", "(", "action", ",", "argparse", ".", "_AppendAction", ")", ":", "# pylint: disable=protected-access", "args", "=", "[", "format_option", "(", "arg_name", ",", "elem", ")", "for", "elem", "in", "arg_value", "]", "other_local_args", ".", "extend", "(", "args", ")", "else", ":", "arg", "=", "format_option", "(", "arg_name", ",", "arg_value", ")", "# We track the value for the --suites and --storageEngine command line options", "# separately in order to more easily sort them to the front.", "if", "arg_dest", "==", "\"suite_files\"", ":", "suites_arg", "=", "arg", "elif", "arg_dest", "==", "\"storage_engine\"", ":", "storage_engine_arg", "=", "arg", "else", ":", "other_local_args", ".", "append", "(", "arg", ")", "return", "[", "\"run\"", "]", "+", "[", "arg", "for", "arg", "in", "(", "suites_arg", ",", "storage_engine_arg", ")", "if", "arg", "is", "not", "None", "]", "+", "other_local_args", "+", "positional_args" ]
https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/buildscripts/resmokelib/run/__init__.py#L1188-L1295
mongodb/mongo
d8ff665343ad29cf286ee2cf4a1960d29371937b
src/third_party/wiredtiger/dist/stat.py
python
print_defines
()
Print the #defines for the wiredtiger.in file.
Print the #defines for the wiredtiger.in file.
[ "Print", "the", "#defines", "for", "the", "wiredtiger", ".", "in", "file", "." ]
def print_defines(): '''Print the #defines for the wiredtiger.in file.''' f.write(''' /*! * @name Connection statistics * @anchor statistics_keys * @anchor statistics_conn * Statistics are accessed through cursors with \c "statistics:" URIs. * Individual statistics can be queried through the cursor using the following * keys. See @ref data_statistics for more information. * @{ */ ''') print_defines_one('CONN', 1000, sorted_conn_stats) f.write(''' /*! * @} * @name Statistics for data sources * @anchor statistics_dsrc * @{ */ ''') print_defines_one('DSRC', 2000, sorted_dsrc_statistics) f.write(''' /*! * @} * @name Statistics for join cursors * @anchor statistics_join * @{ */ ''') print_defines_one('JOIN', 3000, join_stats) f.write(''' /*! * @} * @name Statistics for session * @anchor statistics_session * @{ */ ''') print_defines_one('SESSION', 4000, session_stats) f.write('/*! @} */\n')
[ "def", "print_defines", "(", ")", ":", "f", ".", "write", "(", "'''\n/*!\n * @name Connection statistics\n * @anchor statistics_keys\n * @anchor statistics_conn\n * Statistics are accessed through cursors with \\c \"statistics:\" URIs.\n * Individual statistics can be queried through the cursor using the following\n * keys. See @ref data_statistics for more information.\n * @{\n */\n'''", ")", "print_defines_one", "(", "'CONN'", ",", "1000", ",", "sorted_conn_stats", ")", "f", ".", "write", "(", "'''\n/*!\n * @}\n * @name Statistics for data sources\n * @anchor statistics_dsrc\n * @{\n */\n'''", ")", "print_defines_one", "(", "'DSRC'", ",", "2000", ",", "sorted_dsrc_statistics", ")", "f", ".", "write", "(", "'''\n/*!\n * @}\n * @name Statistics for join cursors\n * @anchor statistics_join\n * @{\n */\n'''", ")", "print_defines_one", "(", "'JOIN'", ",", "3000", ",", "join_stats", ")", "f", ".", "write", "(", "'''\n/*!\n * @}\n * @name Statistics for session\n * @anchor statistics_session\n * @{\n */\n'''", ")", "print_defines_one", "(", "'SESSION'", ",", "4000", ",", "session_stats", ")", "f", ".", "write", "(", "'/*! @} */\\n'", ")" ]
https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/src/third_party/wiredtiger/dist/stat.py#L72-L113
giuspen/cherrytree
84712f206478fcf9acf30174009ad28c648c6344
pygtk2/modules/exports.py
python
Export2Txt.get_single_txt_filepath
(self, proposed_name)
return ret_filepath
Prepare for the txt file save
Prepare for the txt file save
[ "Prepare", "for", "the", "txt", "file", "save" ]
def get_single_txt_filepath(self, proposed_name): """Prepare for the txt file save""" ret_filepath = support.dialog_file_save_as(proposed_name + ".txt", filter_pattern="*.txt", filter_name=_("Plain Text Document"), curr_folder=self.dad.pick_dir_export, parent=self.dad.window) if ret_filepath: if not ret_filepath.endswith(".txt"): ret_filepath += ".txt" self.dad.pick_dir_export = os.path.dirname(ret_filepath) return ret_filepath
[ "def", "get_single_txt_filepath", "(", "self", ",", "proposed_name", ")", ":", "ret_filepath", "=", "support", ".", "dialog_file_save_as", "(", "proposed_name", "+", "\".txt\"", ",", "filter_pattern", "=", "\"*.txt\"", ",", "filter_name", "=", "_", "(", "\"Plain Text Document\"", ")", ",", "curr_folder", "=", "self", ".", "dad", ".", "pick_dir_export", ",", "parent", "=", "self", ".", "dad", ".", "window", ")", "if", "ret_filepath", ":", "if", "not", "ret_filepath", ".", "endswith", "(", "\".txt\"", ")", ":", "ret_filepath", "+=", "\".txt\"", "self", ".", "dad", ".", "pick_dir_export", "=", "os", ".", "path", ".", "dirname", "(", "ret_filepath", ")", "return", "ret_filepath" ]
https://github.com/giuspen/cherrytree/blob/84712f206478fcf9acf30174009ad28c648c6344/pygtk2/modules/exports.py#L296-L306
natanielruiz/android-yolo
1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f
jni-build/jni/include/tensorflow/examples/image_retraining/retrain.py
python
get_or_create_bottleneck
(sess, image_lists, label_name, index, image_dir, category, bottleneck_dir, jpeg_data_tensor, bottleneck_tensor)
return bottleneck_values
Retrieves or calculates bottleneck values for an image. If a cached version of the bottleneck data exists on-disk, return that, otherwise calculate the data and save it to disk for future use. Args: sess: The current active TensorFlow Session. image_lists: Dictionary of training images for each label. label_name: Label string we want to get an image for. index: Integer offset of the image we want. This will be modulo-ed by the available number of images for the label, so it can be arbitrarily large. image_dir: Root folder string of the subfolders containing the training images. category: Name string of which set to pull images from - training, testing, or validation. bottleneck_dir: Folder string holding cached files of bottleneck values. jpeg_data_tensor: The tensor to feed loaded jpeg data into. bottleneck_tensor: The output tensor for the bottleneck values. Returns: Numpy array of values produced by the bottleneck layer for the image.
Retrieves or calculates bottleneck values for an image.
[ "Retrieves", "or", "calculates", "bottleneck", "values", "for", "an", "image", "." ]
def get_or_create_bottleneck(sess, image_lists, label_name, index, image_dir, category, bottleneck_dir, jpeg_data_tensor, bottleneck_tensor): """Retrieves or calculates bottleneck values for an image. If a cached version of the bottleneck data exists on-disk, return that, otherwise calculate the data and save it to disk for future use. Args: sess: The current active TensorFlow Session. image_lists: Dictionary of training images for each label. label_name: Label string we want to get an image for. index: Integer offset of the image we want. This will be modulo-ed by the available number of images for the label, so it can be arbitrarily large. image_dir: Root folder string of the subfolders containing the training images. category: Name string of which set to pull images from - training, testing, or validation. bottleneck_dir: Folder string holding cached files of bottleneck values. jpeg_data_tensor: The tensor to feed loaded jpeg data into. bottleneck_tensor: The output tensor for the bottleneck values. Returns: Numpy array of values produced by the bottleneck layer for the image. """ label_lists = image_lists[label_name] sub_dir = label_lists['dir'] sub_dir_path = os.path.join(bottleneck_dir, sub_dir) ensure_dir_exists(sub_dir_path) bottleneck_path = get_bottleneck_path(image_lists, label_name, index, bottleneck_dir, category) if not os.path.exists(bottleneck_path): print('Creating bottleneck at ' + bottleneck_path) image_path = get_image_path(image_lists, label_name, index, image_dir, category) if not gfile.Exists(image_path): tf.logging.fatal('File does not exist %s', image_path) image_data = gfile.FastGFile(image_path, 'rb').read() bottleneck_values = run_bottleneck_on_image(sess, image_data, jpeg_data_tensor, bottleneck_tensor) bottleneck_string = ','.join(str(x) for x in bottleneck_values) with open(bottleneck_path, 'w') as bottleneck_file: bottleneck_file.write(bottleneck_string) with open(bottleneck_path, 'r') as bottleneck_file: bottleneck_string = bottleneck_file.read() bottleneck_values = [float(x) for x in bottleneck_string.split(',')] return bottleneck_values
[ "def", "get_or_create_bottleneck", "(", "sess", ",", "image_lists", ",", "label_name", ",", "index", ",", "image_dir", ",", "category", ",", "bottleneck_dir", ",", "jpeg_data_tensor", ",", "bottleneck_tensor", ")", ":", "label_lists", "=", "image_lists", "[", "label_name", "]", "sub_dir", "=", "label_lists", "[", "'dir'", "]", "sub_dir_path", "=", "os", ".", "path", ".", "join", "(", "bottleneck_dir", ",", "sub_dir", ")", "ensure_dir_exists", "(", "sub_dir_path", ")", "bottleneck_path", "=", "get_bottleneck_path", "(", "image_lists", ",", "label_name", ",", "index", ",", "bottleneck_dir", ",", "category", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "bottleneck_path", ")", ":", "print", "(", "'Creating bottleneck at '", "+", "bottleneck_path", ")", "image_path", "=", "get_image_path", "(", "image_lists", ",", "label_name", ",", "index", ",", "image_dir", ",", "category", ")", "if", "not", "gfile", ".", "Exists", "(", "image_path", ")", ":", "tf", ".", "logging", ".", "fatal", "(", "'File does not exist %s'", ",", "image_path", ")", "image_data", "=", "gfile", ".", "FastGFile", "(", "image_path", ",", "'rb'", ")", ".", "read", "(", ")", "bottleneck_values", "=", "run_bottleneck_on_image", "(", "sess", ",", "image_data", ",", "jpeg_data_tensor", ",", "bottleneck_tensor", ")", "bottleneck_string", "=", "','", ".", "join", "(", "str", "(", "x", ")", "for", "x", "in", "bottleneck_values", ")", "with", "open", "(", "bottleneck_path", ",", "'w'", ")", "as", "bottleneck_file", ":", "bottleneck_file", ".", "write", "(", "bottleneck_string", ")", "with", "open", "(", "bottleneck_path", ",", "'r'", ")", "as", "bottleneck_file", ":", "bottleneck_string", "=", "bottleneck_file", ".", "read", "(", ")", "bottleneck_values", "=", "[", "float", "(", "x", ")", "for", "x", "in", "bottleneck_string", ".", "split", "(", "','", ")", "]", "return", "bottleneck_values" ]
https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/examples/image_retraining/retrain.py#L374-L422
google/syzygy
8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5
third_party/numpy/files/numpy/core/numerictypes.py
python
obj2sctype
(rep, default=None)
return res.type
Return the scalar dtype or NumPy equivalent of Python type of an object. Parameters ---------- rep : any The object of which the type is returned. default : any, optional If given, this is returned for objects whose types can not be determined. If not given, None is returned for those objects. Returns ------- dtype : dtype or Python type The data type of `rep`. See Also -------- sctype2char, issctype, issubsctype, issubdtype, maximum_sctype Examples -------- >>> np.obj2sctype(np.int32) <type 'numpy.int32'> >>> np.obj2sctype(np.array([1., 2.])) <type 'numpy.float64'> >>> np.obj2sctype(np.array([1.j])) <type 'numpy.complex128'> >>> np.obj2sctype(dict) <type 'numpy.object_'> >>> np.obj2sctype('string') <type 'numpy.string_'> >>> np.obj2sctype(1, default=list) <type 'list'>
Return the scalar dtype or NumPy equivalent of Python type of an object.
[ "Return", "the", "scalar", "dtype", "or", "NumPy", "equivalent", "of", "Python", "type", "of", "an", "object", "." ]
def obj2sctype(rep, default=None): """ Return the scalar dtype or NumPy equivalent of Python type of an object. Parameters ---------- rep : any The object of which the type is returned. default : any, optional If given, this is returned for objects whose types can not be determined. If not given, None is returned for those objects. Returns ------- dtype : dtype or Python type The data type of `rep`. See Also -------- sctype2char, issctype, issubsctype, issubdtype, maximum_sctype Examples -------- >>> np.obj2sctype(np.int32) <type 'numpy.int32'> >>> np.obj2sctype(np.array([1., 2.])) <type 'numpy.float64'> >>> np.obj2sctype(np.array([1.j])) <type 'numpy.complex128'> >>> np.obj2sctype(dict) <type 'numpy.object_'> >>> np.obj2sctype('string') <type 'numpy.string_'> >>> np.obj2sctype(1, default=list) <type 'list'> """ try: if issubclass(rep, generic): return rep except TypeError: pass if isinstance(rep, dtype): return rep.type if isinstance(rep, type): return _python_type(rep) if isinstance(rep, ndarray): return rep.dtype.type try: res = dtype(rep) except: return default return res.type
[ "def", "obj2sctype", "(", "rep", ",", "default", "=", "None", ")", ":", "try", ":", "if", "issubclass", "(", "rep", ",", "generic", ")", ":", "return", "rep", "except", "TypeError", ":", "pass", "if", "isinstance", "(", "rep", ",", "dtype", ")", ":", "return", "rep", ".", "type", "if", "isinstance", "(", "rep", ",", "type", ")", ":", "return", "_python_type", "(", "rep", ")", "if", "isinstance", "(", "rep", ",", "ndarray", ")", ":", "return", "rep", ".", "dtype", ".", "type", "try", ":", "res", "=", "dtype", "(", "rep", ")", "except", ":", "return", "default", "return", "res", ".", "type" ]
https://github.com/google/syzygy/blob/8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5/third_party/numpy/files/numpy/core/numerictypes.py#L608-L662
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/email/_header_value_parser.py
python
get_obs_local_part
(value)
return obs_local_part, value
obs-local-part = word *("." word)
obs-local-part = word *("." word)
[ "obs", "-", "local", "-", "part", "=", "word", "*", "(", ".", "word", ")" ]
def get_obs_local_part(value): """ obs-local-part = word *("." word) """ obs_local_part = ObsLocalPart() last_non_ws_was_dot = False while value and (value[0]=='\\' or value[0] not in PHRASE_ENDS): if value[0] == '.': if last_non_ws_was_dot: obs_local_part.defects.append(errors.InvalidHeaderDefect( "invalid repeated '.'")) obs_local_part.append(DOT) last_non_ws_was_dot = True value = value[1:] continue elif value[0]=='\\': obs_local_part.append(ValueTerminal(value[0], 'misplaced-special')) value = value[1:] obs_local_part.defects.append(errors.InvalidHeaderDefect( "'\\' character outside of quoted-string/ccontent")) last_non_ws_was_dot = False continue if obs_local_part and obs_local_part[-1].token_type != 'dot': obs_local_part.defects.append(errors.InvalidHeaderDefect( "missing '.' between words")) try: token, value = get_word(value) last_non_ws_was_dot = False except errors.HeaderParseError: if value[0] not in CFWS_LEADER: raise token, value = get_cfws(value) obs_local_part.append(token) if (obs_local_part[0].token_type == 'dot' or obs_local_part[0].token_type=='cfws' and obs_local_part[1].token_type=='dot'): obs_local_part.defects.append(errors.InvalidHeaderDefect( "Invalid leading '.' in local part")) if (obs_local_part[-1].token_type == 'dot' or obs_local_part[-1].token_type=='cfws' and obs_local_part[-2].token_type=='dot'): obs_local_part.defects.append(errors.InvalidHeaderDefect( "Invalid trailing '.' in local part")) if obs_local_part.defects: obs_local_part.token_type = 'invalid-obs-local-part' return obs_local_part, value
[ "def", "get_obs_local_part", "(", "value", ")", ":", "obs_local_part", "=", "ObsLocalPart", "(", ")", "last_non_ws_was_dot", "=", "False", "while", "value", "and", "(", "value", "[", "0", "]", "==", "'\\\\'", "or", "value", "[", "0", "]", "not", "in", "PHRASE_ENDS", ")", ":", "if", "value", "[", "0", "]", "==", "'.'", ":", "if", "last_non_ws_was_dot", ":", "obs_local_part", ".", "defects", ".", "append", "(", "errors", ".", "InvalidHeaderDefect", "(", "\"invalid repeated '.'\"", ")", ")", "obs_local_part", ".", "append", "(", "DOT", ")", "last_non_ws_was_dot", "=", "True", "value", "=", "value", "[", "1", ":", "]", "continue", "elif", "value", "[", "0", "]", "==", "'\\\\'", ":", "obs_local_part", ".", "append", "(", "ValueTerminal", "(", "value", "[", "0", "]", ",", "'misplaced-special'", ")", ")", "value", "=", "value", "[", "1", ":", "]", "obs_local_part", ".", "defects", ".", "append", "(", "errors", ".", "InvalidHeaderDefect", "(", "\"'\\\\' character outside of quoted-string/ccontent\"", ")", ")", "last_non_ws_was_dot", "=", "False", "continue", "if", "obs_local_part", "and", "obs_local_part", "[", "-", "1", "]", ".", "token_type", "!=", "'dot'", ":", "obs_local_part", ".", "defects", ".", "append", "(", "errors", ".", "InvalidHeaderDefect", "(", "\"missing '.' between words\"", ")", ")", "try", ":", "token", ",", "value", "=", "get_word", "(", "value", ")", "last_non_ws_was_dot", "=", "False", "except", "errors", ".", "HeaderParseError", ":", "if", "value", "[", "0", "]", "not", "in", "CFWS_LEADER", ":", "raise", "token", ",", "value", "=", "get_cfws", "(", "value", ")", "obs_local_part", ".", "append", "(", "token", ")", "if", "(", "obs_local_part", "[", "0", "]", ".", "token_type", "==", "'dot'", "or", "obs_local_part", "[", "0", "]", ".", "token_type", "==", "'cfws'", "and", "obs_local_part", "[", "1", "]", ".", "token_type", "==", "'dot'", ")", ":", "obs_local_part", ".", "defects", ".", "append", "(", "errors", ".", "InvalidHeaderDefect", "(", "\"Invalid leading '.' in local part\"", ")", ")", "if", "(", "obs_local_part", "[", "-", "1", "]", ".", "token_type", "==", "'dot'", "or", "obs_local_part", "[", "-", "1", "]", ".", "token_type", "==", "'cfws'", "and", "obs_local_part", "[", "-", "2", "]", ".", "token_type", "==", "'dot'", ")", ":", "obs_local_part", ".", "defects", ".", "append", "(", "errors", ".", "InvalidHeaderDefect", "(", "\"Invalid trailing '.' in local part\"", ")", ")", "if", "obs_local_part", ".", "defects", ":", "obs_local_part", ".", "token_type", "=", "'invalid-obs-local-part'", "return", "obs_local_part", ",", "value" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/email/_header_value_parser.py#L1483-L1528
apple/swift-clang
d7403439fc6641751840b723e7165fb02f52db95
bindings/python/clang/cindex.py
python
Cursor.kind
(self)
return CursorKind.from_id(self._kind_id)
Return the kind of this cursor.
Return the kind of this cursor.
[ "Return", "the", "kind", "of", "this", "cursor", "." ]
def kind(self): """Return the kind of this cursor.""" return CursorKind.from_id(self._kind_id)
[ "def", "kind", "(", "self", ")", ":", "return", "CursorKind", ".", "from_id", "(", "self", ".", "_kind_id", ")" ]
https://github.com/apple/swift-clang/blob/d7403439fc6641751840b723e7165fb02f52db95/bindings/python/clang/cindex.py#L1539-L1541
aimerykong/Low-Rank-Bilinear-Pooling
487eb2c857fd9c95357a5166b0c15ad0fe135b28
caffe-20160312/python/caffe/pycaffe.py
python
_Net_params
(self)
return OrderedDict([(name, lr.blobs) for name, lr in zip(self._layer_names, self.layers) if len(lr.blobs) > 0])
An OrderedDict (bottom to top, i.e., input to output) of network parameters indexed by name; each is a list of multiple blobs (e.g., weights and biases)
An OrderedDict (bottom to top, i.e., input to output) of network parameters indexed by name; each is a list of multiple blobs (e.g., weights and biases)
[ "An", "OrderedDict", "(", "bottom", "to", "top", "i", ".", "e", ".", "input", "to", "output", ")", "of", "network", "parameters", "indexed", "by", "name", ";", "each", "is", "a", "list", "of", "multiple", "blobs", "(", "e", ".", "g", ".", "weights", "and", "biases", ")" ]
def _Net_params(self): """ An OrderedDict (bottom to top, i.e., input to output) of network parameters indexed by name; each is a list of multiple blobs (e.g., weights and biases) """ return OrderedDict([(name, lr.blobs) for name, lr in zip(self._layer_names, self.layers) if len(lr.blobs) > 0])
[ "def", "_Net_params", "(", "self", ")", ":", "return", "OrderedDict", "(", "[", "(", "name", ",", "lr", ".", "blobs", ")", "for", "name", ",", "lr", "in", "zip", "(", "self", ".", "_layer_names", ",", "self", ".", "layers", ")", "if", "len", "(", "lr", ".", "blobs", ")", ">", "0", "]", ")" ]
https://github.com/aimerykong/Low-Rank-Bilinear-Pooling/blob/487eb2c857fd9c95357a5166b0c15ad0fe135b28/caffe-20160312/python/caffe/pycaffe.py#L43-L51
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/py2/scipy/optimize/_basinhopping.py
python
Metropolis.__call__
(self, **kwargs)
return bool(self.accept_reject(kwargs["f_new"], kwargs["f_old"]))
f_new and f_old are mandatory in kwargs
f_new and f_old are mandatory in kwargs
[ "f_new", "and", "f_old", "are", "mandatory", "in", "kwargs" ]
def __call__(self, **kwargs): """ f_new and f_old are mandatory in kwargs """ return bool(self.accept_reject(kwargs["f_new"], kwargs["f_old"]))
[ "def", "__call__", "(", "self", ",", "*", "*", "kwargs", ")", ":", "return", "bool", "(", "self", ".", "accept_reject", "(", "kwargs", "[", "\"f_new\"", "]", ",", "kwargs", "[", "\"f_old\"", "]", ")", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py2/scipy/optimize/_basinhopping.py#L317-L322
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_internal/network/download.py
python
parse_content_disposition
(content_disposition, default_filename)
return filename or default_filename
Parse the "filename" value from a Content-Disposition header, and return the default filename if the result is empty.
Parse the "filename" value from a Content-Disposition header, and return the default filename if the result is empty.
[ "Parse", "the", "filename", "value", "from", "a", "Content", "-", "Disposition", "header", "and", "return", "the", "default", "filename", "if", "the", "result", "is", "empty", "." ]
def parse_content_disposition(content_disposition, default_filename): # type: (str, str) -> str """ Parse the "filename" value from a Content-Disposition header, and return the default filename if the result is empty. """ _type, params = cgi.parse_header(content_disposition) filename = params.get('filename') if filename: # We need to sanitize the filename to prevent directory traversal # in case the filename contains ".." path parts. filename = sanitize_content_filename(filename) return filename or default_filename
[ "def", "parse_content_disposition", "(", "content_disposition", ",", "default_filename", ")", ":", "# type: (str, str) -> str", "_type", ",", "params", "=", "cgi", ".", "parse_header", "(", "content_disposition", ")", "filename", "=", "params", ".", "get", "(", "'filename'", ")", "if", "filename", ":", "# We need to sanitize the filename to prevent directory traversal", "# in case the filename contains \"..\" path parts.", "filename", "=", "sanitize_content_filename", "(", "filename", ")", "return", "filename", "or", "default_filename" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_internal/network/download.py#L89-L101
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/profiler/parser/hccl_parser.py
python
HcclParser._parse_link_cost
(self, result_dict, key, link_type_dict)
Parse link cost.
Parse link cost.
[ "Parse", "link", "cost", "." ]
def _parse_link_cost(self, result_dict, key, link_type_dict): """Parse link cost.""" for link_type_key, link_type_value in link_type_dict.items(): if link_type_key == CommunicationInfo.RDMA.value: # Divide information by thread. rdma_infos = [] threads_dict = self._divide_communication_info_by_thread(link_type_value) for thread_value in threads_dict.values(): rdma_info = self._calculate_adma_link_info(thread_value) rdma_infos.append(rdma_info) rdma_total_cost = np.sum(rdma_infos, axis=0).tolist() result_dict[key][link_type_key] = rdma_total_cost if link_type_key == CommunicationInfo.SDMA.value: sdma_total_cost = self._calculate_sdma_link_info(link_type_value) result_dict[key][link_type_key] = sdma_total_cost
[ "def", "_parse_link_cost", "(", "self", ",", "result_dict", ",", "key", ",", "link_type_dict", ")", ":", "for", "link_type_key", ",", "link_type_value", "in", "link_type_dict", ".", "items", "(", ")", ":", "if", "link_type_key", "==", "CommunicationInfo", ".", "RDMA", ".", "value", ":", "# Divide information by thread.", "rdma_infos", "=", "[", "]", "threads_dict", "=", "self", ".", "_divide_communication_info_by_thread", "(", "link_type_value", ")", "for", "thread_value", "in", "threads_dict", ".", "values", "(", ")", ":", "rdma_info", "=", "self", ".", "_calculate_adma_link_info", "(", "thread_value", ")", "rdma_infos", ".", "append", "(", "rdma_info", ")", "rdma_total_cost", "=", "np", ".", "sum", "(", "rdma_infos", ",", "axis", "=", "0", ")", ".", "tolist", "(", ")", "result_dict", "[", "key", "]", "[", "link_type_key", "]", "=", "rdma_total_cost", "if", "link_type_key", "==", "CommunicationInfo", ".", "SDMA", ".", "value", ":", "sdma_total_cost", "=", "self", ".", "_calculate_sdma_link_info", "(", "link_type_value", ")", "result_dict", "[", "key", "]", "[", "link_type_key", "]", "=", "sdma_total_cost" ]
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/profiler/parser/hccl_parser.py#L385-L399