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
Yijunmaverick/GenerativeFaceCompletion
f72dea0fa27c779fef7b65d2f01e82bcc23a0eb2
scripts/cpp_lint.py
python
CheckForMultilineCommentsAndStrings
(filename, clean_lines, linenum, error)
Logs an error if we see /* ... */ or "..." that extend past one line. /* ... */ comments are legit inside macros, for one line. Otherwise, we prefer // comments, so it's ok to warn about the other. Likewise, it's ok for strings to extend across multiple lines, as long as a line continuation character (backslash) terminates each line. Although not currently prohibited by the C++ style guide, it's ugly and unnecessary. We don't do well with either in this lint program, so we warn about both. 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.
Logs an error if we see /* ... */ or "..." that extend past one line.
[ "Logs", "an", "error", "if", "we", "see", "/", "*", "...", "*", "/", "or", "...", "that", "extend", "past", "one", "line", "." ]
def CheckForMultilineCommentsAndStrings(filename, clean_lines, linenum, error): """Logs an error if we see /* ... */ or "..." that extend past one line. /* ... */ comments are legit inside macros, for one line. Otherwise, we prefer // comments, so it's ok to warn about the other. Likewise, it's ok for strings to extend across multiple lines, as long as a line continuation character (backslash) terminates each line. Although not currently prohibited by the C++ style guide, it's ugly and unnecessary. We don't do well with either in this lint program, so we warn about both. 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. """ line = clean_lines.elided[linenum] # Remove all \\ (escaped backslashes) from the line. They are OK, and the # second (escaped) slash may trigger later \" detection erroneously. line = line.replace('\\\\', '') if line.count('/*') > line.count('*/'): error(filename, linenum, 'readability/multiline_comment', 5, 'Complex multi-line /*...*/-style comment found. ' 'Lint may give bogus warnings. ' 'Consider replacing these with //-style comments, ' 'with #if 0...#endif, ' 'or with more clearly structured multi-line comments.') if (line.count('"') - line.count('\\"')) % 2: error(filename, linenum, 'readability/multiline_string', 5, 'Multi-line string ("...") found. This lint script doesn\'t ' 'do well with such strings, and may give bogus warnings. ' 'Use C++11 raw strings or concatenation instead.')
[ "def", "CheckForMultilineCommentsAndStrings", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "error", ")", ":", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "# Remove all \\\\ (escaped backslashes) from the line. They are OK, and the", "# second (escaped) slash may trigger later \\\" detection erroneously.", "line", "=", "line", ".", "replace", "(", "'\\\\\\\\'", ",", "''", ")", "if", "line", ".", "count", "(", "'/*'", ")", ">", "line", ".", "count", "(", "'*/'", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'readability/multiline_comment'", ",", "5", ",", "'Complex multi-line /*...*/-style comment found. '", "'Lint may give bogus warnings. '", "'Consider replacing these with //-style comments, '", "'with #if 0...#endif, '", "'or with more clearly structured multi-line comments.'", ")", "if", "(", "line", ".", "count", "(", "'\"'", ")", "-", "line", ".", "count", "(", "'\\\\\"'", ")", ")", "%", "2", ":", "error", "(", "filename", ",", "linenum", ",", "'readability/multiline_string'", ",", "5", ",", "'Multi-line string (\"...\") found. This lint script doesn\\'t '", "'do well with such strings, and may give bogus warnings. '", "'Use C++11 raw strings or concatenation instead.'", ")" ]
https://github.com/Yijunmaverick/GenerativeFaceCompletion/blob/f72dea0fa27c779fef7b65d2f01e82bcc23a0eb2/scripts/cpp_lint.py#L1526-L1561
Caffe-MPI/Caffe-MPI.github.io
df5992af571a2a19981b69635115c393f18d1c76
python/caffe/pycaffe.py
python
_Net_forward
(self, blobs=None, start=None, end=None, **kwargs)
return {out: self.blobs[out].data for out in outputs}
Forward pass: prepare inputs and run the net forward. Parameters ---------- blobs : list of blobs to return in addition to output blobs. kwargs : Keys are input blob names and values are blob ndarrays. For formatting inputs for Caffe, see Net.preprocess(). If None, input is taken from data layers. start : optional name of layer at which to begin the forward pass end : optional name of layer at which to finish the forward pass (inclusive) Returns ------- outs : {blob name: blob ndarray} dict.
Forward pass: prepare inputs and run the net forward.
[ "Forward", "pass", ":", "prepare", "inputs", "and", "run", "the", "net", "forward", "." ]
def _Net_forward(self, blobs=None, start=None, end=None, **kwargs): """ Forward pass: prepare inputs and run the net forward. Parameters ---------- blobs : list of blobs to return in addition to output blobs. kwargs : Keys are input blob names and values are blob ndarrays. For formatting inputs for Caffe, see Net.preprocess(). If None, input is taken from data layers. start : optional name of layer at which to begin the forward pass end : optional name of layer at which to finish the forward pass (inclusive) Returns ------- outs : {blob name: blob ndarray} dict. """ if blobs is None: blobs = [] if start is not None: start_ind = list(self._layer_names).index(start) else: start_ind = 0 if end is not None: end_ind = list(self._layer_names).index(end) outputs = set([end] + blobs) else: end_ind = len(self.layers) - 1 outputs = set(self.outputs + blobs) if kwargs: if set(kwargs.keys()) != set(self.inputs): raise Exception('Input blob arguments do not match net inputs.') # Set input according to defined shapes and make arrays single and # C-contiguous as Caffe expects. for in_, blob in six.iteritems(kwargs): if blob.shape[0] != self.blobs[in_].shape[0]: raise Exception('Input is not batch sized') self.blobs[in_].data[...] = blob self._forward(start_ind, end_ind) # Unpack blobs to extract return {out: self.blobs[out].data for out in outputs}
[ "def", "_Net_forward", "(", "self", ",", "blobs", "=", "None", ",", "start", "=", "None", ",", "end", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "blobs", "is", "None", ":", "blobs", "=", "[", "]", "if", "start", "is", "not", "None", ":", "start_ind", "=", "list", "(", "self", ".", "_layer_names", ")", ".", "index", "(", "start", ")", "else", ":", "start_ind", "=", "0", "if", "end", "is", "not", "None", ":", "end_ind", "=", "list", "(", "self", ".", "_layer_names", ")", ".", "index", "(", "end", ")", "outputs", "=", "set", "(", "[", "end", "]", "+", "blobs", ")", "else", ":", "end_ind", "=", "len", "(", "self", ".", "layers", ")", "-", "1", "outputs", "=", "set", "(", "self", ".", "outputs", "+", "blobs", ")", "if", "kwargs", ":", "if", "set", "(", "kwargs", ".", "keys", "(", ")", ")", "!=", "set", "(", "self", ".", "inputs", ")", ":", "raise", "Exception", "(", "'Input blob arguments do not match net inputs.'", ")", "# Set input according to defined shapes and make arrays single and", "# C-contiguous as Caffe expects.", "for", "in_", ",", "blob", "in", "six", ".", "iteritems", "(", "kwargs", ")", ":", "if", "blob", ".", "shape", "[", "0", "]", "!=", "self", ".", "blobs", "[", "in_", "]", ".", "shape", "[", "0", "]", ":", "raise", "Exception", "(", "'Input is not batch sized'", ")", "self", ".", "blobs", "[", "in_", "]", ".", "data", "[", "...", "]", "=", "blob", "self", ".", "_forward", "(", "start_ind", ",", "end_ind", ")", "# Unpack blobs to extract", "return", "{", "out", ":", "self", ".", "blobs", "[", "out", "]", ".", "data", "for", "out", "in", "outputs", "}" ]
https://github.com/Caffe-MPI/Caffe-MPI.github.io/blob/df5992af571a2a19981b69635115c393f18d1c76/python/caffe/pycaffe.py#L78-L124
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/ipython/py2/IPython/core/prefilter.py
python
PrefilterManager.init_handlers
(self)
Create the default handlers.
Create the default handlers.
[ "Create", "the", "default", "handlers", "." ]
def init_handlers(self): """Create the default handlers.""" self._handlers = {} self._esc_handlers = {} for handler in _default_handlers: handler( shell=self.shell, prefilter_manager=self, parent=self )
[ "def", "init_handlers", "(", "self", ")", ":", "self", ".", "_handlers", "=", "{", "}", "self", ".", "_esc_handlers", "=", "{", "}", "for", "handler", "in", "_default_handlers", ":", "handler", "(", "shell", "=", "self", ".", "shell", ",", "prefilter_manager", "=", "self", ",", "parent", "=", "self", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/ipython/py2/IPython/core/prefilter.py#L203-L210
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/stc.py
python
StyledTextCtrl.GetColumn
(*args, **kwargs)
return _stc.StyledTextCtrl_GetColumn(*args, **kwargs)
GetColumn(self, int pos) -> int Retrieve the column number of a position, taking tab width into account.
GetColumn(self, int pos) -> int
[ "GetColumn", "(", "self", "int", "pos", ")", "-", ">", "int" ]
def GetColumn(*args, **kwargs): """ GetColumn(self, int pos) -> int Retrieve the column number of a position, taking tab width into account. """ return _stc.StyledTextCtrl_GetColumn(*args, **kwargs)
[ "def", "GetColumn", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_stc", ".", "StyledTextCtrl_GetColumn", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/stc.py#L3327-L3333
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/idlelib/pyshell.py
python
PyShellEditorWindow.update_breakpoints
(self)
Retrieves all the breakpoints in the current window
Retrieves all the breakpoints in the current window
[ "Retrieves", "all", "the", "breakpoints", "in", "the", "current", "window" ]
def update_breakpoints(self): "Retrieves all the breakpoints in the current window" text = self.text ranges = text.tag_ranges("BREAK") linenumber_list = self.ranges_to_linenumbers(ranges) self.breakpoints = linenumber_list
[ "def", "update_breakpoints", "(", "self", ")", ":", "text", "=", "self", ".", "text", "ranges", "=", "text", ".", "tag_ranges", "(", "\"BREAK\"", ")", "linenumber_list", "=", "self", ".", "ranges_to_linenumbers", "(", "ranges", ")", "self", ".", "breakpoints", "=", "linenumber_list" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/idlelib/pyshell.py#L286-L291
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/AWSPythonSDK/1.5.8/botocore/vendored/requests/utils.py
python
prepend_scheme_if_needed
(url, new_scheme)
return urlunparse((scheme, netloc, path, params, query, fragment))
Given a URL that may or may not have a scheme, prepend the given scheme. Does not replace a present scheme with the one provided as an argument.
Given a URL that may or may not have a scheme, prepend the given scheme. Does not replace a present scheme with the one provided as an argument.
[ "Given", "a", "URL", "that", "may", "or", "may", "not", "have", "a", "scheme", "prepend", "the", "given", "scheme", ".", "Does", "not", "replace", "a", "present", "scheme", "with", "the", "one", "provided", "as", "an", "argument", "." ]
def prepend_scheme_if_needed(url, new_scheme): '''Given a URL that may or may not have a scheme, prepend the given scheme. Does not replace a present scheme with the one provided as an argument.''' scheme, netloc, path, params, query, fragment = urlparse(url, new_scheme) # urlparse is a finicky beast, and sometimes decides that there isn't a # netloc present. Assume that it's being over-cautious, and switch netloc # and path if urlparse decided there was no netloc. if not netloc: netloc, path = path, netloc return urlunparse((scheme, netloc, path, params, query, fragment))
[ "def", "prepend_scheme_if_needed", "(", "url", ",", "new_scheme", ")", ":", "scheme", ",", "netloc", ",", "path", ",", "params", ",", "query", ",", "fragment", "=", "urlparse", "(", "url", ",", "new_scheme", ")", "# urlparse is a finicky beast, and sometimes decides that there isn't a", "# netloc present. Assume that it's being over-cautious, and switch netloc", "# and path if urlparse decided there was no netloc.", "if", "not", "netloc", ":", "netloc", ",", "path", "=", "path", ",", "netloc", "return", "urlunparse", "(", "(", "scheme", ",", "netloc", ",", "path", ",", "params", ",", "query", ",", "fragment", ")", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/AWSPythonSDK/1.5.8/botocore/vendored/requests/utils.py#L649-L660
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/pkg_resources/__init__.py
python
ResourceManager.resource_string
(self, package_or_requirement, resource_name)
return get_provider(package_or_requirement).get_resource_string( self, resource_name )
Return specified resource as a string
Return specified resource as a string
[ "Return", "specified", "resource", "as", "a", "string" ]
def resource_string(self, package_or_requirement, resource_name): """Return specified resource as a string""" return get_provider(package_or_requirement).get_resource_string( self, resource_name )
[ "def", "resource_string", "(", "self", ",", "package_or_requirement", ",", "resource_name", ")", ":", "return", "get_provider", "(", "package_or_requirement", ")", ".", "get_resource_string", "(", "self", ",", "resource_name", ")" ]
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/_vendor/pkg_resources/__init__.py#L1154-L1158
ros-planning/moveit
ee48dc5cedc981d0869352aa3db0b41469c2735c
moveit_ros/benchmarks/scripts/moveit_benchmark_statistics.py
python
readBenchmarkLog
(dbname, filenames)
Parse benchmark log files and store the parsed data in a sqlite3 database.
Parse benchmark log files and store the parsed data in a sqlite3 database.
[ "Parse", "benchmark", "log", "files", "and", "store", "the", "parsed", "data", "in", "a", "sqlite3", "database", "." ]
def readBenchmarkLog(dbname, filenames): """Parse benchmark log files and store the parsed data in a sqlite3 database.""" conn = sqlite3.connect(dbname) c = conn.cursor() c.execute("PRAGMA FOREIGN_KEYS = ON") # create all tables if they don't already exist c.executescript( """CREATE TABLE IF NOT EXISTS experiments (id INTEGER PRIMARY KEY ON CONFLICT REPLACE AUTOINCREMENT, name VARCHAR(512), totaltime REAL, timelimit REAL, memorylimit REAL, runcount INTEGER, version VARCHAR(128), hostname VARCHAR(1024), cpuinfo TEXT, date DATETIME, seed INTEGER, setup TEXT); CREATE TABLE IF NOT EXISTS plannerConfigs (id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR(512) NOT NULL, settings TEXT); CREATE TABLE IF NOT EXISTS enums (name VARCHAR(512), value INTEGER, description TEXT, PRIMARY KEY (name, value)); CREATE TABLE IF NOT EXISTS runs (id INTEGER PRIMARY KEY AUTOINCREMENT, experimentid INTEGER, plannerid INTEGER, FOREIGN KEY (experimentid) REFERENCES experiments(id) ON DELETE CASCADE, FOREIGN KEY (plannerid) REFERENCES plannerConfigs(id) ON DELETE CASCADE); CREATE TABLE IF NOT EXISTS progress (runid INTEGER, time REAL, PRIMARY KEY (runid, time), FOREIGN KEY (runid) REFERENCES runs(id) ON DELETE CASCADE)""" ) # add placeholder entry for all_experiments allExperimentsName = "all_experiments" allExperimentsValues = { "totaltime": 0.0, "timelimit": 0.0, "memorylimit": 0.0, "runcount": 0, "version": "0.0.0", "hostname": "", "cpuinfo": "", "date": 0, "seed": 0, "setup": "", } addAllExperiments = len(filenames) > 0 if addAllExperiments: c.execute( "INSERT INTO experiments VALUES (?,?,?,?,?,?,?,?,?,?,?,?)", (None, allExperimentsName) + tuple(allExperimentsValues.values()), ) allExperimentsId = c.lastrowid for i, filename in enumerate(filenames): print("Processing " + filename) logfile = open(filename, "r") start_pos = logfile.tell() libname = readOptionalLogValue(logfile, 0, {1: "version"}) if libname == None: libname = "OMPL" logfile.seek(start_pos) version = readOptionalLogValue(logfile, -1, {1: "version"}) if version == None: # set the version number to make Planner Arena happy version = "0.0.0" version = " ".join([libname, version]) expname = readRequiredLogValue( "experiment name", logfile, -1, {0: "Experiment"} ) hostname = readRequiredLogValue("hostname", logfile, -1, {0: "Running"}) date = " ".join(ensurePrefix(logfile.readline(), "Starting").split()[2:]) expsetup = readRequiredMultilineValue(logfile) cpuinfo = readOptionalMultilineValue(logfile) rseed = int( readRequiredLogValue("random seed", logfile, 0, {-2: "random", -1: "seed"}) ) timelimit = float( readRequiredLogValue( "time limit", logfile, 0, {-3: "seconds", -2: "per", -1: "run"} ) ) memorylimit = float( readRequiredLogValue( "memory limit", logfile, 0, {-3: "MB", -2: "per", -1: "run"} ) ) nrrunsOrNone = readOptionalLogValue( logfile, 0, {-3: "runs", -2: "per", -1: "planner"} ) nrruns = -1 if nrrunsOrNone != None: nrruns = int(nrrunsOrNone) allExperimentsValues["runcount"] += nrruns totaltime = float( readRequiredLogValue( "total time", logfile, 0, {-3: "collect", -2: "the", -1: "data"} ) ) # fill in fields of all_experiments allExperimentsValues["totaltime"] += totaltime allExperimentsValues["memorylimit"] = max( allExperimentsValues["memorylimit"], totaltime ) allExperimentsValues["timelimit"] = max( allExperimentsValues["timelimit"], totaltime ) # copy the fields of the first file to all_experiments so that they are not empty if i == 0: allExperimentsValues["version"] = version allExperimentsValues["date"] = date allExperimentsValues["setup"] = expsetup allExperimentsValues["hostname"] = hostname allExperimentsValues["cpuinfo"] = cpuinfo numEnums = 0 numEnumsOrNone = readOptionalLogValue(logfile, 0, {-2: "enum"}) if numEnumsOrNone != None: numEnums = int(numEnumsOrNone) for i in range(numEnums): enum = logfile.readline()[:-1].split("|") c.execute('SELECT * FROM enums WHERE name IS "%s"' % enum[0]) if c.fetchone() == None: for j in range(len(enum) - 1): c.execute( "INSERT INTO enums VALUES (?,?,?)", (enum[0], j, enum[j + 1]) ) c.execute( "INSERT INTO experiments VALUES (?,?,?,?,?,?,?,?,?,?,?,?)", ( None, expname, totaltime, timelimit, memorylimit, nrruns, version, hostname, cpuinfo, date, rseed, expsetup, ), ) experimentId = c.lastrowid numPlanners = int( readRequiredLogValue("planner count", logfile, 0, {-1: "planners"}) ) for i in range(numPlanners): plannerName = logfile.readline()[:-1] print("Parsing data for " + plannerName) # read common data for planner numCommon = int(logfile.readline().split()[0]) settings = "" for j in range(numCommon): settings = settings + logfile.readline() + ";" # find planner id c.execute( "SELECT id FROM plannerConfigs WHERE (name=? AND settings=?)", ( plannerName, settings, ), ) p = c.fetchone() if p == None: c.execute( "INSERT INTO plannerConfigs VALUES (?,?,?)", ( None, plannerName, settings, ), ) plannerId = c.lastrowid else: plannerId = p[0] # get current column names c.execute("PRAGMA table_info(runs)") columnNames = [col[1] for col in c.fetchall()] # read properties and add columns as necessary numProperties = int(logfile.readline().split()[0]) propertyNames = ["experimentid", "plannerid"] for j in range(numProperties): field = logfile.readline().split() propertyType = field[-1] propertyName = "_".join(field[:-1]) if propertyName not in columnNames: c.execute( "ALTER TABLE runs ADD %s %s" % (propertyName, propertyType) ) propertyNames.append(propertyName) # read measurements insertFmtStr = ( "INSERT INTO runs (" + ",".join(propertyNames) + ") VALUES (" + ",".join("?" * len(propertyNames)) + ")" ) numRuns = int(logfile.readline().split()[0]) runIds = [] for j in range(numRuns): runValues = [ None if len(x) == 0 or x == "nan" or x == "inf" else x for x in logfile.readline().split("; ")[:-1] ] values = tuple([experimentId, plannerId] + runValues) c.execute(insertFmtStr, values) # extract primary key of each run row so we can reference them # in the planner progress data table if needed runIds.append(c.lastrowid) # add all run data to all_experiments if addAllExperiments: values = tuple([allExperimentsId, plannerId] + runValues) c.execute(insertFmtStr, values) nextLine = logfile.readline().strip() # read planner progress data if it's supplied if nextLine != ".": # get current column names c.execute("PRAGMA table_info(progress)") columnNames = [col[1] for col in c.fetchall()] # read progress properties and add columns as necesary numProgressProperties = int(nextLine.split()[0]) progressPropertyNames = ["runid"] for i in range(numProgressProperties): field = logfile.readline().split() progressPropertyType = field[-1] progressPropertyName = "_".join(field[:-1]) if progressPropertyName not in columnNames: c.execute( "ALTER TABLE progress ADD %s %s" % (progressPropertyName, progressPropertyType) ) progressPropertyNames.append(progressPropertyName) # read progress measurements insertFmtStr = ( "INSERT INTO progress (" + ",".join(progressPropertyNames) + ") VALUES (" + ",".join("?" * len(progressPropertyNames)) + ")" ) numRuns = int(logfile.readline().split()[0]) for j in range(numRuns): dataSeries = logfile.readline().split(";")[:-1] for dataSample in dataSeries: values = tuple( [runIds[j]] + [ None if len(x) == 0 or x == "nan" or x == "inf" else x for x in dataSample.split(",")[:-1] ] ) try: c.execute(insertFmtStr, values) except sqlite3.IntegrityError: print( "Ignoring duplicate progress data. Consider increasing ompl::tools::Benchmark::Request::timeBetweenUpdates." ) pass logfile.readline() logfile.close() if addAllExperiments: updateString = "UPDATE experiments SET" for i, (key, val) in enumerate(allExperimentsValues.items()): if i > 0: updateString += "," updateString += " " + str(key) + "='" + str(val) + "'" updateString += "WHERE id='" + str(allExperimentsId) + "'" c.execute(updateString) conn.commit() c.close()
[ "def", "readBenchmarkLog", "(", "dbname", ",", "filenames", ")", ":", "conn", "=", "sqlite3", ".", "connect", "(", "dbname", ")", "c", "=", "conn", ".", "cursor", "(", ")", "c", ".", "execute", "(", "\"PRAGMA FOREIGN_KEYS = ON\"", ")", "# create all tables if they don't already exist", "c", ".", "executescript", "(", "\"\"\"CREATE TABLE IF NOT EXISTS experiments\n (id INTEGER PRIMARY KEY ON CONFLICT REPLACE AUTOINCREMENT, name VARCHAR(512),\n totaltime REAL, timelimit REAL, memorylimit REAL, runcount INTEGER,\n version VARCHAR(128), hostname VARCHAR(1024), cpuinfo TEXT,\n date DATETIME, seed INTEGER, setup TEXT);\n CREATE TABLE IF NOT EXISTS plannerConfigs\n (id INTEGER PRIMARY KEY AUTOINCREMENT,\n name VARCHAR(512) NOT NULL, settings TEXT);\n CREATE TABLE IF NOT EXISTS enums\n (name VARCHAR(512), value INTEGER, description TEXT,\n PRIMARY KEY (name, value));\n CREATE TABLE IF NOT EXISTS runs\n (id INTEGER PRIMARY KEY AUTOINCREMENT, experimentid INTEGER, plannerid INTEGER,\n FOREIGN KEY (experimentid) REFERENCES experiments(id) ON DELETE CASCADE,\n FOREIGN KEY (plannerid) REFERENCES plannerConfigs(id) ON DELETE CASCADE);\n CREATE TABLE IF NOT EXISTS progress\n (runid INTEGER, time REAL, PRIMARY KEY (runid, time),\n FOREIGN KEY (runid) REFERENCES runs(id) ON DELETE CASCADE)\"\"\"", ")", "# add placeholder entry for all_experiments", "allExperimentsName", "=", "\"all_experiments\"", "allExperimentsValues", "=", "{", "\"totaltime\"", ":", "0.0", ",", "\"timelimit\"", ":", "0.0", ",", "\"memorylimit\"", ":", "0.0", ",", "\"runcount\"", ":", "0", ",", "\"version\"", ":", "\"0.0.0\"", ",", "\"hostname\"", ":", "\"\"", ",", "\"cpuinfo\"", ":", "\"\"", ",", "\"date\"", ":", "0", ",", "\"seed\"", ":", "0", ",", "\"setup\"", ":", "\"\"", ",", "}", "addAllExperiments", "=", "len", "(", "filenames", ")", ">", "0", "if", "addAllExperiments", ":", "c", ".", "execute", "(", "\"INSERT INTO experiments VALUES (?,?,?,?,?,?,?,?,?,?,?,?)\"", ",", "(", "None", ",", "allExperimentsName", ")", "+", "tuple", "(", "allExperimentsValues", ".", "values", "(", ")", ")", ",", ")", "allExperimentsId", "=", "c", ".", "lastrowid", "for", "i", ",", "filename", "in", "enumerate", "(", "filenames", ")", ":", "print", "(", "\"Processing \"", "+", "filename", ")", "logfile", "=", "open", "(", "filename", ",", "\"r\"", ")", "start_pos", "=", "logfile", ".", "tell", "(", ")", "libname", "=", "readOptionalLogValue", "(", "logfile", ",", "0", ",", "{", "1", ":", "\"version\"", "}", ")", "if", "libname", "==", "None", ":", "libname", "=", "\"OMPL\"", "logfile", ".", "seek", "(", "start_pos", ")", "version", "=", "readOptionalLogValue", "(", "logfile", ",", "-", "1", ",", "{", "1", ":", "\"version\"", "}", ")", "if", "version", "==", "None", ":", "# set the version number to make Planner Arena happy", "version", "=", "\"0.0.0\"", "version", "=", "\" \"", ".", "join", "(", "[", "libname", ",", "version", "]", ")", "expname", "=", "readRequiredLogValue", "(", "\"experiment name\"", ",", "logfile", ",", "-", "1", ",", "{", "0", ":", "\"Experiment\"", "}", ")", "hostname", "=", "readRequiredLogValue", "(", "\"hostname\"", ",", "logfile", ",", "-", "1", ",", "{", "0", ":", "\"Running\"", "}", ")", "date", "=", "\" \"", ".", "join", "(", "ensurePrefix", "(", "logfile", ".", "readline", "(", ")", ",", "\"Starting\"", ")", ".", "split", "(", ")", "[", "2", ":", "]", ")", "expsetup", "=", "readRequiredMultilineValue", "(", "logfile", ")", "cpuinfo", "=", "readOptionalMultilineValue", "(", "logfile", ")", "rseed", "=", "int", "(", "readRequiredLogValue", "(", "\"random seed\"", ",", "logfile", ",", "0", ",", "{", "-", "2", ":", "\"random\"", ",", "-", "1", ":", "\"seed\"", "}", ")", ")", "timelimit", "=", "float", "(", "readRequiredLogValue", "(", "\"time limit\"", ",", "logfile", ",", "0", ",", "{", "-", "3", ":", "\"seconds\"", ",", "-", "2", ":", "\"per\"", ",", "-", "1", ":", "\"run\"", "}", ")", ")", "memorylimit", "=", "float", "(", "readRequiredLogValue", "(", "\"memory limit\"", ",", "logfile", ",", "0", ",", "{", "-", "3", ":", "\"MB\"", ",", "-", "2", ":", "\"per\"", ",", "-", "1", ":", "\"run\"", "}", ")", ")", "nrrunsOrNone", "=", "readOptionalLogValue", "(", "logfile", ",", "0", ",", "{", "-", "3", ":", "\"runs\"", ",", "-", "2", ":", "\"per\"", ",", "-", "1", ":", "\"planner\"", "}", ")", "nrruns", "=", "-", "1", "if", "nrrunsOrNone", "!=", "None", ":", "nrruns", "=", "int", "(", "nrrunsOrNone", ")", "allExperimentsValues", "[", "\"runcount\"", "]", "+=", "nrruns", "totaltime", "=", "float", "(", "readRequiredLogValue", "(", "\"total time\"", ",", "logfile", ",", "0", ",", "{", "-", "3", ":", "\"collect\"", ",", "-", "2", ":", "\"the\"", ",", "-", "1", ":", "\"data\"", "}", ")", ")", "# fill in fields of all_experiments", "allExperimentsValues", "[", "\"totaltime\"", "]", "+=", "totaltime", "allExperimentsValues", "[", "\"memorylimit\"", "]", "=", "max", "(", "allExperimentsValues", "[", "\"memorylimit\"", "]", ",", "totaltime", ")", "allExperimentsValues", "[", "\"timelimit\"", "]", "=", "max", "(", "allExperimentsValues", "[", "\"timelimit\"", "]", ",", "totaltime", ")", "# copy the fields of the first file to all_experiments so that they are not empty", "if", "i", "==", "0", ":", "allExperimentsValues", "[", "\"version\"", "]", "=", "version", "allExperimentsValues", "[", "\"date\"", "]", "=", "date", "allExperimentsValues", "[", "\"setup\"", "]", "=", "expsetup", "allExperimentsValues", "[", "\"hostname\"", "]", "=", "hostname", "allExperimentsValues", "[", "\"cpuinfo\"", "]", "=", "cpuinfo", "numEnums", "=", "0", "numEnumsOrNone", "=", "readOptionalLogValue", "(", "logfile", ",", "0", ",", "{", "-", "2", ":", "\"enum\"", "}", ")", "if", "numEnumsOrNone", "!=", "None", ":", "numEnums", "=", "int", "(", "numEnumsOrNone", ")", "for", "i", "in", "range", "(", "numEnums", ")", ":", "enum", "=", "logfile", ".", "readline", "(", ")", "[", ":", "-", "1", "]", ".", "split", "(", "\"|\"", ")", "c", ".", "execute", "(", "'SELECT * FROM enums WHERE name IS \"%s\"'", "%", "enum", "[", "0", "]", ")", "if", "c", ".", "fetchone", "(", ")", "==", "None", ":", "for", "j", "in", "range", "(", "len", "(", "enum", ")", "-", "1", ")", ":", "c", ".", "execute", "(", "\"INSERT INTO enums VALUES (?,?,?)\"", ",", "(", "enum", "[", "0", "]", ",", "j", ",", "enum", "[", "j", "+", "1", "]", ")", ")", "c", ".", "execute", "(", "\"INSERT INTO experiments VALUES (?,?,?,?,?,?,?,?,?,?,?,?)\"", ",", "(", "None", ",", "expname", ",", "totaltime", ",", "timelimit", ",", "memorylimit", ",", "nrruns", ",", "version", ",", "hostname", ",", "cpuinfo", ",", "date", ",", "rseed", ",", "expsetup", ",", ")", ",", ")", "experimentId", "=", "c", ".", "lastrowid", "numPlanners", "=", "int", "(", "readRequiredLogValue", "(", "\"planner count\"", ",", "logfile", ",", "0", ",", "{", "-", "1", ":", "\"planners\"", "}", ")", ")", "for", "i", "in", "range", "(", "numPlanners", ")", ":", "plannerName", "=", "logfile", ".", "readline", "(", ")", "[", ":", "-", "1", "]", "print", "(", "\"Parsing data for \"", "+", "plannerName", ")", "# read common data for planner", "numCommon", "=", "int", "(", "logfile", ".", "readline", "(", ")", ".", "split", "(", ")", "[", "0", "]", ")", "settings", "=", "\"\"", "for", "j", "in", "range", "(", "numCommon", ")", ":", "settings", "=", "settings", "+", "logfile", ".", "readline", "(", ")", "+", "\";\"", "# find planner id", "c", ".", "execute", "(", "\"SELECT id FROM plannerConfigs WHERE (name=? AND settings=?)\"", ",", "(", "plannerName", ",", "settings", ",", ")", ",", ")", "p", "=", "c", ".", "fetchone", "(", ")", "if", "p", "==", "None", ":", "c", ".", "execute", "(", "\"INSERT INTO plannerConfigs VALUES (?,?,?)\"", ",", "(", "None", ",", "plannerName", ",", "settings", ",", ")", ",", ")", "plannerId", "=", "c", ".", "lastrowid", "else", ":", "plannerId", "=", "p", "[", "0", "]", "# get current column names", "c", ".", "execute", "(", "\"PRAGMA table_info(runs)\"", ")", "columnNames", "=", "[", "col", "[", "1", "]", "for", "col", "in", "c", ".", "fetchall", "(", ")", "]", "# read properties and add columns as necessary", "numProperties", "=", "int", "(", "logfile", ".", "readline", "(", ")", ".", "split", "(", ")", "[", "0", "]", ")", "propertyNames", "=", "[", "\"experimentid\"", ",", "\"plannerid\"", "]", "for", "j", "in", "range", "(", "numProperties", ")", ":", "field", "=", "logfile", ".", "readline", "(", ")", ".", "split", "(", ")", "propertyType", "=", "field", "[", "-", "1", "]", "propertyName", "=", "\"_\"", ".", "join", "(", "field", "[", ":", "-", "1", "]", ")", "if", "propertyName", "not", "in", "columnNames", ":", "c", ".", "execute", "(", "\"ALTER TABLE runs ADD %s %s\"", "%", "(", "propertyName", ",", "propertyType", ")", ")", "propertyNames", ".", "append", "(", "propertyName", ")", "# read measurements", "insertFmtStr", "=", "(", "\"INSERT INTO runs (\"", "+", "\",\"", ".", "join", "(", "propertyNames", ")", "+", "\") VALUES (\"", "+", "\",\"", ".", "join", "(", "\"?\"", "*", "len", "(", "propertyNames", ")", ")", "+", "\")\"", ")", "numRuns", "=", "int", "(", "logfile", ".", "readline", "(", ")", ".", "split", "(", ")", "[", "0", "]", ")", "runIds", "=", "[", "]", "for", "j", "in", "range", "(", "numRuns", ")", ":", "runValues", "=", "[", "None", "if", "len", "(", "x", ")", "==", "0", "or", "x", "==", "\"nan\"", "or", "x", "==", "\"inf\"", "else", "x", "for", "x", "in", "logfile", ".", "readline", "(", ")", ".", "split", "(", "\"; \"", ")", "[", ":", "-", "1", "]", "]", "values", "=", "tuple", "(", "[", "experimentId", ",", "plannerId", "]", "+", "runValues", ")", "c", ".", "execute", "(", "insertFmtStr", ",", "values", ")", "# extract primary key of each run row so we can reference them", "# in the planner progress data table if needed", "runIds", ".", "append", "(", "c", ".", "lastrowid", ")", "# add all run data to all_experiments", "if", "addAllExperiments", ":", "values", "=", "tuple", "(", "[", "allExperimentsId", ",", "plannerId", "]", "+", "runValues", ")", "c", ".", "execute", "(", "insertFmtStr", ",", "values", ")", "nextLine", "=", "logfile", ".", "readline", "(", ")", ".", "strip", "(", ")", "# read planner progress data if it's supplied", "if", "nextLine", "!=", "\".\"", ":", "# get current column names", "c", ".", "execute", "(", "\"PRAGMA table_info(progress)\"", ")", "columnNames", "=", "[", "col", "[", "1", "]", "for", "col", "in", "c", ".", "fetchall", "(", ")", "]", "# read progress properties and add columns as necesary", "numProgressProperties", "=", "int", "(", "nextLine", ".", "split", "(", ")", "[", "0", "]", ")", "progressPropertyNames", "=", "[", "\"runid\"", "]", "for", "i", "in", "range", "(", "numProgressProperties", ")", ":", "field", "=", "logfile", ".", "readline", "(", ")", ".", "split", "(", ")", "progressPropertyType", "=", "field", "[", "-", "1", "]", "progressPropertyName", "=", "\"_\"", ".", "join", "(", "field", "[", ":", "-", "1", "]", ")", "if", "progressPropertyName", "not", "in", "columnNames", ":", "c", ".", "execute", "(", "\"ALTER TABLE progress ADD %s %s\"", "%", "(", "progressPropertyName", ",", "progressPropertyType", ")", ")", "progressPropertyNames", ".", "append", "(", "progressPropertyName", ")", "# read progress measurements", "insertFmtStr", "=", "(", "\"INSERT INTO progress (\"", "+", "\",\"", ".", "join", "(", "progressPropertyNames", ")", "+", "\") VALUES (\"", "+", "\",\"", ".", "join", "(", "\"?\"", "*", "len", "(", "progressPropertyNames", ")", ")", "+", "\")\"", ")", "numRuns", "=", "int", "(", "logfile", ".", "readline", "(", ")", ".", "split", "(", ")", "[", "0", "]", ")", "for", "j", "in", "range", "(", "numRuns", ")", ":", "dataSeries", "=", "logfile", ".", "readline", "(", ")", ".", "split", "(", "\";\"", ")", "[", ":", "-", "1", "]", "for", "dataSample", "in", "dataSeries", ":", "values", "=", "tuple", "(", "[", "runIds", "[", "j", "]", "]", "+", "[", "None", "if", "len", "(", "x", ")", "==", "0", "or", "x", "==", "\"nan\"", "or", "x", "==", "\"inf\"", "else", "x", "for", "x", "in", "dataSample", ".", "split", "(", "\",\"", ")", "[", ":", "-", "1", "]", "]", ")", "try", ":", "c", ".", "execute", "(", "insertFmtStr", ",", "values", ")", "except", "sqlite3", ".", "IntegrityError", ":", "print", "(", "\"Ignoring duplicate progress data. Consider increasing ompl::tools::Benchmark::Request::timeBetweenUpdates.\"", ")", "pass", "logfile", ".", "readline", "(", ")", "logfile", ".", "close", "(", ")", "if", "addAllExperiments", ":", "updateString", "=", "\"UPDATE experiments SET\"", "for", "i", ",", "(", "key", ",", "val", ")", "in", "enumerate", "(", "allExperimentsValues", ".", "items", "(", ")", ")", ":", "if", "i", ">", "0", ":", "updateString", "+=", "\",\"", "updateString", "+=", "\" \"", "+", "str", "(", "key", ")", "+", "\"='\"", "+", "str", "(", "val", ")", "+", "\"'\"", "updateString", "+=", "\"WHERE id='\"", "+", "str", "(", "allExperimentsId", ")", "+", "\"'\"", "c", ".", "execute", "(", "updateString", ")", "conn", ".", "commit", "(", ")", "c", ".", "close", "(", ")" ]
https://github.com/ros-planning/moveit/blob/ee48dc5cedc981d0869352aa3db0b41469c2735c/moveit_ros/benchmarks/scripts/moveit_benchmark_statistics.py#L112-L389
abforce/xposed_art_n
ec3fbe417d74d4664cec053d91dd4e3881176374
tools/checker/match/file.py
python
matchDagGroup
(assertions, c1Pass, scope, variables)
return MatchInfo(MatchScope(min(matchedLines), max(matchedLines)), variables)
Attempts to find matching `c1Pass` lines for a group of DAG assertions. Assertions are matched in the list order and variable values propagated. Only lines in `scope` are scanned and each line can only match one assertion. Returns the range of `c1Pass` lines covered by this group (min/max of matching line numbers) and the variable values after the match of the last assertion. Raises MatchFailedException when an assertion cannot be satisfied.
Attempts to find matching `c1Pass` lines for a group of DAG assertions.
[ "Attempts", "to", "find", "matching", "c1Pass", "lines", "for", "a", "group", "of", "DAG", "assertions", "." ]
def matchDagGroup(assertions, c1Pass, scope, variables): """ Attempts to find matching `c1Pass` lines for a group of DAG assertions. Assertions are matched in the list order and variable values propagated. Only lines in `scope` are scanned and each line can only match one assertion. Returns the range of `c1Pass` lines covered by this group (min/max of matching line numbers) and the variable values after the match of the last assertion. Raises MatchFailedException when an assertion cannot be satisfied. """ matchedLines = [] for assertion in assertions: assert assertion.variant == TestAssertion.Variant.DAG match = findMatchingLine(assertion, c1Pass, scope, variables, matchedLines) variables = match.variables assert match.scope.start == match.scope.end assert match.scope.start not in matchedLines matchedLines.append(match.scope.start) return MatchInfo(MatchScope(min(matchedLines), max(matchedLines)), variables)
[ "def", "matchDagGroup", "(", "assertions", ",", "c1Pass", ",", "scope", ",", "variables", ")", ":", "matchedLines", "=", "[", "]", "for", "assertion", "in", "assertions", ":", "assert", "assertion", ".", "variant", "==", "TestAssertion", ".", "Variant", ".", "DAG", "match", "=", "findMatchingLine", "(", "assertion", ",", "c1Pass", ",", "scope", ",", "variables", ",", "matchedLines", ")", "variables", "=", "match", ".", "variables", "assert", "match", ".", "scope", ".", "start", "==", "match", ".", "scope", ".", "end", "assert", "match", ".", "scope", ".", "start", "not", "in", "matchedLines", "matchedLines", ".", "append", "(", "match", ".", "scope", ".", "start", ")", "return", "MatchInfo", "(", "MatchScope", "(", "min", "(", "matchedLines", ")", ",", "max", "(", "matchedLines", ")", ")", ",", "variables", ")" ]
https://github.com/abforce/xposed_art_n/blob/ec3fbe417d74d4664cec053d91dd4e3881176374/tools/checker/match/file.py#L64-L83
lhmRyan/deep-supervised-hashing-DSH
631901f82e2ab031fbac33f914a5b08ef8e21d57
scripts/cpp_lint.py
python
_FunctionState.End
(self)
Stop analyzing function body.
Stop analyzing function body.
[ "Stop", "analyzing", "function", "body", "." ]
def End(self): """Stop analyzing function body.""" self.in_a_function = False
[ "def", "End", "(", "self", ")", ":", "self", ".", "in_a_function", "=", "False" ]
https://github.com/lhmRyan/deep-supervised-hashing-DSH/blob/631901f82e2ab031fbac33f914a5b08ef8e21d57/scripts/cpp_lint.py#L861-L863
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/py3/scipy/sparse/sputils.py
python
upcast
(*args)
Returns the nearest supported sparse dtype for the combination of one or more types. upcast(t0, t1, ..., tn) -> T where T is a supported dtype Examples -------- >>> upcast('int32') <type 'numpy.int32'> >>> upcast('bool') <type 'numpy.bool_'> >>> upcast('int32','float32') <type 'numpy.float64'> >>> upcast('bool',complex,float) <type 'numpy.complex128'>
Returns the nearest supported sparse dtype for the combination of one or more types.
[ "Returns", "the", "nearest", "supported", "sparse", "dtype", "for", "the", "combination", "of", "one", "or", "more", "types", "." ]
def upcast(*args): """Returns the nearest supported sparse dtype for the combination of one or more types. upcast(t0, t1, ..., tn) -> T where T is a supported dtype Examples -------- >>> upcast('int32') <type 'numpy.int32'> >>> upcast('bool') <type 'numpy.bool_'> >>> upcast('int32','float32') <type 'numpy.float64'> >>> upcast('bool',complex,float) <type 'numpy.complex128'> """ t = _upcast_memo.get(hash(args)) if t is not None: return t upcast = np.find_common_type(args, []) for t in supported_dtypes: if np.can_cast(upcast, t): _upcast_memo[hash(args)] = t return t raise TypeError('no supported conversion for types: %r' % (args,))
[ "def", "upcast", "(", "*", "args", ")", ":", "t", "=", "_upcast_memo", ".", "get", "(", "hash", "(", "args", ")", ")", "if", "t", "is", "not", "None", ":", "return", "t", "upcast", "=", "np", ".", "find_common_type", "(", "args", ",", "[", "]", ")", "for", "t", "in", "supported_dtypes", ":", "if", "np", ".", "can_cast", "(", "upcast", ",", "t", ")", ":", "_upcast_memo", "[", "hash", "(", "args", ")", "]", "=", "t", "return", "t", "raise", "TypeError", "(", "'no supported conversion for types: %r'", "%", "(", "args", ",", ")", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py3/scipy/sparse/sputils.py#L28-L59
qt/qt
0a2f2382541424726168804be2c90b91381608c6
src/3rdparty/freetype/src/tools/glnames.py
python
adobe_glyph_values
()
return glyphs, values
return the list of glyph names and their unicode values
return the list of glyph names and their unicode values
[ "return", "the", "list", "of", "glyph", "names", "and", "their", "unicode", "values" ]
def adobe_glyph_values(): """return the list of glyph names and their unicode values""" lines = string.split( adobe_glyph_list, '\n' ) glyphs = [] values = [] for line in lines: if line: fields = string.split( line, ';' ) # print fields[1] + ' - ' + fields[0] subfields = string.split( fields[1], ' ' ) if len( subfields ) == 1: glyphs.append( fields[0] ) values.append( fields[1] ) return glyphs, values
[ "def", "adobe_glyph_values", "(", ")", ":", "lines", "=", "string", ".", "split", "(", "adobe_glyph_list", ",", "'\\n'", ")", "glyphs", "=", "[", "]", "values", "=", "[", "]", "for", "line", "in", "lines", ":", "if", "line", ":", "fields", "=", "string", ".", "split", "(", "line", ",", "';'", ")", "# print fields[1] + ' - ' + fields[0]", "subfields", "=", "string", ".", "split", "(", "fields", "[", "1", "]", ",", "' '", ")", "if", "len", "(", "subfields", ")", "==", "1", ":", "glyphs", ".", "append", "(", "fields", "[", "0", "]", ")", "values", ".", "append", "(", "fields", "[", "1", "]", ")", "return", "glyphs", ",", "values" ]
https://github.com/qt/qt/blob/0a2f2382541424726168804be2c90b91381608c6/src/3rdparty/freetype/src/tools/glnames.py#L4952-L4968
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/idlelib/rpc.py
python
RPCServer.server_activate
(self)
Override TCPServer method, connect() instead of listen() Due to the reversed connection, self.server_address is actually the address of the Idle Client to which we are connecting.
Override TCPServer method, connect() instead of listen()
[ "Override", "TCPServer", "method", "connect", "()", "instead", "of", "listen", "()" ]
def server_activate(self): """Override TCPServer method, connect() instead of listen() Due to the reversed connection, self.server_address is actually the address of the Idle Client to which we are connecting. """ self.socket.connect(self.server_address)
[ "def", "server_activate", "(", "self", ")", ":", "self", ".", "socket", ".", "connect", "(", "self", ".", "server_address", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/idlelib/rpc.py#L85-L92
NVIDIAGameWorks/kaolin
e5148d05e9c1e2ce92a07881ce3593b1c5c3f166
kaolin/io/dataset.py
python
ProcessedDataset.get_data
(self, index)
return data
Returns the data at the given index.
Returns the data at the given index.
[ "Returns", "the", "data", "at", "the", "given", "index", "." ]
def get_data(self, index): """Returns the data at the given index. """ data = (self._get_base_data(index) if self.cache_convert is None else self.cache_convert.try_get(self.get_cache_key(index))) if self.transform is not None: data = self.transform(data) return data
[ "def", "get_data", "(", "self", ",", "index", ")", ":", "data", "=", "(", "self", ".", "_get_base_data", "(", "index", ")", "if", "self", ".", "cache_convert", "is", "None", "else", "self", ".", "cache_convert", ".", "try_get", "(", "self", ".", "get_cache_key", "(", "index", ")", ")", ")", "if", "self", ".", "transform", "is", "not", "None", ":", "data", "=", "self", ".", "transform", "(", "data", ")", "return", "data" ]
https://github.com/NVIDIAGameWorks/kaolin/blob/e5148d05e9c1e2ce92a07881ce3593b1c5c3f166/kaolin/io/dataset.py#L253-L261
openthread/openthread
9fcdbed9c526c70f1556d1ed84099c1535c7cd32
tools/otci/otci/otci.py
python
OTCI.__init__
(self, otcmd: OTCommandHandler)
This method initializes an OTCI instance. :param otcmd: An OpenThread Command Handler instance to execute OpenThread CLI commands.
This method initializes an OTCI instance.
[ "This", "method", "initializes", "an", "OTCI", "instance", "." ]
def __init__(self, otcmd: OTCommandHandler): """ This method initializes an OTCI instance. :param otcmd: An OpenThread Command Handler instance to execute OpenThread CLI commands. """ self.__otcmd: OTCommandHandler = otcmd self.__logger = logging.getLogger(name=str(self))
[ "def", "__init__", "(", "self", ",", "otcmd", ":", "OTCommandHandler", ")", ":", "self", ".", "__otcmd", ":", "OTCommandHandler", "=", "otcmd", "self", ".", "__logger", "=", "logging", ".", "getLogger", "(", "name", "=", "str", "(", "self", ")", ")" ]
https://github.com/openthread/openthread/blob/9fcdbed9c526c70f1556d1ed84099c1535c7cd32/tools/otci/otci/otci.py#L54-L61
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/nn/probability/bijector/scalar_affine.py
python
ScalarAffine.extend_repr
(self)
return str_info
Display instance object as string.
Display instance object as string.
[ "Display", "instance", "object", "as", "string", "." ]
def extend_repr(self): """Display instance object as string.""" if self.is_scalar_batch: str_info = 'scale = {}, shift = {}'.format(self.scale, self.shift) else: str_info = 'batch_shape = {}'.format(self.batch_shape) return str_info
[ "def", "extend_repr", "(", "self", ")", ":", "if", "self", ".", "is_scalar_batch", ":", "str_info", "=", "'scale = {}, shift = {}'", ".", "format", "(", "self", ".", "scale", ",", "self", ".", "shift", ")", "else", ":", "str_info", "=", "'batch_shape = {}'", ".", "format", "(", "self", ".", "batch_shape", ")", "return", "str_info" ]
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/nn/probability/bijector/scalar_affine.py#L128-L134
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_windows.py
python
Dialog.GetLayoutAdaptationMode
(*args, **kwargs)
return _windows_.Dialog_GetLayoutAdaptationMode(*args, **kwargs)
GetLayoutAdaptationMode(self) -> int
GetLayoutAdaptationMode(self) -> int
[ "GetLayoutAdaptationMode", "(", "self", ")", "-", ">", "int" ]
def GetLayoutAdaptationMode(*args, **kwargs): """GetLayoutAdaptationMode(self) -> int""" return _windows_.Dialog_GetLayoutAdaptationMode(*args, **kwargs)
[ "def", "GetLayoutAdaptationMode", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_windows_", ".", "Dialog_GetLayoutAdaptationMode", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_windows.py#L855-L857
adobe/chromium
cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7
tools/generate_stubs/generate_stubs.py
python
WriteWindowsDefFile
(module_name, signatures, outfile)
Writes a windows def file to the given output file object. The def file format is basically a list of function names. Generation is simple. After outputting the LIBRARY and EXPORTS lines, print out each function name, one to a line, preceeded by 2 spaces. Args: module_name: The name of the module we are writing a stub for. signatures: The list of signature hashes, as produced by ParseSignatures, to create stubs for. outfile: File handle to populate with definitions.
Writes a windows def file to the given output file object.
[ "Writes", "a", "windows", "def", "file", "to", "the", "given", "output", "file", "object", "." ]
def WriteWindowsDefFile(module_name, signatures, outfile): """Writes a windows def file to the given output file object. The def file format is basically a list of function names. Generation is simple. After outputting the LIBRARY and EXPORTS lines, print out each function name, one to a line, preceeded by 2 spaces. Args: module_name: The name of the module we are writing a stub for. signatures: The list of signature hashes, as produced by ParseSignatures, to create stubs for. outfile: File handle to populate with definitions. """ outfile.write('LIBRARY %s\n' % module_name) outfile.write('EXPORTS\n') for sig in signatures: outfile.write(' %s\n' % sig['name'])
[ "def", "WriteWindowsDefFile", "(", "module_name", ",", "signatures", ",", "outfile", ")", ":", "outfile", ".", "write", "(", "'LIBRARY %s\\n'", "%", "module_name", ")", "outfile", ".", "write", "(", "'EXPORTS\\n'", ")", "for", "sig", "in", "signatures", ":", "outfile", ".", "write", "(", "' %s\\n'", "%", "sig", "[", "'name'", "]", ")" ]
https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/tools/generate_stubs/generate_stubs.py#L422-L439
asLody/whale
6a661b27cc4cf83b7b5a3b02451597ee1ac7f264
whale/cpplint.py
python
CheckTrailingSemicolon
(filename, clean_lines, linenum, error)
Looks for redundant trailing 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.
Looks for redundant trailing semicolon.
[ "Looks", "for", "redundant", "trailing", "semicolon", "." ]
def CheckTrailingSemicolon(filename, clean_lines, linenum, error): """Looks for redundant trailing 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. """ line = clean_lines.elided[linenum] # Block bodies should not be followed by a semicolon. Due to C++11 # brace initialization, there are more places where semicolons are # required than not, so we use a whitelist approach to check these # rather than a blacklist. These are the places where "};" should # be replaced by just "}": # 1. Some flavor of block following closing parenthesis: # for (;;) {}; # while (...) {}; # switch (...) {}; # Function(...) {}; # if (...) {}; # if (...) else if (...) {}; # # 2. else block: # if (...) else {}; # # 3. const member function: # Function(...) const {}; # # 4. Block following some statement: # x = 42; # {}; # # 5. Block at the beginning of a function: # Function(...) { # {}; # } # # Note that naively checking for the preceding "{" will also match # braces inside multi-dimensional arrays, but this is fine since # that expression will not contain semicolons. # # 6. Block following another block: # while (true) {} # {}; # # 7. End of namespaces: # namespace {}; # # These semicolons seems far more common than other kinds of # redundant semicolons, possibly due to people converting classes # to namespaces. For now we do not warn for this case. # # Try matching case 1 first. match = Match(r'^(.*\)\s*)\{', line) if match: # Matched closing parenthesis (case 1). Check the token before the # matching opening parenthesis, and don't warn if it looks like a # macro. This avoids these false positives: # - macro that defines a base class # - multi-line macro that defines a base class # - macro that defines the whole class-head # # But we still issue warnings for macros that we know are safe to # warn, specifically: # - TEST, TEST_F, TEST_P, MATCHER, MATCHER_P # - TYPED_TEST # - INTERFACE_DEF # - EXCLUSIVE_LOCKS_REQUIRED, SHARED_LOCKS_REQUIRED, LOCKS_EXCLUDED: # # We implement a whitelist of safe macros instead of a blacklist of # unsafe macros, even though the latter appears less frequently in # google code and would have been easier to implement. This is because # the downside for getting the whitelist wrong means some extra # semicolons, while the downside for getting the blacklist wrong # would result in compile errors. # # In addition to macros, we also don't want to warn on # - Compound literals # - Lambdas # - alignas specifier with anonymous structs # - decltype closing_brace_pos = match.group(1).rfind(')') opening_parenthesis = ReverseCloseExpression( clean_lines, linenum, closing_brace_pos) if opening_parenthesis[2] > -1: line_prefix = opening_parenthesis[0][0:opening_parenthesis[2]] macro = Search(r'\b([A-Z_][A-Z0-9_]*)\s*$', line_prefix) func = Match(r'^(.*\])\s*$', line_prefix) if ((macro and macro.group(1) not in ( 'TEST', 'TEST_F', 'MATCHER', 'MATCHER_P', 'TYPED_TEST', 'EXCLUSIVE_LOCKS_REQUIRED', 'SHARED_LOCKS_REQUIRED', 'LOCKS_EXCLUDED', 'INTERFACE_DEF')) or (func and not Search(r'\boperator\s*\[\s*\]', func.group(1))) or Search(r'\b(?:struct|union)\s+alignas\s*$', line_prefix) or Search(r'\bdecltype$', line_prefix) or Search(r'\s+=\s*$', line_prefix)): match = None if (match and opening_parenthesis[1] > 1 and Search(r'\]\s*$', clean_lines.elided[opening_parenthesis[1] - 1])): # Multi-line lambda-expression match = None else: # Try matching cases 2-3. match = Match(r'^(.*(?:else|\)\s*const)\s*)\{', line) if not match: # Try matching cases 4-6. These are always matched on separate lines. # # Note that we can't simply concatenate the previous line to the # current line and do a single match, otherwise we may output # duplicate warnings for the blank line case: # if (cond) { # // blank line # } prevline = GetPreviousNonBlankLine(clean_lines, linenum)[0] if prevline and Search(r'[;{}]\s*$', prevline): match = Match(r'^(\s*)\{', line) # Check matching closing brace if match: (endline, endlinenum, endpos) = CloseExpression( clean_lines, linenum, len(match.group(1))) if endpos > -1 and Match(r'^\s*;', endline[endpos:]): # Current {} pair is eligible for semicolon check, and we have found # the redundant semicolon, output warning here. # # Note: because we are scanning forward for opening braces, and # outputting warnings for the matching closing brace, if there are # nested blocks with trailing semicolons, we will get the error # messages in reversed order. # We need to check the line forward for NOLINT raw_lines = clean_lines.raw_lines ParseNolintSuppressions(filename, raw_lines[endlinenum-1], endlinenum-1, error) ParseNolintSuppressions(filename, raw_lines[endlinenum], endlinenum, error) error(filename, endlinenum, 'readability/braces', 4, "You don't need a ; after a }")
[ "def", "CheckTrailingSemicolon", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "error", ")", ":", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "# Block bodies should not be followed by a semicolon. Due to C++11", "# brace initialization, there are more places where semicolons are", "# required than not, so we use a whitelist approach to check these", "# rather than a blacklist. These are the places where \"};\" should", "# be replaced by just \"}\":", "# 1. Some flavor of block following closing parenthesis:", "# for (;;) {};", "# while (...) {};", "# switch (...) {};", "# Function(...) {};", "# if (...) {};", "# if (...) else if (...) {};", "#", "# 2. else block:", "# if (...) else {};", "#", "# 3. const member function:", "# Function(...) const {};", "#", "# 4. Block following some statement:", "# x = 42;", "# {};", "#", "# 5. Block at the beginning of a function:", "# Function(...) {", "# {};", "# }", "#", "# Note that naively checking for the preceding \"{\" will also match", "# braces inside multi-dimensional arrays, but this is fine since", "# that expression will not contain semicolons.", "#", "# 6. Block following another block:", "# while (true) {}", "# {};", "#", "# 7. End of namespaces:", "# namespace {};", "#", "# These semicolons seems far more common than other kinds of", "# redundant semicolons, possibly due to people converting classes", "# to namespaces. For now we do not warn for this case.", "#", "# Try matching case 1 first.", "match", "=", "Match", "(", "r'^(.*\\)\\s*)\\{'", ",", "line", ")", "if", "match", ":", "# Matched closing parenthesis (case 1). Check the token before the", "# matching opening parenthesis, and don't warn if it looks like a", "# macro. This avoids these false positives:", "# - macro that defines a base class", "# - multi-line macro that defines a base class", "# - macro that defines the whole class-head", "#", "# But we still issue warnings for macros that we know are safe to", "# warn, specifically:", "# - TEST, TEST_F, TEST_P, MATCHER, MATCHER_P", "# - TYPED_TEST", "# - INTERFACE_DEF", "# - EXCLUSIVE_LOCKS_REQUIRED, SHARED_LOCKS_REQUIRED, LOCKS_EXCLUDED:", "#", "# We implement a whitelist of safe macros instead of a blacklist of", "# unsafe macros, even though the latter appears less frequently in", "# google code and would have been easier to implement. This is because", "# the downside for getting the whitelist wrong means some extra", "# semicolons, while the downside for getting the blacklist wrong", "# would result in compile errors.", "#", "# In addition to macros, we also don't want to warn on", "# - Compound literals", "# - Lambdas", "# - alignas specifier with anonymous structs", "# - decltype", "closing_brace_pos", "=", "match", ".", "group", "(", "1", ")", ".", "rfind", "(", "')'", ")", "opening_parenthesis", "=", "ReverseCloseExpression", "(", "clean_lines", ",", "linenum", ",", "closing_brace_pos", ")", "if", "opening_parenthesis", "[", "2", "]", ">", "-", "1", ":", "line_prefix", "=", "opening_parenthesis", "[", "0", "]", "[", "0", ":", "opening_parenthesis", "[", "2", "]", "]", "macro", "=", "Search", "(", "r'\\b([A-Z_][A-Z0-9_]*)\\s*$'", ",", "line_prefix", ")", "func", "=", "Match", "(", "r'^(.*\\])\\s*$'", ",", "line_prefix", ")", "if", "(", "(", "macro", "and", "macro", ".", "group", "(", "1", ")", "not", "in", "(", "'TEST'", ",", "'TEST_F'", ",", "'MATCHER'", ",", "'MATCHER_P'", ",", "'TYPED_TEST'", ",", "'EXCLUSIVE_LOCKS_REQUIRED'", ",", "'SHARED_LOCKS_REQUIRED'", ",", "'LOCKS_EXCLUDED'", ",", "'INTERFACE_DEF'", ")", ")", "or", "(", "func", "and", "not", "Search", "(", "r'\\boperator\\s*\\[\\s*\\]'", ",", "func", ".", "group", "(", "1", ")", ")", ")", "or", "Search", "(", "r'\\b(?:struct|union)\\s+alignas\\s*$'", ",", "line_prefix", ")", "or", "Search", "(", "r'\\bdecltype$'", ",", "line_prefix", ")", "or", "Search", "(", "r'\\s+=\\s*$'", ",", "line_prefix", ")", ")", ":", "match", "=", "None", "if", "(", "match", "and", "opening_parenthesis", "[", "1", "]", ">", "1", "and", "Search", "(", "r'\\]\\s*$'", ",", "clean_lines", ".", "elided", "[", "opening_parenthesis", "[", "1", "]", "-", "1", "]", ")", ")", ":", "# Multi-line lambda-expression", "match", "=", "None", "else", ":", "# Try matching cases 2-3.", "match", "=", "Match", "(", "r'^(.*(?:else|\\)\\s*const)\\s*)\\{'", ",", "line", ")", "if", "not", "match", ":", "# Try matching cases 4-6. These are always matched on separate lines.", "#", "# Note that we can't simply concatenate the previous line to the", "# current line and do a single match, otherwise we may output", "# duplicate warnings for the blank line case:", "# if (cond) {", "# // blank line", "# }", "prevline", "=", "GetPreviousNonBlankLine", "(", "clean_lines", ",", "linenum", ")", "[", "0", "]", "if", "prevline", "and", "Search", "(", "r'[;{}]\\s*$'", ",", "prevline", ")", ":", "match", "=", "Match", "(", "r'^(\\s*)\\{'", ",", "line", ")", "# Check matching closing brace", "if", "match", ":", "(", "endline", ",", "endlinenum", ",", "endpos", ")", "=", "CloseExpression", "(", "clean_lines", ",", "linenum", ",", "len", "(", "match", ".", "group", "(", "1", ")", ")", ")", "if", "endpos", ">", "-", "1", "and", "Match", "(", "r'^\\s*;'", ",", "endline", "[", "endpos", ":", "]", ")", ":", "# Current {} pair is eligible for semicolon check, and we have found", "# the redundant semicolon, output warning here.", "#", "# Note: because we are scanning forward for opening braces, and", "# outputting warnings for the matching closing brace, if there are", "# nested blocks with trailing semicolons, we will get the error", "# messages in reversed order.", "# We need to check the line forward for NOLINT", "raw_lines", "=", "clean_lines", ".", "raw_lines", "ParseNolintSuppressions", "(", "filename", ",", "raw_lines", "[", "endlinenum", "-", "1", "]", ",", "endlinenum", "-", "1", ",", "error", ")", "ParseNolintSuppressions", "(", "filename", ",", "raw_lines", "[", "endlinenum", "]", ",", "endlinenum", ",", "error", ")", "error", "(", "filename", ",", "endlinenum", ",", "'readability/braces'", ",", "4", ",", "\"You don't need a ; after a }\"", ")" ]
https://github.com/asLody/whale/blob/6a661b27cc4cf83b7b5a3b02451597ee1ac7f264/whale/cpplint.py#L3855-L3999
cathywu/Sentiment-Analysis
eb501fd1375c0c3f3ab430f963255f1bb858e659
PyML-0.7.9/PyML/classifiers/random_forests.py
python
RF.cleanup
(self)
return
remove the directory that was created using training/testing
remove the directory that was created using training/testing
[ "remove", "the", "directory", "that", "was", "created", "using", "training", "/", "testing" ]
def cleanup(self) : """remove the directory that was created using training/testing""" return directory = self.trainingDirectory if directory is None : return if os.path.exists(directory) : os.system('rm -rf ' + directory)
[ "def", "cleanup", "(", "self", ")", ":", "return", "directory", "=", "self", ".", "trainingDirectory", "if", "directory", "is", "None", ":", "return", "if", "os", ".", "path", ".", "exists", "(", "directory", ")", ":", "os", ".", "system", "(", "'rm -rf '", "+", "directory", ")" ]
https://github.com/cathywu/Sentiment-Analysis/blob/eb501fd1375c0c3f3ab430f963255f1bb858e659/PyML-0.7.9/PyML/classifiers/random_forests.py#L179-L185
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/email/_header_value_parser.py
python
get_mailbox_list
(value)
return mailbox_list, value
mailbox-list = (mailbox *("," mailbox)) / obs-mbox-list obs-mbox-list = *([CFWS] ",") mailbox *("," [mailbox / CFWS]) For this routine we go outside the formal grammar in order to improve error handling. We recognize the end of the mailbox list only at the end of the value or at a ';' (the group terminator). This is so that we can turn invalid mailboxes into InvalidMailbox tokens and continue parsing any remaining valid mailboxes. We also allow all mailbox entries to be null, and this condition is handled appropriately at a higher level.
mailbox-list = (mailbox *("," mailbox)) / obs-mbox-list obs-mbox-list = *([CFWS] ",") mailbox *("," [mailbox / CFWS])
[ "mailbox", "-", "list", "=", "(", "mailbox", "*", "(", "mailbox", "))", "/", "obs", "-", "mbox", "-", "list", "obs", "-", "mbox", "-", "list", "=", "*", "(", "[", "CFWS", "]", ")", "mailbox", "*", "(", "[", "mailbox", "/", "CFWS", "]", ")" ]
def get_mailbox_list(value): """ mailbox-list = (mailbox *("," mailbox)) / obs-mbox-list obs-mbox-list = *([CFWS] ",") mailbox *("," [mailbox / CFWS]) For this routine we go outside the formal grammar in order to improve error handling. We recognize the end of the mailbox list only at the end of the value or at a ';' (the group terminator). This is so that we can turn invalid mailboxes into InvalidMailbox tokens and continue parsing any remaining valid mailboxes. We also allow all mailbox entries to be null, and this condition is handled appropriately at a higher level. """ mailbox_list = MailboxList() while value and value[0] != ';': try: token, value = get_mailbox(value) mailbox_list.append(token) except errors.HeaderParseError: leader = None if value[0] in CFWS_LEADER: leader, value = get_cfws(value) if not value or value[0] in ',;': mailbox_list.append(leader) mailbox_list.defects.append(errors.ObsoleteHeaderDefect( "empty element in mailbox-list")) else: token, value = get_invalid_mailbox(value, ',;') if leader is not None: token[:0] = [leader] mailbox_list.append(token) mailbox_list.defects.append(errors.InvalidHeaderDefect( "invalid mailbox in mailbox-list")) elif value[0] == ',': mailbox_list.defects.append(errors.ObsoleteHeaderDefect( "empty element in mailbox-list")) else: token, value = get_invalid_mailbox(value, ',;') if leader is not None: token[:0] = [leader] mailbox_list.append(token) mailbox_list.defects.append(errors.InvalidHeaderDefect( "invalid mailbox in mailbox-list")) if value and value[0] not in ',;': # Crap after mailbox; treat it as an invalid mailbox. # The mailbox info will still be available. mailbox = mailbox_list[-1] mailbox.token_type = 'invalid-mailbox' token, value = get_invalid_mailbox(value, ',;') mailbox.extend(token) mailbox_list.defects.append(errors.InvalidHeaderDefect( "invalid mailbox in mailbox-list")) if value and value[0] == ',': mailbox_list.append(ListSeparator) value = value[1:] return mailbox_list, value
[ "def", "get_mailbox_list", "(", "value", ")", ":", "mailbox_list", "=", "MailboxList", "(", ")", "while", "value", "and", "value", "[", "0", "]", "!=", "';'", ":", "try", ":", "token", ",", "value", "=", "get_mailbox", "(", "value", ")", "mailbox_list", ".", "append", "(", "token", ")", "except", "errors", ".", "HeaderParseError", ":", "leader", "=", "None", "if", "value", "[", "0", "]", "in", "CFWS_LEADER", ":", "leader", ",", "value", "=", "get_cfws", "(", "value", ")", "if", "not", "value", "or", "value", "[", "0", "]", "in", "',;'", ":", "mailbox_list", ".", "append", "(", "leader", ")", "mailbox_list", ".", "defects", ".", "append", "(", "errors", ".", "ObsoleteHeaderDefect", "(", "\"empty element in mailbox-list\"", ")", ")", "else", ":", "token", ",", "value", "=", "get_invalid_mailbox", "(", "value", ",", "',;'", ")", "if", "leader", "is", "not", "None", ":", "token", "[", ":", "0", "]", "=", "[", "leader", "]", "mailbox_list", ".", "append", "(", "token", ")", "mailbox_list", ".", "defects", ".", "append", "(", "errors", ".", "InvalidHeaderDefect", "(", "\"invalid mailbox in mailbox-list\"", ")", ")", "elif", "value", "[", "0", "]", "==", "','", ":", "mailbox_list", ".", "defects", ".", "append", "(", "errors", ".", "ObsoleteHeaderDefect", "(", "\"empty element in mailbox-list\"", ")", ")", "else", ":", "token", ",", "value", "=", "get_invalid_mailbox", "(", "value", ",", "',;'", ")", "if", "leader", "is", "not", "None", ":", "token", "[", ":", "0", "]", "=", "[", "leader", "]", "mailbox_list", ".", "append", "(", "token", ")", "mailbox_list", ".", "defects", ".", "append", "(", "errors", ".", "InvalidHeaderDefect", "(", "\"invalid mailbox in mailbox-list\"", ")", ")", "if", "value", "and", "value", "[", "0", "]", "not", "in", "',;'", ":", "# Crap after mailbox; treat it as an invalid mailbox.", "# The mailbox info will still be available.", "mailbox", "=", "mailbox_list", "[", "-", "1", "]", "mailbox", ".", "token_type", "=", "'invalid-mailbox'", "token", ",", "value", "=", "get_invalid_mailbox", "(", "value", ",", "',;'", ")", "mailbox", ".", "extend", "(", "token", ")", "mailbox_list", ".", "defects", ".", "append", "(", "errors", ".", "InvalidHeaderDefect", "(", "\"invalid mailbox in mailbox-list\"", ")", ")", "if", "value", "and", "value", "[", "0", "]", "==", "','", ":", "mailbox_list", ".", "append", "(", "ListSeparator", ")", "value", "=", "value", "[", "1", ":", "]", "return", "mailbox_list", ",", "value" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/email/_header_value_parser.py#L1822-L1876
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/py3/scipy/interpolate/ndgriddata.py
python
griddata
(points, values, xi, method='linear', fill_value=np.nan, rescale=False)
Interpolate unstructured D-dimensional data. Parameters ---------- points : ndarray of floats, shape (n, D) Data point coordinates. Can either be an array of shape (n, D), or a tuple of `ndim` arrays. values : ndarray of float or complex, shape (n,) Data values. xi : 2-D ndarray of float or tuple of 1-D array, shape (M, D) Points at which to interpolate data. method : {'linear', 'nearest', 'cubic'}, optional Method of interpolation. One of ``nearest`` return the value at the data point closest to the point of interpolation. See `NearestNDInterpolator` for more details. ``linear`` tessellate the input point set to n-dimensional simplices, and interpolate linearly on each simplex. See `LinearNDInterpolator` for more details. ``cubic`` (1-D) return the value determined from a cubic spline. ``cubic`` (2-D) return the value determined from a piecewise cubic, continuously differentiable (C1), and approximately curvature-minimizing polynomial surface. See `CloughTocher2DInterpolator` for more details. fill_value : float, optional Value used to fill in for requested points outside of the convex hull of the input points. If not provided, then the default is ``nan``. This option has no effect for the 'nearest' method. rescale : bool, optional Rescale points to unit cube before performing interpolation. This is useful if some of the input dimensions have incommensurable units and differ by many orders of magnitude. .. versionadded:: 0.14.0 Returns ------- ndarray Array of interpolated values. Notes ----- .. versionadded:: 0.9 Examples -------- Suppose we want to interpolate the 2-D function >>> def func(x, y): ... return x*(1-x)*np.cos(4*np.pi*x) * np.sin(4*np.pi*y**2)**2 on a grid in [0, 1]x[0, 1] >>> grid_x, grid_y = np.mgrid[0:1:100j, 0:1:200j] but we only know its values at 1000 data points: >>> points = np.random.rand(1000, 2) >>> values = func(points[:,0], points[:,1]) This can be done with `griddata` -- below we try out all of the interpolation methods: >>> from scipy.interpolate import griddata >>> grid_z0 = griddata(points, values, (grid_x, grid_y), method='nearest') >>> grid_z1 = griddata(points, values, (grid_x, grid_y), method='linear') >>> grid_z2 = griddata(points, values, (grid_x, grid_y), method='cubic') One can see that the exact result is reproduced by all of the methods to some degree, but for this smooth function the piecewise cubic interpolant gives the best results: >>> import matplotlib.pyplot as plt >>> plt.subplot(221) >>> plt.imshow(func(grid_x, grid_y).T, extent=(0,1,0,1), origin='lower') >>> plt.plot(points[:,0], points[:,1], 'k.', ms=1) >>> plt.title('Original') >>> plt.subplot(222) >>> plt.imshow(grid_z0.T, extent=(0,1,0,1), origin='lower') >>> plt.title('Nearest') >>> plt.subplot(223) >>> plt.imshow(grid_z1.T, extent=(0,1,0,1), origin='lower') >>> plt.title('Linear') >>> plt.subplot(224) >>> plt.imshow(grid_z2.T, extent=(0,1,0,1), origin='lower') >>> plt.title('Cubic') >>> plt.gcf().set_size_inches(6, 6) >>> plt.show()
Interpolate unstructured D-dimensional data.
[ "Interpolate", "unstructured", "D", "-", "dimensional", "data", "." ]
def griddata(points, values, xi, method='linear', fill_value=np.nan, rescale=False): """ Interpolate unstructured D-dimensional data. Parameters ---------- points : ndarray of floats, shape (n, D) Data point coordinates. Can either be an array of shape (n, D), or a tuple of `ndim` arrays. values : ndarray of float or complex, shape (n,) Data values. xi : 2-D ndarray of float or tuple of 1-D array, shape (M, D) Points at which to interpolate data. method : {'linear', 'nearest', 'cubic'}, optional Method of interpolation. One of ``nearest`` return the value at the data point closest to the point of interpolation. See `NearestNDInterpolator` for more details. ``linear`` tessellate the input point set to n-dimensional simplices, and interpolate linearly on each simplex. See `LinearNDInterpolator` for more details. ``cubic`` (1-D) return the value determined from a cubic spline. ``cubic`` (2-D) return the value determined from a piecewise cubic, continuously differentiable (C1), and approximately curvature-minimizing polynomial surface. See `CloughTocher2DInterpolator` for more details. fill_value : float, optional Value used to fill in for requested points outside of the convex hull of the input points. If not provided, then the default is ``nan``. This option has no effect for the 'nearest' method. rescale : bool, optional Rescale points to unit cube before performing interpolation. This is useful if some of the input dimensions have incommensurable units and differ by many orders of magnitude. .. versionadded:: 0.14.0 Returns ------- ndarray Array of interpolated values. Notes ----- .. versionadded:: 0.9 Examples -------- Suppose we want to interpolate the 2-D function >>> def func(x, y): ... return x*(1-x)*np.cos(4*np.pi*x) * np.sin(4*np.pi*y**2)**2 on a grid in [0, 1]x[0, 1] >>> grid_x, grid_y = np.mgrid[0:1:100j, 0:1:200j] but we only know its values at 1000 data points: >>> points = np.random.rand(1000, 2) >>> values = func(points[:,0], points[:,1]) This can be done with `griddata` -- below we try out all of the interpolation methods: >>> from scipy.interpolate import griddata >>> grid_z0 = griddata(points, values, (grid_x, grid_y), method='nearest') >>> grid_z1 = griddata(points, values, (grid_x, grid_y), method='linear') >>> grid_z2 = griddata(points, values, (grid_x, grid_y), method='cubic') One can see that the exact result is reproduced by all of the methods to some degree, but for this smooth function the piecewise cubic interpolant gives the best results: >>> import matplotlib.pyplot as plt >>> plt.subplot(221) >>> plt.imshow(func(grid_x, grid_y).T, extent=(0,1,0,1), origin='lower') >>> plt.plot(points[:,0], points[:,1], 'k.', ms=1) >>> plt.title('Original') >>> plt.subplot(222) >>> plt.imshow(grid_z0.T, extent=(0,1,0,1), origin='lower') >>> plt.title('Nearest') >>> plt.subplot(223) >>> plt.imshow(grid_z1.T, extent=(0,1,0,1), origin='lower') >>> plt.title('Linear') >>> plt.subplot(224) >>> plt.imshow(grid_z2.T, extent=(0,1,0,1), origin='lower') >>> plt.title('Cubic') >>> plt.gcf().set_size_inches(6, 6) >>> plt.show() """ points = _ndim_coords_from_arrays(points) if points.ndim < 2: ndim = points.ndim else: ndim = points.shape[-1] if ndim == 1 and method in ('nearest', 'linear', 'cubic'): from .interpolate import interp1d points = points.ravel() if isinstance(xi, tuple): if len(xi) != 1: raise ValueError("invalid number of dimensions in xi") xi, = xi # Sort points/values together, necessary as input for interp1d idx = np.argsort(points) points = points[idx] values = values[idx] if method == 'nearest': fill_value = 'extrapolate' ip = interp1d(points, values, kind=method, axis=0, bounds_error=False, fill_value=fill_value) return ip(xi) elif method == 'nearest': ip = NearestNDInterpolator(points, values, rescale=rescale) return ip(xi) elif method == 'linear': ip = LinearNDInterpolator(points, values, fill_value=fill_value, rescale=rescale) return ip(xi) elif method == 'cubic' and ndim == 2: ip = CloughTocher2DInterpolator(points, values, fill_value=fill_value, rescale=rescale) return ip(xi) else: raise ValueError("Unknown interpolation method %r for " "%d dimensional data" % (method, ndim))
[ "def", "griddata", "(", "points", ",", "values", ",", "xi", ",", "method", "=", "'linear'", ",", "fill_value", "=", "np", ".", "nan", ",", "rescale", "=", "False", ")", ":", "points", "=", "_ndim_coords_from_arrays", "(", "points", ")", "if", "points", ".", "ndim", "<", "2", ":", "ndim", "=", "points", ".", "ndim", "else", ":", "ndim", "=", "points", ".", "shape", "[", "-", "1", "]", "if", "ndim", "==", "1", "and", "method", "in", "(", "'nearest'", ",", "'linear'", ",", "'cubic'", ")", ":", "from", ".", "interpolate", "import", "interp1d", "points", "=", "points", ".", "ravel", "(", ")", "if", "isinstance", "(", "xi", ",", "tuple", ")", ":", "if", "len", "(", "xi", ")", "!=", "1", ":", "raise", "ValueError", "(", "\"invalid number of dimensions in xi\"", ")", "xi", ",", "=", "xi", "# Sort points/values together, necessary as input for interp1d", "idx", "=", "np", ".", "argsort", "(", "points", ")", "points", "=", "points", "[", "idx", "]", "values", "=", "values", "[", "idx", "]", "if", "method", "==", "'nearest'", ":", "fill_value", "=", "'extrapolate'", "ip", "=", "interp1d", "(", "points", ",", "values", ",", "kind", "=", "method", ",", "axis", "=", "0", ",", "bounds_error", "=", "False", ",", "fill_value", "=", "fill_value", ")", "return", "ip", "(", "xi", ")", "elif", "method", "==", "'nearest'", ":", "ip", "=", "NearestNDInterpolator", "(", "points", ",", "values", ",", "rescale", "=", "rescale", ")", "return", "ip", "(", "xi", ")", "elif", "method", "==", "'linear'", ":", "ip", "=", "LinearNDInterpolator", "(", "points", ",", "values", ",", "fill_value", "=", "fill_value", ",", "rescale", "=", "rescale", ")", "return", "ip", "(", "xi", ")", "elif", "method", "==", "'cubic'", "and", "ndim", "==", "2", ":", "ip", "=", "CloughTocher2DInterpolator", "(", "points", ",", "values", ",", "fill_value", "=", "fill_value", ",", "rescale", "=", "rescale", ")", "return", "ip", "(", "xi", ")", "else", ":", "raise", "ValueError", "(", "\"Unknown interpolation method %r for \"", "\"%d dimensional data\"", "%", "(", "method", ",", "ndim", ")", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py3/scipy/interpolate/ndgriddata.py#L88-L230
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
qt/python/mantidqt/mantidqt/widgets/samplelogs/view.py
python
SampleLogsView.get_selected_row_indexes
(self)
return [row.row() for row in self.table.selectionModel().selectedRows()]
Return a list of selected row from table
Return a list of selected row from table
[ "Return", "a", "list", "of", "selected", "row", "from", "table" ]
def get_selected_row_indexes(self): """Return a list of selected row from table""" return [row.row() for row in self.table.selectionModel().selectedRows()]
[ "def", "get_selected_row_indexes", "(", "self", ")", ":", "return", "[", "row", ".", "row", "(", ")", "for", "row", "in", "self", ".", "table", ".", "selectionModel", "(", ")", ".", "selectedRows", "(", ")", "]" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqt/mantidqt/widgets/samplelogs/view.py#L212-L214
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/ops/gradient_checker_v2.py
python
_to_numpy
(a)
return a
Converts Tensors, EagerTensors, and IndexedSlicesValue to numpy arrays. Args: a: any value. Returns: If a is EagerTensor or Tensor, returns the evaluation of a by calling numpy() or run(). If a is IndexedSlicesValue, constructs the corresponding dense numpy array. Otherwise returns a unchanged.
Converts Tensors, EagerTensors, and IndexedSlicesValue to numpy arrays.
[ "Converts", "Tensors", "EagerTensors", "and", "IndexedSlicesValue", "to", "numpy", "arrays", "." ]
def _to_numpy(a): """Converts Tensors, EagerTensors, and IndexedSlicesValue to numpy arrays. Args: a: any value. Returns: If a is EagerTensor or Tensor, returns the evaluation of a by calling numpy() or run(). If a is IndexedSlicesValue, constructs the corresponding dense numpy array. Otherwise returns a unchanged. """ if isinstance(a, ops.EagerTensor): return a.numpy() if isinstance(a, ops.Tensor): sess = ops.get_default_session() return sess.run(a) if isinstance(a, indexed_slices.IndexedSlicesValue): arr = np.zeros(a.dense_shape) assert len(a.values) == len(a.indices), ( "IndexedSlicesValue has %s value slices but %s indices\n%s" % (a.values, a.indices, a)) for values_slice, index in zip(a.values, a.indices): assert 0 <= index < len(arr), ( "IndexedSlicesValue has invalid index %s\n%s" % (index, a)) arr[index] += values_slice return arr return a
[ "def", "_to_numpy", "(", "a", ")", ":", "if", "isinstance", "(", "a", ",", "ops", ".", "EagerTensor", ")", ":", "return", "a", ".", "numpy", "(", ")", "if", "isinstance", "(", "a", ",", "ops", ".", "Tensor", ")", ":", "sess", "=", "ops", ".", "get_default_session", "(", ")", "return", "sess", ".", "run", "(", "a", ")", "if", "isinstance", "(", "a", ",", "indexed_slices", ".", "IndexedSlicesValue", ")", ":", "arr", "=", "np", ".", "zeros", "(", "a", ".", "dense_shape", ")", "assert", "len", "(", "a", ".", "values", ")", "==", "len", "(", "a", ".", "indices", ")", ",", "(", "\"IndexedSlicesValue has %s value slices but %s indices\\n%s\"", "%", "(", "a", ".", "values", ",", "a", ".", "indices", ",", "a", ")", ")", "for", "values_slice", ",", "index", "in", "zip", "(", "a", ".", "values", ",", "a", ".", "indices", ")", ":", "assert", "0", "<=", "index", "<", "len", "(", "arr", ")", ",", "(", "\"IndexedSlicesValue has invalid index %s\\n%s\"", "%", "(", "index", ",", "a", ")", ")", "arr", "[", "index", "]", "+=", "values_slice", "return", "arr", "return", "a" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/gradient_checker_v2.py#L64-L90
apple/turicreate
cce55aa5311300e3ce6af93cb45ba791fd1bdf49
src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/python_message.py
python
_GetFieldByName
(message_descriptor, field_name)
Returns a field descriptor by field name. Args: message_descriptor: A Descriptor describing all fields in message. field_name: The name of the field to retrieve. Returns: The field descriptor associated with the field name.
Returns a field descriptor by field name.
[ "Returns", "a", "field", "descriptor", "by", "field", "name", "." ]
def _GetFieldByName(message_descriptor, field_name): """Returns a field descriptor by field name. Args: message_descriptor: A Descriptor describing all fields in message. field_name: The name of the field to retrieve. Returns: The field descriptor associated with the field name. """ try: return message_descriptor.fields_by_name[field_name] except KeyError: raise ValueError('Protocol message %s has no "%s" field.' % (message_descriptor.name, field_name))
[ "def", "_GetFieldByName", "(", "message_descriptor", ",", "field_name", ")", ":", "try", ":", "return", "message_descriptor", ".", "fields_by_name", "[", "field_name", "]", "except", "KeyError", ":", "raise", "ValueError", "(", "'Protocol message %s has no \"%s\" field.'", "%", "(", "message_descriptor", ".", "name", ",", "field_name", ")", ")" ]
https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/python_message.py#L534-L547
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/series.py
python
Series.diff
(self, periods=1)
return self._constructor(result, index=self.index).__finalize__(self)
First discrete difference of element. Calculates the difference of a Series element compared with another element in the Series (default is element in previous row). Parameters ---------- periods : int, default 1 Periods to shift for calculating difference, accepts negative values. Returns ------- Series First differences of the Series. See Also -------- Series.pct_change: Percent change over given number of periods. Series.shift: Shift index by desired number of periods with an optional time freq. DataFrame.diff: First discrete difference of object. Notes ----- For boolean dtypes, this uses :meth:`operator.xor` rather than :meth:`operator.sub`. Examples -------- Difference with previous row >>> s = pd.Series([1, 1, 2, 3, 5, 8]) >>> s.diff() 0 NaN 1 0.0 2 1.0 3 1.0 4 2.0 5 3.0 dtype: float64 Difference with 3rd previous row >>> s.diff(periods=3) 0 NaN 1 NaN 2 NaN 3 2.0 4 4.0 5 6.0 dtype: float64 Difference with following row >>> s.diff(periods=-1) 0 0.0 1 -1.0 2 -1.0 3 -2.0 4 -3.0 5 NaN dtype: float64
First discrete difference of element.
[ "First", "discrete", "difference", "of", "element", "." ]
def diff(self, periods=1): """ First discrete difference of element. Calculates the difference of a Series element compared with another element in the Series (default is element in previous row). Parameters ---------- periods : int, default 1 Periods to shift for calculating difference, accepts negative values. Returns ------- Series First differences of the Series. See Also -------- Series.pct_change: Percent change over given number of periods. Series.shift: Shift index by desired number of periods with an optional time freq. DataFrame.diff: First discrete difference of object. Notes ----- For boolean dtypes, this uses :meth:`operator.xor` rather than :meth:`operator.sub`. Examples -------- Difference with previous row >>> s = pd.Series([1, 1, 2, 3, 5, 8]) >>> s.diff() 0 NaN 1 0.0 2 1.0 3 1.0 4 2.0 5 3.0 dtype: float64 Difference with 3rd previous row >>> s.diff(periods=3) 0 NaN 1 NaN 2 NaN 3 2.0 4 4.0 5 6.0 dtype: float64 Difference with following row >>> s.diff(periods=-1) 0 0.0 1 -1.0 2 -1.0 3 -2.0 4 -3.0 5 NaN dtype: float64 """ result = algorithms.diff(self.array, periods) return self._constructor(result, index=self.index).__finalize__(self)
[ "def", "diff", "(", "self", ",", "periods", "=", "1", ")", ":", "result", "=", "algorithms", ".", "diff", "(", "self", ".", "array", ",", "periods", ")", "return", "self", ".", "_constructor", "(", "result", ",", "index", "=", "self", ".", "index", ")", ".", "__finalize__", "(", "self", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/series.py#L2292-L2359
hughperkins/tf-coriander
970d3df6c11400ad68405f22b0c42a52374e94ca
tensorflow/python/ops/nn_grad.py
python
_BatchNormWithGlobalNormalizationGrad
(op, grad)
return dx, dm, dv, db, dg
Return the gradients for the 5 inputs of BatchNormWithGlobalNormalization. We do not backprop anything for the mean and var intentionally as they are not being trained with backprop in the operation. Args: op: The BatchNormOp for which we need to generate gradients. grad: Tensor. The gradients passed to the BatchNormOp. Returns: dx: Backprop for input, which is (grad * (g * rsqrt(v + epsilon))) dm: Backprop for mean, which is sum_over_rest(grad * g) * (-1 / rsqrt(v + epsilon)) dv: Backprop for variance, which is sum_over_rest(grad * g * (x - m)) * (-1/2) * (v + epsilon) ^ (-3/2) db: Backprop for beta, which is grad reduced in all except the last dimension. dg: Backprop for gamma, which is (grad * ((x - m) * rsqrt(v + epsilon)))
Return the gradients for the 5 inputs of BatchNormWithGlobalNormalization.
[ "Return", "the", "gradients", "for", "the", "5", "inputs", "of", "BatchNormWithGlobalNormalization", "." ]
def _BatchNormWithGlobalNormalizationGrad(op, grad): """Return the gradients for the 5 inputs of BatchNormWithGlobalNormalization. We do not backprop anything for the mean and var intentionally as they are not being trained with backprop in the operation. Args: op: The BatchNormOp for which we need to generate gradients. grad: Tensor. The gradients passed to the BatchNormOp. Returns: dx: Backprop for input, which is (grad * (g * rsqrt(v + epsilon))) dm: Backprop for mean, which is sum_over_rest(grad * g) * (-1 / rsqrt(v + epsilon)) dv: Backprop for variance, which is sum_over_rest(grad * g * (x - m)) * (-1/2) * (v + epsilon) ^ (-3/2) db: Backprop for beta, which is grad reduced in all except the last dimension. dg: Backprop for gamma, which is (grad * ((x - m) * rsqrt(v + epsilon))) """ dx, dm, dv, db, dg = gen_nn_ops._batch_norm_with_global_normalization_grad( op.inputs[0], op.inputs[1], op.inputs[2], op.inputs[4], grad, op.get_attr("variance_epsilon"), op.get_attr("scale_after_normalization")) return dx, dm, dv, db, dg
[ "def", "_BatchNormWithGlobalNormalizationGrad", "(", "op", ",", "grad", ")", ":", "dx", ",", "dm", ",", "dv", ",", "db", ",", "dg", "=", "gen_nn_ops", ".", "_batch_norm_with_global_normalization_grad", "(", "op", ".", "inputs", "[", "0", "]", ",", "op", ".", "inputs", "[", "1", "]", ",", "op", ".", "inputs", "[", "2", "]", ",", "op", ".", "inputs", "[", "4", "]", ",", "grad", ",", "op", ".", "get_attr", "(", "\"variance_epsilon\"", ")", ",", "op", ".", "get_attr", "(", "\"scale_after_normalization\"", ")", ")", "return", "dx", ",", "dm", ",", "dv", ",", "db", ",", "dg" ]
https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/python/ops/nn_grad.py#L449-L472
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/setuptools/py3/pkg_resources/_vendor/pyparsing.py
python
indentedBlock
(blockStatementExpr, indentStack, indent=True)
return smExpr.setName('indented block')
Helper method for defining space-delimited indentation blocks, such as those used to define block statements in Python source code. Parameters: - blockStatementExpr - expression defining syntax of statement that is repeated within the indented block - indentStack - list created by caller to manage indentation stack (multiple statementWithIndentedBlock expressions within a single grammar should share a common indentStack) - indent - boolean indicating whether block must be indented beyond the the current level; set to False for block of left-most statements (default=C{True}) A valid block must contain at least one C{blockStatement}. Example:: data = ''' def A(z): A1 B = 100 G = A2 A2 A3 B def BB(a,b,c): BB1 def BBA(): bba1 bba2 bba3 C D def spam(x,y): def eggs(z): pass ''' indentStack = [1] stmt = Forward() identifier = Word(alphas, alphanums) funcDecl = ("def" + identifier + Group( "(" + Optional( delimitedList(identifier) ) + ")" ) + ":") func_body = indentedBlock(stmt, indentStack) funcDef = Group( funcDecl + func_body ) rvalue = Forward() funcCall = Group(identifier + "(" + Optional(delimitedList(rvalue)) + ")") rvalue << (funcCall | identifier | Word(nums)) assignment = Group(identifier + "=" + rvalue) stmt << ( funcDef | assignment | identifier ) module_body = OneOrMore(stmt) parseTree = module_body.parseString(data) parseTree.pprint() prints:: [['def', 'A', ['(', 'z', ')'], ':', [['A1'], [['B', '=', '100']], [['G', '=', 'A2']], ['A2'], ['A3']]], 'B', ['def', 'BB', ['(', 'a', 'b', 'c', ')'], ':', [['BB1'], [['def', 'BBA', ['(', ')'], ':', [['bba1'], ['bba2'], ['bba3']]]]]], 'C', 'D', ['def', 'spam', ['(', 'x', 'y', ')'], ':', [[['def', 'eggs', ['(', 'z', ')'], ':', [['pass']]]]]]]
Helper method for defining space-delimited indentation blocks, such as those used to define block statements in Python source code.
[ "Helper", "method", "for", "defining", "space", "-", "delimited", "indentation", "blocks", "such", "as", "those", "used", "to", "define", "block", "statements", "in", "Python", "source", "code", "." ]
def indentedBlock(blockStatementExpr, indentStack, indent=True): """ Helper method for defining space-delimited indentation blocks, such as those used to define block statements in Python source code. Parameters: - blockStatementExpr - expression defining syntax of statement that is repeated within the indented block - indentStack - list created by caller to manage indentation stack (multiple statementWithIndentedBlock expressions within a single grammar should share a common indentStack) - indent - boolean indicating whether block must be indented beyond the the current level; set to False for block of left-most statements (default=C{True}) A valid block must contain at least one C{blockStatement}. Example:: data = ''' def A(z): A1 B = 100 G = A2 A2 A3 B def BB(a,b,c): BB1 def BBA(): bba1 bba2 bba3 C D def spam(x,y): def eggs(z): pass ''' indentStack = [1] stmt = Forward() identifier = Word(alphas, alphanums) funcDecl = ("def" + identifier + Group( "(" + Optional( delimitedList(identifier) ) + ")" ) + ":") func_body = indentedBlock(stmt, indentStack) funcDef = Group( funcDecl + func_body ) rvalue = Forward() funcCall = Group(identifier + "(" + Optional(delimitedList(rvalue)) + ")") rvalue << (funcCall | identifier | Word(nums)) assignment = Group(identifier + "=" + rvalue) stmt << ( funcDef | assignment | identifier ) module_body = OneOrMore(stmt) parseTree = module_body.parseString(data) parseTree.pprint() prints:: [['def', 'A', ['(', 'z', ')'], ':', [['A1'], [['B', '=', '100']], [['G', '=', 'A2']], ['A2'], ['A3']]], 'B', ['def', 'BB', ['(', 'a', 'b', 'c', ')'], ':', [['BB1'], [['def', 'BBA', ['(', ')'], ':', [['bba1'], ['bba2'], ['bba3']]]]]], 'C', 'D', ['def', 'spam', ['(', 'x', 'y', ')'], ':', [[['def', 'eggs', ['(', 'z', ')'], ':', [['pass']]]]]]] """ def checkPeerIndent(s,l,t): if l >= len(s): return curCol = col(l,s) if curCol != indentStack[-1]: if curCol > indentStack[-1]: raise ParseFatalException(s,l,"illegal nesting") raise ParseException(s,l,"not a peer entry") def checkSubIndent(s,l,t): curCol = col(l,s) if curCol > indentStack[-1]: indentStack.append( curCol ) else: raise ParseException(s,l,"not a subentry") def checkUnindent(s,l,t): if l >= len(s): return curCol = col(l,s) if not(indentStack and curCol < indentStack[-1] and curCol <= indentStack[-2]): raise ParseException(s,l,"not an unindent") indentStack.pop() NL = OneOrMore(LineEnd().setWhitespaceChars("\t ").suppress()) INDENT = (Empty() + Empty().setParseAction(checkSubIndent)).setName('INDENT') PEER = Empty().setParseAction(checkPeerIndent).setName('') UNDENT = Empty().setParseAction(checkUnindent).setName('UNINDENT') if indent: smExpr = Group( Optional(NL) + #~ FollowedBy(blockStatementExpr) + INDENT + (OneOrMore( PEER + Group(blockStatementExpr) + Optional(NL) )) + UNDENT) else: smExpr = Group( Optional(NL) + (OneOrMore( PEER + Group(blockStatementExpr) + Optional(NL) )) ) blockStatementExpr.ignore(_bslash + LineEnd()) return smExpr.setName('indented block')
[ "def", "indentedBlock", "(", "blockStatementExpr", ",", "indentStack", ",", "indent", "=", "True", ")", ":", "def", "checkPeerIndent", "(", "s", ",", "l", ",", "t", ")", ":", "if", "l", ">=", "len", "(", "s", ")", ":", "return", "curCol", "=", "col", "(", "l", ",", "s", ")", "if", "curCol", "!=", "indentStack", "[", "-", "1", "]", ":", "if", "curCol", ">", "indentStack", "[", "-", "1", "]", ":", "raise", "ParseFatalException", "(", "s", ",", "l", ",", "\"illegal nesting\"", ")", "raise", "ParseException", "(", "s", ",", "l", ",", "\"not a peer entry\"", ")", "def", "checkSubIndent", "(", "s", ",", "l", ",", "t", ")", ":", "curCol", "=", "col", "(", "l", ",", "s", ")", "if", "curCol", ">", "indentStack", "[", "-", "1", "]", ":", "indentStack", ".", "append", "(", "curCol", ")", "else", ":", "raise", "ParseException", "(", "s", ",", "l", ",", "\"not a subentry\"", ")", "def", "checkUnindent", "(", "s", ",", "l", ",", "t", ")", ":", "if", "l", ">=", "len", "(", "s", ")", ":", "return", "curCol", "=", "col", "(", "l", ",", "s", ")", "if", "not", "(", "indentStack", "and", "curCol", "<", "indentStack", "[", "-", "1", "]", "and", "curCol", "<=", "indentStack", "[", "-", "2", "]", ")", ":", "raise", "ParseException", "(", "s", ",", "l", ",", "\"not an unindent\"", ")", "indentStack", ".", "pop", "(", ")", "NL", "=", "OneOrMore", "(", "LineEnd", "(", ")", ".", "setWhitespaceChars", "(", "\"\\t \"", ")", ".", "suppress", "(", ")", ")", "INDENT", "=", "(", "Empty", "(", ")", "+", "Empty", "(", ")", ".", "setParseAction", "(", "checkSubIndent", ")", ")", ".", "setName", "(", "'INDENT'", ")", "PEER", "=", "Empty", "(", ")", ".", "setParseAction", "(", "checkPeerIndent", ")", ".", "setName", "(", "''", ")", "UNDENT", "=", "Empty", "(", ")", ".", "setParseAction", "(", "checkUnindent", ")", ".", "setName", "(", "'UNINDENT'", ")", "if", "indent", ":", "smExpr", "=", "Group", "(", "Optional", "(", "NL", ")", "+", "#~ FollowedBy(blockStatementExpr) +", "INDENT", "+", "(", "OneOrMore", "(", "PEER", "+", "Group", "(", "blockStatementExpr", ")", "+", "Optional", "(", "NL", ")", ")", ")", "+", "UNDENT", ")", "else", ":", "smExpr", "=", "Group", "(", "Optional", "(", "NL", ")", "+", "(", "OneOrMore", "(", "PEER", "+", "Group", "(", "blockStatementExpr", ")", "+", "Optional", "(", "NL", ")", ")", ")", ")", "blockStatementExpr", ".", "ignore", "(", "_bslash", "+", "LineEnd", "(", ")", ")", "return", "smExpr", ".", "setName", "(", "'indented block'", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/setuptools/py3/pkg_resources/_vendor/pyparsing.py#L5247-L5359
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/urllib.py
python
FancyURLopener.http_error_default
(self, url, fp, errcode, errmsg, headers)
return addinfourl(fp, headers, "http:" + url, errcode)
Default error handling -- don't raise an exception.
Default error handling -- don't raise an exception.
[ "Default", "error", "handling", "--", "don", "t", "raise", "an", "exception", "." ]
def http_error_default(self, url, fp, errcode, errmsg, headers): """Default error handling -- don't raise an exception.""" return addinfourl(fp, headers, "http:" + url, errcode)
[ "def", "http_error_default", "(", "self", ",", "url", ",", "fp", ",", "errcode", ",", "errmsg", ",", "headers", ")", ":", "return", "addinfourl", "(", "fp", ",", "headers", ",", "\"http:\"", "+", "url", ",", "errcode", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/urllib.py#L619-L621
apache/incubator-mxnet
f03fb23f1d103fec9541b5ae59ee06b1734a51d9
python/mxnet/gluon/probability/distributions/utils.py
python
logit2prob
(logit, binary=True)
return npx.softmax(logit)
r"""Convert logit into probability form. For the binary case, `sigmoid()` is applied on the logit tensor. Whereas for the multinomial case, `softmax` is applied along the last dimension of the logit tensor.
r"""Convert logit into probability form. For the binary case, `sigmoid()` is applied on the logit tensor. Whereas for the multinomial case, `softmax` is applied along the last dimension of the logit tensor.
[ "r", "Convert", "logit", "into", "probability", "form", ".", "For", "the", "binary", "case", "sigmoid", "()", "is", "applied", "on", "the", "logit", "tensor", ".", "Whereas", "for", "the", "multinomial", "case", "softmax", "is", "applied", "along", "the", "last", "dimension", "of", "the", "logit", "tensor", "." ]
def logit2prob(logit, binary=True): r"""Convert logit into probability form. For the binary case, `sigmoid()` is applied on the logit tensor. Whereas for the multinomial case, `softmax` is applied along the last dimension of the logit tensor. """ if binary: return npx.sigmoid(logit) return npx.softmax(logit)
[ "def", "logit2prob", "(", "logit", ",", "binary", "=", "True", ")", ":", "if", "binary", ":", "return", "npx", ".", "sigmoid", "(", "logit", ")", "return", "npx", ".", "softmax", "(", "logit", ")" ]
https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/python/mxnet/gluon/probability/distributions/utils.py#L159-L167
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/contrib/losses/python/losses/loss_ops.py
python
sparse_softmax_cross_entropy
(logits, labels, weights=1.0, scope=None)
Cross-entropy loss using `tf.nn.sparse_softmax_cross_entropy_with_logits`. `weights` acts as a coefficient for the loss. If a scalar is provided, then the loss is simply scaled by the given value. If `weights` is a tensor of size [`batch_size`], then the loss weights apply to each corresponding sample. Args: logits: [batch_size, num_classes] logits outputs of the network . labels: [batch_size, 1] or [batch_size] labels of dtype `int32` or `int64` in the range `[0, num_classes)`. weights: Coefficients for the loss. The tensor must be a scalar or a tensor of shape [batch_size] or [batch_size, 1]. scope: the scope for the operations performed in computing the loss. Returns: A scalar `Tensor` representing the mean loss value. Raises: ValueError: If the shapes of `logits`, `labels`, and `weights` are incompatible, or if `weights` is None.
Cross-entropy loss using `tf.nn.sparse_softmax_cross_entropy_with_logits`.
[ "Cross", "-", "entropy", "loss", "using", "tf", ".", "nn", ".", "sparse_softmax_cross_entropy_with_logits", "." ]
def sparse_softmax_cross_entropy(logits, labels, weights=1.0, scope=None): """Cross-entropy loss using `tf.nn.sparse_softmax_cross_entropy_with_logits`. `weights` acts as a coefficient for the loss. If a scalar is provided, then the loss is simply scaled by the given value. If `weights` is a tensor of size [`batch_size`], then the loss weights apply to each corresponding sample. Args: logits: [batch_size, num_classes] logits outputs of the network . labels: [batch_size, 1] or [batch_size] labels of dtype `int32` or `int64` in the range `[0, num_classes)`. weights: Coefficients for the loss. The tensor must be a scalar or a tensor of shape [batch_size] or [batch_size, 1]. scope: the scope for the operations performed in computing the loss. Returns: A scalar `Tensor` representing the mean loss value. Raises: ValueError: If the shapes of `logits`, `labels`, and `weights` are incompatible, or if `weights` is None. """ with ops.name_scope(scope, "sparse_softmax_cross_entropy_loss", [logits, labels, weights]) as scope: labels = array_ops.reshape(labels, shape=[array_ops.shape(labels)[0]]) losses = nn.sparse_softmax_cross_entropy_with_logits(labels=labels, logits=logits, name="xentropy") return compute_weighted_loss(losses, weights, scope=scope)
[ "def", "sparse_softmax_cross_entropy", "(", "logits", ",", "labels", ",", "weights", "=", "1.0", ",", "scope", "=", "None", ")", ":", "with", "ops", ".", "name_scope", "(", "scope", ",", "\"sparse_softmax_cross_entropy_loss\"", ",", "[", "logits", ",", "labels", ",", "weights", "]", ")", "as", "scope", ":", "labels", "=", "array_ops", ".", "reshape", "(", "labels", ",", "shape", "=", "[", "array_ops", ".", "shape", "(", "labels", ")", "[", "0", "]", "]", ")", "losses", "=", "nn", ".", "sparse_softmax_cross_entropy_with_logits", "(", "labels", "=", "labels", ",", "logits", "=", "logits", ",", "name", "=", "\"xentropy\"", ")", "return", "compute_weighted_loss", "(", "losses", ",", "weights", ",", "scope", "=", "scope", ")" ]
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/contrib/losses/python/losses/loss_ops.py#L405-L435
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/http/cookiejar.py
python
escape_path
(path)
return path
Escape any invalid characters in HTTP URL, and uppercase all escapes.
Escape any invalid characters in HTTP URL, and uppercase all escapes.
[ "Escape", "any", "invalid", "characters", "in", "HTTP", "URL", "and", "uppercase", "all", "escapes", "." ]
def escape_path(path): """Escape any invalid characters in HTTP URL, and uppercase all escapes.""" # There's no knowing what character encoding was used to create URLs # containing %-escapes, but since we have to pick one to escape invalid # path characters, we pick UTF-8, as recommended in the HTML 4.0 # specification: # http://www.w3.org/TR/REC-html40/appendix/notes.html#h-B.2.1 # And here, kind of: draft-fielding-uri-rfc2396bis-03 # (And in draft IRI specification: draft-duerst-iri-05) # (And here, for new URI schemes: RFC 2718) path = urllib.parse.quote(path, HTTP_PATH_SAFE) path = ESCAPED_CHAR_RE.sub(uppercase_escaped_char, path) return path
[ "def", "escape_path", "(", "path", ")", ":", "# There's no knowing what character encoding was used to create URLs", "# containing %-escapes, but since we have to pick one to escape invalid", "# path characters, we pick UTF-8, as recommended in the HTML 4.0", "# specification:", "# http://www.w3.org/TR/REC-html40/appendix/notes.html#h-B.2.1", "# And here, kind of: draft-fielding-uri-rfc2396bis-03", "# (And in draft IRI specification: draft-duerst-iri-05)", "# (And here, for new URI schemes: RFC 2718)", "path", "=", "urllib", ".", "parse", ".", "quote", "(", "path", ",", "HTTP_PATH_SAFE", ")", "path", "=", "ESCAPED_CHAR_RE", ".", "sub", "(", "uppercase_escaped_char", ",", "path", ")", "return", "path" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/http/cookiejar.py#L669-L681
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/dataview.py
python
DataViewTreeStore.SetItemData
(*args, **kwargs)
return _dataview.DataViewTreeStore_SetItemData(*args, **kwargs)
SetItemData(self, DataViewItem item, wxClientData data)
SetItemData(self, DataViewItem item, wxClientData data)
[ "SetItemData", "(", "self", "DataViewItem", "item", "wxClientData", "data", ")" ]
def SetItemData(*args, **kwargs): """SetItemData(self, DataViewItem item, wxClientData data)""" return _dataview.DataViewTreeStore_SetItemData(*args, **kwargs)
[ "def", "SetItemData", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_dataview", ".", "DataViewTreeStore_SetItemData", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/dataview.py#L2436-L2438
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py2/pandas/util/_decorators.py
python
Substitution.from_params
(cls, params)
return result
In the case where the params is a mutable sequence (list or dictionary) and it may change before this class is called, one may explicitly use a reference to the params rather than using *args or **kwargs which will copy the values and not reference them.
In the case where the params is a mutable sequence (list or dictionary) and it may change before this class is called, one may explicitly use a reference to the params rather than using *args or **kwargs which will copy the values and not reference them.
[ "In", "the", "case", "where", "the", "params", "is", "a", "mutable", "sequence", "(", "list", "or", "dictionary", ")", "and", "it", "may", "change", "before", "this", "class", "is", "called", "one", "may", "explicitly", "use", "a", "reference", "to", "the", "params", "rather", "than", "using", "*", "args", "or", "**", "kwargs", "which", "will", "copy", "the", "values", "and", "not", "reference", "them", "." ]
def from_params(cls, params): """ In the case where the params is a mutable sequence (list or dictionary) and it may change before this class is called, one may explicitly use a reference to the params rather than using *args or **kwargs which will copy the values and not reference them. """ result = cls() result.params = params return result
[ "def", "from_params", "(", "cls", ",", "params", ")", ":", "result", "=", "cls", "(", ")", "result", ".", "params", "=", "params", "return", "result" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py2/pandas/util/_decorators.py#L271-L280
zeusees/HyperVID
f189944a278eea2c0d2e9322a31698d5bf5417a3
Prj-Python/model_forward.py
python
softmax
(x)
return x
Compute softmax values for each sets of scores in x.
Compute softmax values for each sets of scores in x.
[ "Compute", "softmax", "values", "for", "each", "sets", "of", "scores", "in", "x", "." ]
def softmax(x): """Compute softmax values for each sets of scores in x.""" pass # TODO: Compute and return softmax(x) x = np.array(x) x = np.exp(x) x.astype('float32') if x.ndim == 1: sumcol = sum(x) for i in range(x.size): x[i] = x[i]/float(sumcol) if x.ndim > 1: sumcol = x.sum(axis = 0) for row in x: for i in range(row.size): row[i] = row[i]/float(sumcol[i]) return x
[ "def", "softmax", "(", "x", ")", ":", "pass", "# TODO: Compute and return softmax(x)", "x", "=", "np", ".", "array", "(", "x", ")", "x", "=", "np", ".", "exp", "(", "x", ")", "x", ".", "astype", "(", "'float32'", ")", "if", "x", ".", "ndim", "==", "1", ":", "sumcol", "=", "sum", "(", "x", ")", "for", "i", "in", "range", "(", "x", ".", "size", ")", ":", "x", "[", "i", "]", "=", "x", "[", "i", "]", "/", "float", "(", "sumcol", ")", "if", "x", ".", "ndim", ">", "1", ":", "sumcol", "=", "x", ".", "sum", "(", "axis", "=", "0", ")", "for", "row", "in", "x", ":", "for", "i", "in", "range", "(", "row", ".", "size", ")", ":", "row", "[", "i", "]", "=", "row", "[", "i", "]", "/", "float", "(", "sumcol", "[", "i", "]", ")", "return", "x" ]
https://github.com/zeusees/HyperVID/blob/f189944a278eea2c0d2e9322a31698d5bf5417a3/Prj-Python/model_forward.py#L5-L20
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/boosted_trees/lib/learner/batch/ordinal_split_handler.py
python
sparse_make_stats_update
( is_active, are_buckets_ready, sparse_column_indices, sparse_column_values, sparse_column_shape, quantile_buckets, example_partition_ids, gradients, hessians, weights, empty_gradients, empty_hessians)
return (quantile_indices, quantile_values, quantile_shape, quantile_weights, example_partition_ids, feature_ids, gradients, hessians)
Updates the state for this split handler.
Updates the state for this split handler.
[ "Updates", "the", "state", "for", "this", "split", "handler", "." ]
def sparse_make_stats_update( is_active, are_buckets_ready, sparse_column_indices, sparse_column_values, sparse_column_shape, quantile_buckets, example_partition_ids, gradients, hessians, weights, empty_gradients, empty_hessians): """Updates the state for this split handler.""" def quantiles_ready(): """The subgraph for when the quantiles are ready.""" quantized_feature = quantile_ops.quantiles([], [sparse_column_values], [], [quantile_buckets], [sparse_column_indices]) quantized_feature = math_ops.cast(quantized_feature[1], dtypes.int64) quantized_feature = array_ops.squeeze(quantized_feature, axis=0) example_indices, _ = array_ops.split( sparse_column_indices, num_or_size_splits=2, axis=1) example_indices = array_ops.squeeze(example_indices, [1]) filtered_gradients = array_ops.gather(gradients, example_indices) filtered_hessians = array_ops.gather(hessians, example_indices) filtered_partition_ids = array_ops.gather(example_partition_ids, example_indices) unique_partitions, mapped_partitions = array_ops.unique( example_partition_ids) # Compute aggregate stats for each partition. # Since unsorted_segment_sum can be numerically unstable, use 64bit # operation. gradients64 = math_ops.cast(gradients, dtypes.float64) hessians64 = math_ops.cast(hessians, dtypes.float64) per_partition_gradients = math_ops.unsorted_segment_sum( gradients64, mapped_partitions, array_ops.size(unique_partitions)) per_partition_hessians = math_ops.unsorted_segment_sum( hessians64, mapped_partitions, array_ops.size(unique_partitions)) per_partition_gradients = math_ops.cast(per_partition_gradients, dtypes.float32) per_partition_hessians = math_ops.cast(per_partition_hessians, dtypes.float32) # Prepend a bias feature per partition that accumulates the stats for all # examples in that partition. bias_feature_ids = array_ops.fill( array_ops.shape(unique_partitions), _BIAS_FEATURE_ID) bias_feature_ids = math_ops.cast(bias_feature_ids, dtypes.int64) zeros = array_ops.zeros_like(bias_feature_ids) bias_feature_ids = array_ops.stack([bias_feature_ids, zeros], axis=1) partition_ids = array_ops.concat( [unique_partitions, filtered_partition_ids], 0) filtered_gradients = array_ops.concat( [per_partition_gradients, filtered_gradients], 0) filtered_hessians = array_ops.concat( [per_partition_hessians, filtered_hessians], 0) bucket_ids = array_ops.concat([bias_feature_ids, quantized_feature], 0) return partition_ids, bucket_ids, filtered_gradients, filtered_hessians def quantiles_not_ready(): """The subgraph for when the quantiles are not ready.""" return (constant_op.constant_v1([], dtype=dtypes.int32), constant_op.constant_v1([], dtype=dtypes.int64, shape=[1, 2]), empty_gradients, empty_hessians) empty_float = constant_op.constant_v1([], dtype=dtypes.float32) handler_not_active = (constant_op.constant( [], dtype=dtypes.int64, shape=[0, 2]), empty_float, constant_op.constant([0, 1], dtype=dtypes.int64), empty_float) handler_active = (sparse_column_indices, sparse_column_values, sparse_column_shape, weights) quantile_indices, quantile_values, quantile_shape, quantile_weights = ( control_flow_ops.cond(is_active[1], lambda: handler_active, lambda: handler_not_active)) example_partition_ids, feature_ids, gradients, hessians = ( control_flow_ops.cond( math_ops.logical_and(are_buckets_ready, array_ops.size(quantile_buckets) > 0), quantiles_ready, quantiles_not_ready)) return (quantile_indices, quantile_values, quantile_shape, quantile_weights, example_partition_ids, feature_ids, gradients, hessians)
[ "def", "sparse_make_stats_update", "(", "is_active", ",", "are_buckets_ready", ",", "sparse_column_indices", ",", "sparse_column_values", ",", "sparse_column_shape", ",", "quantile_buckets", ",", "example_partition_ids", ",", "gradients", ",", "hessians", ",", "weights", ",", "empty_gradients", ",", "empty_hessians", ")", ":", "def", "quantiles_ready", "(", ")", ":", "\"\"\"The subgraph for when the quantiles are ready.\"\"\"", "quantized_feature", "=", "quantile_ops", ".", "quantiles", "(", "[", "]", ",", "[", "sparse_column_values", "]", ",", "[", "]", ",", "[", "quantile_buckets", "]", ",", "[", "sparse_column_indices", "]", ")", "quantized_feature", "=", "math_ops", ".", "cast", "(", "quantized_feature", "[", "1", "]", ",", "dtypes", ".", "int64", ")", "quantized_feature", "=", "array_ops", ".", "squeeze", "(", "quantized_feature", ",", "axis", "=", "0", ")", "example_indices", ",", "_", "=", "array_ops", ".", "split", "(", "sparse_column_indices", ",", "num_or_size_splits", "=", "2", ",", "axis", "=", "1", ")", "example_indices", "=", "array_ops", ".", "squeeze", "(", "example_indices", ",", "[", "1", "]", ")", "filtered_gradients", "=", "array_ops", ".", "gather", "(", "gradients", ",", "example_indices", ")", "filtered_hessians", "=", "array_ops", ".", "gather", "(", "hessians", ",", "example_indices", ")", "filtered_partition_ids", "=", "array_ops", ".", "gather", "(", "example_partition_ids", ",", "example_indices", ")", "unique_partitions", ",", "mapped_partitions", "=", "array_ops", ".", "unique", "(", "example_partition_ids", ")", "# Compute aggregate stats for each partition.", "# Since unsorted_segment_sum can be numerically unstable, use 64bit", "# operation.", "gradients64", "=", "math_ops", ".", "cast", "(", "gradients", ",", "dtypes", ".", "float64", ")", "hessians64", "=", "math_ops", ".", "cast", "(", "hessians", ",", "dtypes", ".", "float64", ")", "per_partition_gradients", "=", "math_ops", ".", "unsorted_segment_sum", "(", "gradients64", ",", "mapped_partitions", ",", "array_ops", ".", "size", "(", "unique_partitions", ")", ")", "per_partition_hessians", "=", "math_ops", ".", "unsorted_segment_sum", "(", "hessians64", ",", "mapped_partitions", ",", "array_ops", ".", "size", "(", "unique_partitions", ")", ")", "per_partition_gradients", "=", "math_ops", ".", "cast", "(", "per_partition_gradients", ",", "dtypes", ".", "float32", ")", "per_partition_hessians", "=", "math_ops", ".", "cast", "(", "per_partition_hessians", ",", "dtypes", ".", "float32", ")", "# Prepend a bias feature per partition that accumulates the stats for all", "# examples in that partition.", "bias_feature_ids", "=", "array_ops", ".", "fill", "(", "array_ops", ".", "shape", "(", "unique_partitions", ")", ",", "_BIAS_FEATURE_ID", ")", "bias_feature_ids", "=", "math_ops", ".", "cast", "(", "bias_feature_ids", ",", "dtypes", ".", "int64", ")", "zeros", "=", "array_ops", ".", "zeros_like", "(", "bias_feature_ids", ")", "bias_feature_ids", "=", "array_ops", ".", "stack", "(", "[", "bias_feature_ids", ",", "zeros", "]", ",", "axis", "=", "1", ")", "partition_ids", "=", "array_ops", ".", "concat", "(", "[", "unique_partitions", ",", "filtered_partition_ids", "]", ",", "0", ")", "filtered_gradients", "=", "array_ops", ".", "concat", "(", "[", "per_partition_gradients", ",", "filtered_gradients", "]", ",", "0", ")", "filtered_hessians", "=", "array_ops", ".", "concat", "(", "[", "per_partition_hessians", ",", "filtered_hessians", "]", ",", "0", ")", "bucket_ids", "=", "array_ops", ".", "concat", "(", "[", "bias_feature_ids", ",", "quantized_feature", "]", ",", "0", ")", "return", "partition_ids", ",", "bucket_ids", ",", "filtered_gradients", ",", "filtered_hessians", "def", "quantiles_not_ready", "(", ")", ":", "\"\"\"The subgraph for when the quantiles are not ready.\"\"\"", "return", "(", "constant_op", ".", "constant_v1", "(", "[", "]", ",", "dtype", "=", "dtypes", ".", "int32", ")", ",", "constant_op", ".", "constant_v1", "(", "[", "]", ",", "dtype", "=", "dtypes", ".", "int64", ",", "shape", "=", "[", "1", ",", "2", "]", ")", ",", "empty_gradients", ",", "empty_hessians", ")", "empty_float", "=", "constant_op", ".", "constant_v1", "(", "[", "]", ",", "dtype", "=", "dtypes", ".", "float32", ")", "handler_not_active", "=", "(", "constant_op", ".", "constant", "(", "[", "]", ",", "dtype", "=", "dtypes", ".", "int64", ",", "shape", "=", "[", "0", ",", "2", "]", ")", ",", "empty_float", ",", "constant_op", ".", "constant", "(", "[", "0", ",", "1", "]", ",", "dtype", "=", "dtypes", ".", "int64", ")", ",", "empty_float", ")", "handler_active", "=", "(", "sparse_column_indices", ",", "sparse_column_values", ",", "sparse_column_shape", ",", "weights", ")", "quantile_indices", ",", "quantile_values", ",", "quantile_shape", ",", "quantile_weights", "=", "(", "control_flow_ops", ".", "cond", "(", "is_active", "[", "1", "]", ",", "lambda", ":", "handler_active", ",", "lambda", ":", "handler_not_active", ")", ")", "example_partition_ids", ",", "feature_ids", ",", "gradients", ",", "hessians", "=", "(", "control_flow_ops", ".", "cond", "(", "math_ops", ".", "logical_and", "(", "are_buckets_ready", ",", "array_ops", ".", "size", "(", "quantile_buckets", ")", ">", "0", ")", ",", "quantiles_ready", ",", "quantiles_not_ready", ")", ")", "return", "(", "quantile_indices", ",", "quantile_values", ",", "quantile_shape", ",", "quantile_weights", ",", "example_partition_ids", ",", "feature_ids", ",", "gradients", ",", "hessians", ")" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/boosted_trees/lib/learner/batch/ordinal_split_handler.py#L651-L732
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/dateutil/tz/win.py
python
tzwinbase.transitions
(self, year)
return dston, dstoff
For a given year, get the DST on and off transition times, expressed always on the standard time side. For zones with no transitions, this function returns ``None``. :param year: The year whose transitions you would like to query. :return: Returns a :class:`tuple` of :class:`datetime.datetime` objects, ``(dston, dstoff)`` for zones with an annual DST transition, or ``None`` for fixed offset zones.
For a given year, get the DST on and off transition times, expressed always on the standard time side. For zones with no transitions, this function returns ``None``.
[ "For", "a", "given", "year", "get", "the", "DST", "on", "and", "off", "transition", "times", "expressed", "always", "on", "the", "standard", "time", "side", ".", "For", "zones", "with", "no", "transitions", "this", "function", "returns", "None", "." ]
def transitions(self, year): """ For a given year, get the DST on and off transition times, expressed always on the standard time side. For zones with no transitions, this function returns ``None``. :param year: The year whose transitions you would like to query. :return: Returns a :class:`tuple` of :class:`datetime.datetime` objects, ``(dston, dstoff)`` for zones with an annual DST transition, or ``None`` for fixed offset zones. """ if not self.hasdst: return None dston = picknthweekday(year, self._dstmonth, self._dstdayofweek, self._dsthour, self._dstminute, self._dstweeknumber) dstoff = picknthweekday(year, self._stdmonth, self._stddayofweek, self._stdhour, self._stdminute, self._stdweeknumber) # Ambiguous dates default to the STD side dstoff -= self._dst_base_offset return dston, dstoff
[ "def", "transitions", "(", "self", ",", "year", ")", ":", "if", "not", "self", ".", "hasdst", ":", "return", "None", "dston", "=", "picknthweekday", "(", "year", ",", "self", ".", "_dstmonth", ",", "self", ".", "_dstdayofweek", ",", "self", ".", "_dsthour", ",", "self", ".", "_dstminute", ",", "self", ".", "_dstweeknumber", ")", "dstoff", "=", "picknthweekday", "(", "year", ",", "self", ".", "_stdmonth", ",", "self", ".", "_stddayofweek", ",", "self", ".", "_stdhour", ",", "self", ".", "_stdminute", ",", "self", ".", "_stdweeknumber", ")", "# Ambiguous dates default to the STD side", "dstoff", "-=", "self", ".", "_dst_base_offset", "return", "dston", ",", "dstoff" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/dateutil/tz/win.py#L163-L192
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
third_party/jinja2/filters.py
python
do_sort
(environment, value, reverse=False, case_sensitive=False, attribute=None)
return sorted(value, key=sort_func, reverse=reverse)
Sort an iterable. Per default it sorts ascending, if you pass it true as first argument it will reverse the sorting. If the iterable is made of strings the third parameter can be used to control the case sensitiveness of the comparison which is disabled by default. .. sourcecode:: jinja {% for item in iterable|sort %} ... {% endfor %} It is also possible to sort by an attribute (for example to sort by the date of an object) by specifying the `attribute` parameter: .. sourcecode:: jinja {% for item in iterable|sort(attribute='date') %} ... {% endfor %} .. versionchanged:: 2.6 The `attribute` parameter was added.
Sort an iterable. Per default it sorts ascending, if you pass it true as first argument it will reverse the sorting.
[ "Sort", "an", "iterable", ".", "Per", "default", "it", "sorts", "ascending", "if", "you", "pass", "it", "true", "as", "first", "argument", "it", "will", "reverse", "the", "sorting", "." ]
def do_sort(environment, value, reverse=False, case_sensitive=False, attribute=None): """Sort an iterable. Per default it sorts ascending, if you pass it true as first argument it will reverse the sorting. If the iterable is made of strings the third parameter can be used to control the case sensitiveness of the comparison which is disabled by default. .. sourcecode:: jinja {% for item in iterable|sort %} ... {% endfor %} It is also possible to sort by an attribute (for example to sort by the date of an object) by specifying the `attribute` parameter: .. sourcecode:: jinja {% for item in iterable|sort(attribute='date') %} ... {% endfor %} .. versionchanged:: 2.6 The `attribute` parameter was added. """ if not case_sensitive: def sort_func(item): if isinstance(item, string_types): item = item.lower() return item else: sort_func = None if attribute is not None: getter = make_attrgetter(environment, attribute) def sort_func(item, processor=sort_func or (lambda x: x)): return processor(getter(item)) return sorted(value, key=sort_func, reverse=reverse)
[ "def", "do_sort", "(", "environment", ",", "value", ",", "reverse", "=", "False", ",", "case_sensitive", "=", "False", ",", "attribute", "=", "None", ")", ":", "if", "not", "case_sensitive", ":", "def", "sort_func", "(", "item", ")", ":", "if", "isinstance", "(", "item", ",", "string_types", ")", ":", "item", "=", "item", ".", "lower", "(", ")", "return", "item", "else", ":", "sort_func", "=", "None", "if", "attribute", "is", "not", "None", ":", "getter", "=", "make_attrgetter", "(", "environment", ",", "attribute", ")", "def", "sort_func", "(", "item", ",", "processor", "=", "sort_func", "or", "(", "lambda", "x", ":", "x", ")", ")", ":", "return", "processor", "(", "getter", "(", "item", ")", ")", "return", "sorted", "(", "value", ",", "key", "=", "sort_func", ",", "reverse", "=", "reverse", ")" ]
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/third_party/jinja2/filters.py#L227-L265
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/parallel_for/pfor.py
python
_create_op
(op_type, inputs, op_dtypes, attrs=None)
return op
Utility to create an op.
Utility to create an op.
[ "Utility", "to", "create", "an", "op", "." ]
def _create_op(op_type, inputs, op_dtypes, attrs=None): """Utility to create an op.""" op = ops.get_default_graph().create_op( op_type, inputs, op_dtypes, attrs=attrs, compute_device=True) flat_attrs = nest.flatten([(str(a), op.get_attr(str(a))) for a in attrs]) execute.record_gradient( op_type, op.inputs, tuple(flat_attrs), op.outputs[:], "") return op
[ "def", "_create_op", "(", "op_type", ",", "inputs", ",", "op_dtypes", ",", "attrs", "=", "None", ")", ":", "op", "=", "ops", ".", "get_default_graph", "(", ")", ".", "create_op", "(", "op_type", ",", "inputs", ",", "op_dtypes", ",", "attrs", "=", "attrs", ",", "compute_device", "=", "True", ")", "flat_attrs", "=", "nest", ".", "flatten", "(", "[", "(", "str", "(", "a", ")", ",", "op", ".", "get_attr", "(", "str", "(", "a", ")", ")", ")", "for", "a", "in", "attrs", "]", ")", "execute", ".", "record_gradient", "(", "op_type", ",", "op", ".", "inputs", ",", "tuple", "(", "flat_attrs", ")", ",", "op", ".", "outputs", "[", ":", "]", ",", "\"\"", ")", "return", "op" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/parallel_for/pfor.py#L901-L908
panda3d/panda3d
833ad89ebad58395d0af0b7ec08538e5e4308265
direct/src/extensions_native/NodePath_extensions.py
python
getAncestry
(self)
return ancestors
Deprecated. Get a list of a node path's ancestors
Deprecated. Get a list of a node path's ancestors
[ "Deprecated", ".", "Get", "a", "list", "of", "a", "node", "path", "s", "ancestors" ]
def getAncestry(self): """Deprecated. Get a list of a node path's ancestors""" if __debug__: warnings.warn("NodePath.getAncestry() is deprecated. Use get_ancestors() instead.", DeprecationWarning, stacklevel=2) ancestors = list(self.getAncestors()) ancestors.reverse() return ancestors
[ "def", "getAncestry", "(", "self", ")", ":", "if", "__debug__", ":", "warnings", ".", "warn", "(", "\"NodePath.getAncestry() is deprecated. Use get_ancestors() instead.\"", ",", "DeprecationWarning", ",", "stacklevel", "=", "2", ")", "ancestors", "=", "list", "(", "self", ".", "getAncestors", "(", ")", ")", "ancestors", ".", "reverse", "(", ")", "return", "ancestors" ]
https://github.com/panda3d/panda3d/blob/833ad89ebad58395d0af0b7ec08538e5e4308265/direct/src/extensions_native/NodePath_extensions.py#L170-L176
Evolving-AI-Lab/fooling
66f097dd6bd2eb6794ade3e187a7adfdf1887688
caffe/python/caffe/io.py
python
load_image
(filename, color=True)
return img
Load an image converting from grayscale or alpha as needed. Take filename: string color: flag for color format. True (default) loads as RGB while False loads as intensity (if image is already grayscale). Give image: an image with type np.float32 of size (H x W x 3) in RGB or of size (H x W x 1) in grayscale.
Load an image converting from grayscale or alpha as needed.
[ "Load", "an", "image", "converting", "from", "grayscale", "or", "alpha", "as", "needed", "." ]
def load_image(filename, color=True): """ Load an image converting from grayscale or alpha as needed. Take filename: string color: flag for color format. True (default) loads as RGB while False loads as intensity (if image is already grayscale). Give image: an image with type np.float32 of size (H x W x 3) in RGB or of size (H x W x 1) in grayscale. """ img = skimage.img_as_float(skimage.io.imread(filename)).astype(np.float32) if img.ndim == 2: img = img[:, :, np.newaxis] if color: img = np.tile(img, (1, 1, 3)) elif img.shape[2] == 4: img = img[:, :, :3] return img
[ "def", "load_image", "(", "filename", ",", "color", "=", "True", ")", ":", "img", "=", "skimage", ".", "img_as_float", "(", "skimage", ".", "io", ".", "imread", "(", "filename", ")", ")", ".", "astype", "(", "np", ".", "float32", ")", "if", "img", ".", "ndim", "==", "2", ":", "img", "=", "img", "[", ":", ",", ":", ",", "np", ".", "newaxis", "]", "if", "color", ":", "img", "=", "np", ".", "tile", "(", "img", ",", "(", "1", ",", "1", ",", "3", ")", ")", "elif", "img", ".", "shape", "[", "2", "]", "==", "4", ":", "img", "=", "img", "[", ":", ",", ":", ",", ":", "3", "]", "return", "img" ]
https://github.com/Evolving-AI-Lab/fooling/blob/66f097dd6bd2eb6794ade3e187a7adfdf1887688/caffe/python/caffe/io.py#L8-L28
bulletphysics/bullet3
f0f2a952e146f016096db6f85cf0c44ed75b0b9a
examples/pybullet/gym/pybullet_envs/minitaur/envs/minitaur_trotting_env.py
python
MinitaurTrottingEnv._signal
(self, t)
return signal
Generates the trotting gait for the robot. Args: t: Current time in simulation. Returns: A numpy array of the reference leg positions.
Generates the trotting gait for the robot.
[ "Generates", "the", "trotting", "gait", "for", "the", "robot", "." ]
def _signal(self, t): """Generates the trotting gait for the robot. Args: t: Current time in simulation. Returns: A numpy array of the reference leg positions. """ # Generates the leg trajectories for the two digonal pair of legs. ext_first_pair, sw_first_pair = self._gen_signal(t, 0) ext_second_pair, sw_second_pair = self._gen_signal(t, math.pi) trotting_signal = np.array([ sw_first_pair, sw_second_pair, sw_second_pair, sw_first_pair, ext_first_pair, ext_second_pair, ext_second_pair, ext_first_pair ]) signal = np.array(self._init_pose) + trotting_signal return signal
[ "def", "_signal", "(", "self", ",", "t", ")", ":", "# Generates the leg trajectories for the two digonal pair of legs.", "ext_first_pair", ",", "sw_first_pair", "=", "self", ".", "_gen_signal", "(", "t", ",", "0", ")", "ext_second_pair", ",", "sw_second_pair", "=", "self", ".", "_gen_signal", "(", "t", ",", "math", ".", "pi", ")", "trotting_signal", "=", "np", ".", "array", "(", "[", "sw_first_pair", ",", "sw_second_pair", ",", "sw_second_pair", ",", "sw_first_pair", ",", "ext_first_pair", ",", "ext_second_pair", ",", "ext_second_pair", ",", "ext_first_pair", "]", ")", "signal", "=", "np", ".", "array", "(", "self", ".", "_init_pose", ")", "+", "trotting_signal", "return", "signal" ]
https://github.com/bulletphysics/bullet3/blob/f0f2a952e146f016096db6f85cf0c44ed75b0b9a/examples/pybullet/gym/pybullet_envs/minitaur/envs/minitaur_trotting_env.py#L182-L200
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/propgrid.py
python
PGProperty.GetEditorClass
(*args, **kwargs)
return _propgrid.PGProperty_GetEditorClass(*args, **kwargs)
GetEditorClass(self) -> PGEditor
GetEditorClass(self) -> PGEditor
[ "GetEditorClass", "(", "self", ")", "-", ">", "PGEditor" ]
def GetEditorClass(*args, **kwargs): """GetEditorClass(self) -> PGEditor""" return _propgrid.PGProperty_GetEditorClass(*args, **kwargs)
[ "def", "GetEditorClass", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_propgrid", ".", "PGProperty_GetEditorClass", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/propgrid.py#L555-L557
microsoft/LightGBM
904b2d5158703c4900b68008617951dd2f9ff21b
python-package/lightgbm/callback.py
python
early_stopping
(stopping_rounds: int, first_metric_only: bool = False, verbose: bool = True, min_delta: Union[float, List[float]] = 0.0)
return _callback
Create a callback that activates early stopping. Activates early stopping. The model will train until the validation score doesn't improve by at least ``min_delta``. Validation score needs to improve at least every ``stopping_rounds`` round(s) to continue training. Requires at least one validation data and one metric. If there's more than one, will check all of them. But the training data is ignored anyway. To check only the first metric set ``first_metric_only`` to True. The index of iteration that has the best performance will be saved in the ``best_iteration`` attribute of a model. Parameters ---------- stopping_rounds : int The possible number of rounds without the trend occurrence. first_metric_only : bool, optional (default=False) Whether to use only the first metric for early stopping. verbose : bool, optional (default=True) Whether to log message with early stopping information. By default, standard output resource is used. Use ``register_logger()`` function to register a custom logger. min_delta : float or list of float, optional (default=0.0) Minimum improvement in score to keep training. If float, this single value is used for all metrics. If list, its length should match the total number of metrics. Returns ------- callback : callable The callback that activates early stopping.
Create a callback that activates early stopping.
[ "Create", "a", "callback", "that", "activates", "early", "stopping", "." ]
def early_stopping(stopping_rounds: int, first_metric_only: bool = False, verbose: bool = True, min_delta: Union[float, List[float]] = 0.0) -> Callable: """Create a callback that activates early stopping. Activates early stopping. The model will train until the validation score doesn't improve by at least ``min_delta``. Validation score needs to improve at least every ``stopping_rounds`` round(s) to continue training. Requires at least one validation data and one metric. If there's more than one, will check all of them. But the training data is ignored anyway. To check only the first metric set ``first_metric_only`` to True. The index of iteration that has the best performance will be saved in the ``best_iteration`` attribute of a model. Parameters ---------- stopping_rounds : int The possible number of rounds without the trend occurrence. first_metric_only : bool, optional (default=False) Whether to use only the first metric for early stopping. verbose : bool, optional (default=True) Whether to log message with early stopping information. By default, standard output resource is used. Use ``register_logger()`` function to register a custom logger. min_delta : float or list of float, optional (default=0.0) Minimum improvement in score to keep training. If float, this single value is used for all metrics. If list, its length should match the total number of metrics. Returns ------- callback : callable The callback that activates early stopping. """ best_score = [] best_iter = [] best_score_list: list = [] cmp_op = [] enabled = True first_metric = '' def _init(env: CallbackEnv) -> None: nonlocal best_score nonlocal best_iter nonlocal best_score_list nonlocal cmp_op nonlocal enabled nonlocal first_metric enabled = not any(env.params.get(boost_alias, "") == 'dart' for boost_alias in _ConfigAliases.get("boosting")) if not enabled: _log_warning('Early stopping is not available in dart mode') return if not env.evaluation_result_list: raise ValueError('For early stopping, ' 'at least one dataset and eval metric is required for evaluation') if stopping_rounds <= 0: raise ValueError("stopping_rounds should be greater than zero.") if verbose: _log_info(f"Training until validation scores don't improve for {stopping_rounds} rounds") # reset storages best_score = [] best_iter = [] best_score_list = [] cmp_op = [] first_metric = '' n_metrics = len(set(m[1] for m in env.evaluation_result_list)) n_datasets = len(env.evaluation_result_list) // n_metrics if isinstance(min_delta, list): if not all(t >= 0 for t in min_delta): raise ValueError('Values for early stopping min_delta must be non-negative.') if len(min_delta) == 0: if verbose: _log_info('Disabling min_delta for early stopping.') deltas = [0.0] * n_datasets * n_metrics elif len(min_delta) == 1: if verbose: _log_info(f'Using {min_delta[0]} as min_delta for all metrics.') deltas = min_delta * n_datasets * n_metrics else: if len(min_delta) != n_metrics: raise ValueError('Must provide a single value for min_delta or as many as metrics.') if first_metric_only and verbose: _log_info(f'Using only {min_delta[0]} as early stopping min_delta.') deltas = min_delta * n_datasets else: if min_delta < 0: raise ValueError('Early stopping min_delta must be non-negative.') if min_delta > 0 and n_metrics > 1 and not first_metric_only and verbose: _log_info(f'Using {min_delta} as min_delta for all metrics.') deltas = [min_delta] * n_datasets * n_metrics # split is needed for "<dataset type> <metric>" case (e.g. "train l1") first_metric = env.evaluation_result_list[0][1].split(" ")[-1] for eval_ret, delta in zip(env.evaluation_result_list, deltas): best_iter.append(0) best_score_list.append(None) if eval_ret[3]: # greater is better best_score.append(float('-inf')) cmp_op.append(partial(_gt_delta, delta=delta)) else: best_score.append(float('inf')) cmp_op.append(partial(_lt_delta, delta=delta)) def _final_iteration_check(env: CallbackEnv, eval_name_splitted: List[str], i: int) -> None: nonlocal best_iter nonlocal best_score_list if env.iteration == env.end_iteration - 1: if verbose: best_score_str = '\t'.join([_format_eval_result(x) for x in best_score_list[i]]) _log_info('Did not meet early stopping. ' f'Best iteration is:\n[{best_iter[i] + 1}]\t{best_score_str}') if first_metric_only: _log_info(f"Evaluated only: {eval_name_splitted[-1]}") raise EarlyStopException(best_iter[i], best_score_list[i]) def _callback(env: CallbackEnv) -> None: nonlocal best_score nonlocal best_iter nonlocal best_score_list nonlocal cmp_op nonlocal enabled nonlocal first_metric if env.iteration == env.begin_iteration: _init(env) if not enabled: return for i in range(len(env.evaluation_result_list)): score = env.evaluation_result_list[i][2] if best_score_list[i] is None or cmp_op[i](score, best_score[i]): best_score[i] = score best_iter[i] = env.iteration best_score_list[i] = env.evaluation_result_list # split is needed for "<dataset type> <metric>" case (e.g. "train l1") eval_name_splitted = env.evaluation_result_list[i][1].split(" ") if first_metric_only and first_metric != eval_name_splitted[-1]: continue # use only the first metric for early stopping if ((env.evaluation_result_list[i][0] == "cv_agg" and eval_name_splitted[0] == "train" or env.evaluation_result_list[i][0] == env.model._train_data_name)): _final_iteration_check(env, eval_name_splitted, i) continue # train data for lgb.cv or sklearn wrapper (underlying lgb.train) elif env.iteration - best_iter[i] >= stopping_rounds: if verbose: eval_result_str = '\t'.join([_format_eval_result(x) for x in best_score_list[i]]) _log_info(f"Early stopping, best iteration is:\n[{best_iter[i] + 1}]\t{eval_result_str}") if first_metric_only: _log_info(f"Evaluated only: {eval_name_splitted[-1]}") raise EarlyStopException(best_iter[i], best_score_list[i]) _final_iteration_check(env, eval_name_splitted, i) _callback.order = 30 # type: ignore return _callback
[ "def", "early_stopping", "(", "stopping_rounds", ":", "int", ",", "first_metric_only", ":", "bool", "=", "False", ",", "verbose", ":", "bool", "=", "True", ",", "min_delta", ":", "Union", "[", "float", ",", "List", "[", "float", "]", "]", "=", "0.0", ")", "->", "Callable", ":", "best_score", "=", "[", "]", "best_iter", "=", "[", "]", "best_score_list", ":", "list", "=", "[", "]", "cmp_op", "=", "[", "]", "enabled", "=", "True", "first_metric", "=", "''", "def", "_init", "(", "env", ":", "CallbackEnv", ")", "->", "None", ":", "nonlocal", "best_score", "nonlocal", "best_iter", "nonlocal", "best_score_list", "nonlocal", "cmp_op", "nonlocal", "enabled", "nonlocal", "first_metric", "enabled", "=", "not", "any", "(", "env", ".", "params", ".", "get", "(", "boost_alias", ",", "\"\"", ")", "==", "'dart'", "for", "boost_alias", "in", "_ConfigAliases", ".", "get", "(", "\"boosting\"", ")", ")", "if", "not", "enabled", ":", "_log_warning", "(", "'Early stopping is not available in dart mode'", ")", "return", "if", "not", "env", ".", "evaluation_result_list", ":", "raise", "ValueError", "(", "'For early stopping, '", "'at least one dataset and eval metric is required for evaluation'", ")", "if", "stopping_rounds", "<=", "0", ":", "raise", "ValueError", "(", "\"stopping_rounds should be greater than zero.\"", ")", "if", "verbose", ":", "_log_info", "(", "f\"Training until validation scores don't improve for {stopping_rounds} rounds\"", ")", "# reset storages", "best_score", "=", "[", "]", "best_iter", "=", "[", "]", "best_score_list", "=", "[", "]", "cmp_op", "=", "[", "]", "first_metric", "=", "''", "n_metrics", "=", "len", "(", "set", "(", "m", "[", "1", "]", "for", "m", "in", "env", ".", "evaluation_result_list", ")", ")", "n_datasets", "=", "len", "(", "env", ".", "evaluation_result_list", ")", "//", "n_metrics", "if", "isinstance", "(", "min_delta", ",", "list", ")", ":", "if", "not", "all", "(", "t", ">=", "0", "for", "t", "in", "min_delta", ")", ":", "raise", "ValueError", "(", "'Values for early stopping min_delta must be non-negative.'", ")", "if", "len", "(", "min_delta", ")", "==", "0", ":", "if", "verbose", ":", "_log_info", "(", "'Disabling min_delta for early stopping.'", ")", "deltas", "=", "[", "0.0", "]", "*", "n_datasets", "*", "n_metrics", "elif", "len", "(", "min_delta", ")", "==", "1", ":", "if", "verbose", ":", "_log_info", "(", "f'Using {min_delta[0]} as min_delta for all metrics.'", ")", "deltas", "=", "min_delta", "*", "n_datasets", "*", "n_metrics", "else", ":", "if", "len", "(", "min_delta", ")", "!=", "n_metrics", ":", "raise", "ValueError", "(", "'Must provide a single value for min_delta or as many as metrics.'", ")", "if", "first_metric_only", "and", "verbose", ":", "_log_info", "(", "f'Using only {min_delta[0]} as early stopping min_delta.'", ")", "deltas", "=", "min_delta", "*", "n_datasets", "else", ":", "if", "min_delta", "<", "0", ":", "raise", "ValueError", "(", "'Early stopping min_delta must be non-negative.'", ")", "if", "min_delta", ">", "0", "and", "n_metrics", ">", "1", "and", "not", "first_metric_only", "and", "verbose", ":", "_log_info", "(", "f'Using {min_delta} as min_delta for all metrics.'", ")", "deltas", "=", "[", "min_delta", "]", "*", "n_datasets", "*", "n_metrics", "# split is needed for \"<dataset type> <metric>\" case (e.g. \"train l1\")", "first_metric", "=", "env", ".", "evaluation_result_list", "[", "0", "]", "[", "1", "]", ".", "split", "(", "\" \"", ")", "[", "-", "1", "]", "for", "eval_ret", ",", "delta", "in", "zip", "(", "env", ".", "evaluation_result_list", ",", "deltas", ")", ":", "best_iter", ".", "append", "(", "0", ")", "best_score_list", ".", "append", "(", "None", ")", "if", "eval_ret", "[", "3", "]", ":", "# greater is better", "best_score", ".", "append", "(", "float", "(", "'-inf'", ")", ")", "cmp_op", ".", "append", "(", "partial", "(", "_gt_delta", ",", "delta", "=", "delta", ")", ")", "else", ":", "best_score", ".", "append", "(", "float", "(", "'inf'", ")", ")", "cmp_op", ".", "append", "(", "partial", "(", "_lt_delta", ",", "delta", "=", "delta", ")", ")", "def", "_final_iteration_check", "(", "env", ":", "CallbackEnv", ",", "eval_name_splitted", ":", "List", "[", "str", "]", ",", "i", ":", "int", ")", "->", "None", ":", "nonlocal", "best_iter", "nonlocal", "best_score_list", "if", "env", ".", "iteration", "==", "env", ".", "end_iteration", "-", "1", ":", "if", "verbose", ":", "best_score_str", "=", "'\\t'", ".", "join", "(", "[", "_format_eval_result", "(", "x", ")", "for", "x", "in", "best_score_list", "[", "i", "]", "]", ")", "_log_info", "(", "'Did not meet early stopping. '", "f'Best iteration is:\\n[{best_iter[i] + 1}]\\t{best_score_str}'", ")", "if", "first_metric_only", ":", "_log_info", "(", "f\"Evaluated only: {eval_name_splitted[-1]}\"", ")", "raise", "EarlyStopException", "(", "best_iter", "[", "i", "]", ",", "best_score_list", "[", "i", "]", ")", "def", "_callback", "(", "env", ":", "CallbackEnv", ")", "->", "None", ":", "nonlocal", "best_score", "nonlocal", "best_iter", "nonlocal", "best_score_list", "nonlocal", "cmp_op", "nonlocal", "enabled", "nonlocal", "first_metric", "if", "env", ".", "iteration", "==", "env", ".", "begin_iteration", ":", "_init", "(", "env", ")", "if", "not", "enabled", ":", "return", "for", "i", "in", "range", "(", "len", "(", "env", ".", "evaluation_result_list", ")", ")", ":", "score", "=", "env", ".", "evaluation_result_list", "[", "i", "]", "[", "2", "]", "if", "best_score_list", "[", "i", "]", "is", "None", "or", "cmp_op", "[", "i", "]", "(", "score", ",", "best_score", "[", "i", "]", ")", ":", "best_score", "[", "i", "]", "=", "score", "best_iter", "[", "i", "]", "=", "env", ".", "iteration", "best_score_list", "[", "i", "]", "=", "env", ".", "evaluation_result_list", "# split is needed for \"<dataset type> <metric>\" case (e.g. \"train l1\")", "eval_name_splitted", "=", "env", ".", "evaluation_result_list", "[", "i", "]", "[", "1", "]", ".", "split", "(", "\" \"", ")", "if", "first_metric_only", "and", "first_metric", "!=", "eval_name_splitted", "[", "-", "1", "]", ":", "continue", "# use only the first metric for early stopping", "if", "(", "(", "env", ".", "evaluation_result_list", "[", "i", "]", "[", "0", "]", "==", "\"cv_agg\"", "and", "eval_name_splitted", "[", "0", "]", "==", "\"train\"", "or", "env", ".", "evaluation_result_list", "[", "i", "]", "[", "0", "]", "==", "env", ".", "model", ".", "_train_data_name", ")", ")", ":", "_final_iteration_check", "(", "env", ",", "eval_name_splitted", ",", "i", ")", "continue", "# train data for lgb.cv or sklearn wrapper (underlying lgb.train)", "elif", "env", ".", "iteration", "-", "best_iter", "[", "i", "]", ">=", "stopping_rounds", ":", "if", "verbose", ":", "eval_result_str", "=", "'\\t'", ".", "join", "(", "[", "_format_eval_result", "(", "x", ")", "for", "x", "in", "best_score_list", "[", "i", "]", "]", ")", "_log_info", "(", "f\"Early stopping, best iteration is:\\n[{best_iter[i] + 1}]\\t{eval_result_str}\"", ")", "if", "first_metric_only", ":", "_log_info", "(", "f\"Evaluated only: {eval_name_splitted[-1]}\"", ")", "raise", "EarlyStopException", "(", "best_iter", "[", "i", "]", ",", "best_score_list", "[", "i", "]", ")", "_final_iteration_check", "(", "env", ",", "eval_name_splitted", ",", "i", ")", "_callback", ".", "order", "=", "30", "# type: ignore", "return", "_callback" ]
https://github.com/microsoft/LightGBM/blob/904b2d5158703c4900b68008617951dd2f9ff21b/python-package/lightgbm/callback.py#L187-L339
WeitaoVan/L-GM-loss
598582f0631bac876b3eeb8d6c4cd1d780269e03
python/caffe/net_spec.py
python
Top.to_proto
(self)
return to_proto(self)
Generate a NetParameter that contains all layers needed to compute this top.
Generate a NetParameter that contains all layers needed to compute this top.
[ "Generate", "a", "NetParameter", "that", "contains", "all", "layers", "needed", "to", "compute", "this", "top", "." ]
def to_proto(self): """Generate a NetParameter that contains all layers needed to compute this top.""" return to_proto(self)
[ "def", "to_proto", "(", "self", ")", ":", "return", "to_proto", "(", "self", ")" ]
https://github.com/WeitaoVan/L-GM-loss/blob/598582f0631bac876b3eeb8d6c4cd1d780269e03/python/caffe/net_spec.py#L90-L94
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
scripts/Calibration/tofpd/diagnostics.py
python
__calculate_dspacing
(obs: dict)
return np.asarray(list(obs.values())[1:-2])
Extract the dspacing values from a row in output dspace table workspace from PDCalibration
Extract the dspacing values from a row in output dspace table workspace from PDCalibration
[ "Extract", "the", "dspacing", "values", "from", "a", "row", "in", "output", "dspace", "table", "workspace", "from", "PDCalibration" ]
def __calculate_dspacing(obs: dict): """Extract the dspacing values from a row in output dspace table workspace from PDCalibration""" # Trim the table row since this is from the output of PDCalibration, so remove detid, chisq and normchisq columns return np.asarray(list(obs.values())[1:-2])
[ "def", "__calculate_dspacing", "(", "obs", ":", "dict", ")", ":", "# Trim the table row since this is from the output of PDCalibration, so remove detid, chisq and normchisq columns", "return", "np", ".", "asarray", "(", "list", "(", "obs", ".", "values", "(", ")", ")", "[", "1", ":", "-", "2", "]", ")" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/scripts/Calibration/tofpd/diagnostics.py#L310-L313
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/grid.py
python
GridEvent.__init__
(self, *args, **kwargs)
__init__(self, int id, EventType type, Object obj, int row=-1, int col=-1, int x=-1, int y=-1, bool sel=True, bool control=False, bool shift=False, bool alt=False, bool meta=False) -> GridEvent
__init__(self, int id, EventType type, Object obj, int row=-1, int col=-1, int x=-1, int y=-1, bool sel=True, bool control=False, bool shift=False, bool alt=False, bool meta=False) -> GridEvent
[ "__init__", "(", "self", "int", "id", "EventType", "type", "Object", "obj", "int", "row", "=", "-", "1", "int", "col", "=", "-", "1", "int", "x", "=", "-", "1", "int", "y", "=", "-", "1", "bool", "sel", "=", "True", "bool", "control", "=", "False", "bool", "shift", "=", "False", "bool", "alt", "=", "False", "bool", "meta", "=", "False", ")", "-", ">", "GridEvent" ]
def __init__(self, *args, **kwargs): """ __init__(self, int id, EventType type, Object obj, int row=-1, int col=-1, int x=-1, int y=-1, bool sel=True, bool control=False, bool shift=False, bool alt=False, bool meta=False) -> GridEvent """ _grid.GridEvent_swiginit(self,_grid.new_GridEvent(*args, **kwargs))
[ "def", "__init__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "_grid", ".", "GridEvent_swiginit", "(", "self", ",", "_grid", ".", "new_GridEvent", "(", "*", "args", ",", "*", "*", "kwargs", ")", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/grid.py#L2297-L2304
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_controls.py
python
TreeCtrl.GetSpacing
(*args, **kwargs)
return _controls_.TreeCtrl_GetSpacing(*args, **kwargs)
GetSpacing(self) -> unsigned int
GetSpacing(self) -> unsigned int
[ "GetSpacing", "(", "self", ")", "-", ">", "unsigned", "int" ]
def GetSpacing(*args, **kwargs): """GetSpacing(self) -> unsigned int""" return _controls_.TreeCtrl_GetSpacing(*args, **kwargs)
[ "def", "GetSpacing", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_controls_", ".", "TreeCtrl_GetSpacing", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_controls.py#L5228-L5230
wujian16/Cornell-MOE
df299d1be882d2af9796d7a68b3f9505cac7a53e
moe/optimal_learning/python/cpp_wrappers/domain.py
python
TensorProductDomain.domain_bounds
(self)
return self._domain_bounds
Return the [min, max] bounds for each spatial dimension.
Return the [min, max] bounds for each spatial dimension.
[ "Return", "the", "[", "min", "max", "]", "bounds", "for", "each", "spatial", "dimension", "." ]
def domain_bounds(self): """Return the [min, max] bounds for each spatial dimension.""" return self._domain_bounds
[ "def", "domain_bounds", "(", "self", ")", ":", "return", "self", ".", "_domain_bounds" ]
https://github.com/wujian16/Cornell-MOE/blob/df299d1be882d2af9796d7a68b3f9505cac7a53e/moe/optimal_learning/python/cpp_wrappers/domain.py#L62-L64
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/tools/Editra/src/ed_i18n.py
python
GetLangId
(lang_n)
return lang_desc.get(lang_n, wx.LANGUAGE_DEFAULT)
Gets the ID of a language from the description string. If the language cannot be found the function simply returns the default language @param lang_n: Canonical name of a language @return: wx.LANGUAGE_*** id of language
Gets the ID of a language from the description string. If the language cannot be found the function simply returns the default language @param lang_n: Canonical name of a language @return: wx.LANGUAGE_*** id of language
[ "Gets", "the", "ID", "of", "a", "language", "from", "the", "description", "string", ".", "If", "the", "language", "cannot", "be", "found", "the", "function", "simply", "returns", "the", "default", "language", "@param", "lang_n", ":", "Canonical", "name", "of", "a", "language", "@return", ":", "wx", ".", "LANGUAGE_", "***", "id", "of", "language" ]
def GetLangId(lang_n): """Gets the ID of a language from the description string. If the language cannot be found the function simply returns the default language @param lang_n: Canonical name of a language @return: wx.LANGUAGE_*** id of language """ if lang_n == "Default": # No language set, default to English return wx.LANGUAGE_ENGLISH_US lang_desc = GetLocaleDict(GetAvailLocales(), OPT_DESCRIPT) return lang_desc.get(lang_n, wx.LANGUAGE_DEFAULT)
[ "def", "GetLangId", "(", "lang_n", ")", ":", "if", "lang_n", "==", "\"Default\"", ":", "# No language set, default to English", "return", "wx", ".", "LANGUAGE_ENGLISH_US", "lang_desc", "=", "GetLocaleDict", "(", "GetAvailLocales", "(", ")", ",", "OPT_DESCRIPT", ")", "return", "lang_desc", ".", "get", "(", "lang_n", ",", "wx", ".", "LANGUAGE_DEFAULT", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/ed_i18n.py#L87-L98
ApolloAuto/apollo-platform
86d9dc6743b496ead18d597748ebabd34a513289
ros/third_party/lib_aarch64/python2.7/dist-packages/catkin_pkg/package_templates.py
python
_create_depend_tag
(dep_type, name, version_eq=None, version_lt=None, version_lte=None, version_gt=None, version_gte=None)
return result
Helper to create xml snippet for package.xml
Helper to create xml snippet for package.xml
[ "Helper", "to", "create", "xml", "snippet", "for", "package", ".", "xml" ]
def _create_depend_tag(dep_type, name, version_eq=None, version_lt=None, version_lte=None, version_gt=None, version_gte=None): """ Helper to create xml snippet for package.xml """ version_string = [] for key, var in {'version_eq': version_eq, 'version_lt': version_lt, 'version_lte': version_lte, 'version_gt': version_gt, 'version_gte': version_gte}.items(): if var is not None: version_string.append(' %s="%s"' % (key, var)) result = ' <%s%s>%s</%s>\n' % (dep_type, ''.join(version_string), name, dep_type) return result
[ "def", "_create_depend_tag", "(", "dep_type", ",", "name", ",", "version_eq", "=", "None", ",", "version_lt", "=", "None", ",", "version_lte", "=", "None", ",", "version_gt", "=", "None", ",", "version_gte", "=", "None", ")", ":", "version_string", "=", "[", "]", "for", "key", ",", "var", "in", "{", "'version_eq'", ":", "version_eq", ",", "'version_lt'", ":", "version_lt", ",", "'version_lte'", ":", "version_lte", ",", "'version_gt'", ":", "version_gt", ",", "'version_gte'", ":", "version_gte", "}", ".", "items", "(", ")", ":", "if", "var", "is", "not", "None", ":", "version_string", ".", "append", "(", "' %s=\"%s\"'", "%", "(", "key", ",", "var", ")", ")", "result", "=", "' <%s%s>%s</%s>\\n'", "%", "(", "dep_type", ",", "''", ".", "join", "(", "version_string", ")", ",", "name", ",", "dep_type", ")", "return", "result" ]
https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/third_party/lib_aarch64/python2.7/dist-packages/catkin_pkg/package_templates.py#L316-L339
macchina-io/macchina.io
ef24ba0e18379c3dd48fb84e6dbf991101cb8db0
platform/JS/V8/tools/gyp/pylib/gyp/generator/ninja.py
python
NinjaWriter.WritePchTargets
(self, ninja_file, pch_commands)
Writes ninja rules to compile prefix headers.
Writes ninja rules to compile prefix headers.
[ "Writes", "ninja", "rules", "to", "compile", "prefix", "headers", "." ]
def WritePchTargets(self, ninja_file, pch_commands): """Writes ninja rules to compile prefix headers.""" if not pch_commands: return for gch, lang_flag, lang, input in pch_commands: var_name = { 'c': 'cflags_pch_c', 'cc': 'cflags_pch_cc', 'm': 'cflags_pch_objc', 'mm': 'cflags_pch_objcc', }[lang] map = { 'c': 'cc', 'cc': 'cxx', 'm': 'objc', 'mm': 'objcxx', } cmd = map.get(lang) ninja_file.build(gch, cmd, input, variables=[(var_name, lang_flag)])
[ "def", "WritePchTargets", "(", "self", ",", "ninja_file", ",", "pch_commands", ")", ":", "if", "not", "pch_commands", ":", "return", "for", "gch", ",", "lang_flag", ",", "lang", ",", "input", "in", "pch_commands", ":", "var_name", "=", "{", "'c'", ":", "'cflags_pch_c'", ",", "'cc'", ":", "'cflags_pch_cc'", ",", "'m'", ":", "'cflags_pch_objc'", ",", "'mm'", ":", "'cflags_pch_objcc'", ",", "}", "[", "lang", "]", "map", "=", "{", "'c'", ":", "'cc'", ",", "'cc'", ":", "'cxx'", ",", "'m'", ":", "'objc'", ",", "'mm'", ":", "'objcxx'", ",", "}", "cmd", "=", "map", ".", "get", "(", "lang", ")", "ninja_file", ".", "build", "(", "gch", ",", "cmd", ",", "input", ",", "variables", "=", "[", "(", "var_name", ",", "lang_flag", ")", "]", ")" ]
https://github.com/macchina-io/macchina.io/blob/ef24ba0e18379c3dd48fb84e6dbf991101cb8db0/platform/JS/V8/tools/gyp/pylib/gyp/generator/ninja.py#L1086-L1101
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/x86/toolchain/lib/python2.7/logging/__init__.py
python
info
(msg, *args, **kwargs)
Log a message with severity 'INFO' on the root logger.
Log a message with severity 'INFO' on the root logger.
[ "Log", "a", "message", "with", "severity", "INFO", "on", "the", "root", "logger", "." ]
def info(msg, *args, **kwargs): """ Log a message with severity 'INFO' on the root logger. """ if len(root.handlers) == 0: basicConfig() root.info(msg, *args, **kwargs)
[ "def", "info", "(", "msg", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "len", "(", "root", ".", "handlers", ")", "==", "0", ":", "basicConfig", "(", ")", "root", ".", "info", "(", "msg", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/logging/__init__.py#L1605-L1611
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/AWSPythonSDK/1.5.8/botocore/vendored/requests/packages/urllib3/util/response.py
python
is_fp_closed
(obj)
Checks whether a given file-like object is closed. :param obj: The file-like object to check.
Checks whether a given file-like object is closed.
[ "Checks", "whether", "a", "given", "file", "-", "like", "object", "is", "closed", "." ]
def is_fp_closed(obj): """ Checks whether a given file-like object is closed. :param obj: The file-like object to check. """ try: # Check via the official file-like-object way. return obj.closed except AttributeError: pass try: # Check if the object is a container for another file-like object that # gets released on exhaustion (e.g. HTTPResponse). return obj.fp is None except AttributeError: pass raise ValueError("Unable to determine whether fp is closed.")
[ "def", "is_fp_closed", "(", "obj", ")", ":", "try", ":", "# Check via the official file-like-object way.", "return", "obj", ".", "closed", "except", "AttributeError", ":", "pass", "try", ":", "# Check if the object is a container for another file-like object that", "# gets released on exhaustion (e.g. HTTPResponse).", "return", "obj", ".", "fp", "is", "None", "except", "AttributeError", ":", "pass", "raise", "ValueError", "(", "\"Unable to determine whether fp is closed.\"", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/AWSPythonSDK/1.5.8/botocore/vendored/requests/packages/urllib3/util/response.py#L1-L22
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/site-packages/colorama/ansitowin32.py
python
AnsiToWin32.should_wrap
(self)
return self.convert or self.strip or self.autoreset
True if this class is actually needed. If false, then the output stream will not be affected, nor will win32 calls be issued, so wrapping stdout is not actually required. This will generally be False on non-Windows platforms, unless optional functionality like autoreset has been requested using kwargs to init()
True if this class is actually needed. If false, then the output stream will not be affected, nor will win32 calls be issued, so wrapping stdout is not actually required. This will generally be False on non-Windows platforms, unless optional functionality like autoreset has been requested using kwargs to init()
[ "True", "if", "this", "class", "is", "actually", "needed", ".", "If", "false", "then", "the", "output", "stream", "will", "not", "be", "affected", "nor", "will", "win32", "calls", "be", "issued", "so", "wrapping", "stdout", "is", "not", "actually", "required", ".", "This", "will", "generally", "be", "False", "on", "non", "-", "Windows", "platforms", "unless", "optional", "functionality", "like", "autoreset", "has", "been", "requested", "using", "kwargs", "to", "init", "()" ]
def should_wrap(self): ''' True if this class is actually needed. If false, then the output stream will not be affected, nor will win32 calls be issued, so wrapping stdout is not actually required. This will generally be False on non-Windows platforms, unless optional functionality like autoreset has been requested using kwargs to init() ''' return self.convert or self.strip or self.autoreset
[ "def", "should_wrap", "(", "self", ")", ":", "return", "self", ".", "convert", "or", "self", ".", "strip", "or", "self", ".", "autoreset" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/colorama/ansitowin32.py#L106-L114
vtraag/leidenalg
b53366829360e10922a2dbf57eb405a516c23bc9
src/leidenalg/functions.py
python
time_slices_to_layers
(graphs, interslice_weight=1, slice_attr='slice', vertex_id_attr='id', edge_type_attr='type', weight_attr='weight')
return slices_to_layers(G_slices, slice_attr, vertex_id_attr, edge_type_attr, weight_attr)
Convert time slices to layer graphs. Each graph is considered to represent a time slice. This function simply connects all the consecutive slices (i.e. the slice graph) with an ``interslice_weight``. The further conversion is then delegated to :func:`slices_to_layers`, which also provides further details. See Also -------- :func:`find_partition_temporal` :func:`slices_to_layers`
Convert time slices to layer graphs.
[ "Convert", "time", "slices", "to", "layer", "graphs", "." ]
def time_slices_to_layers(graphs, interslice_weight=1, slice_attr='slice', vertex_id_attr='id', edge_type_attr='type', weight_attr='weight'): """ Convert time slices to layer graphs. Each graph is considered to represent a time slice. This function simply connects all the consecutive slices (i.e. the slice graph) with an ``interslice_weight``. The further conversion is then delegated to :func:`slices_to_layers`, which also provides further details. See Also -------- :func:`find_partition_temporal` :func:`slices_to_layers` """ G_slices = _ig.Graph.Tree(len(graphs), 1, mode=_ig.TREE_UNDIRECTED) G_slices.es[weight_attr] = interslice_weight G_slices.vs[slice_attr] = graphs return slices_to_layers(G_slices, slice_attr, vertex_id_attr, edge_type_attr, weight_attr)
[ "def", "time_slices_to_layers", "(", "graphs", ",", "interslice_weight", "=", "1", ",", "slice_attr", "=", "'slice'", ",", "vertex_id_attr", "=", "'id'", ",", "edge_type_attr", "=", "'type'", ",", "weight_attr", "=", "'weight'", ")", ":", "G_slices", "=", "_ig", ".", "Graph", ".", "Tree", "(", "len", "(", "graphs", ")", ",", "1", ",", "mode", "=", "_ig", ".", "TREE_UNDIRECTED", ")", "G_slices", ".", "es", "[", "weight_attr", "]", "=", "interslice_weight", "G_slices", ".", "vs", "[", "slice_attr", "]", "=", "graphs", "return", "slices_to_layers", "(", "G_slices", ",", "slice_attr", ",", "vertex_id_attr", ",", "edge_type_attr", ",", "weight_attr", ")" ]
https://github.com/vtraag/leidenalg/blob/b53366829360e10922a2dbf57eb405a516c23bc9/src/leidenalg/functions.py#L331-L358
OSGeo/gdal
3748fc4ba4fba727492774b2b908a2130c864a83
swig/python/osgeo/gdal.py
python
BuildVRTInternalObjects
(*args)
return _gdal.BuildVRTInternalObjects(*args)
r"""BuildVRTInternalObjects(char const * dest, int object_list_count, GDALBuildVRTOptions options, GDALProgressFunc callback=0, void * callback_data=None) -> Dataset
r"""BuildVRTInternalObjects(char const * dest, int object_list_count, GDALBuildVRTOptions options, GDALProgressFunc callback=0, void * callback_data=None) -> Dataset
[ "r", "BuildVRTInternalObjects", "(", "char", "const", "*", "dest", "int", "object_list_count", "GDALBuildVRTOptions", "options", "GDALProgressFunc", "callback", "=", "0", "void", "*", "callback_data", "=", "None", ")", "-", ">", "Dataset" ]
def BuildVRTInternalObjects(*args): r"""BuildVRTInternalObjects(char const * dest, int object_list_count, GDALBuildVRTOptions options, GDALProgressFunc callback=0, void * callback_data=None) -> Dataset""" return _gdal.BuildVRTInternalObjects(*args)
[ "def", "BuildVRTInternalObjects", "(", "*", "args", ")", ":", "return", "_gdal", ".", "BuildVRTInternalObjects", "(", "*", "args", ")" ]
https://github.com/OSGeo/gdal/blob/3748fc4ba4fba727492774b2b908a2130c864a83/swig/python/osgeo/gdal.py#L4348-L4350
floooh/oryol
eb08cffe1b1cb6b05ed14ec692bca9372cef064e
fips-files/generators/util/png.py
python
Reader.read
(self)
return self.width, self.height, pixels, meta
Read the PNG file and decode it. Returns (`width`, `height`, `pixels`, `metadata`). May use excessive memory. `pixels` are returned in boxed row flat pixel format.
Read the PNG file and decode it. Returns (`width`, `height`, `pixels`, `metadata`).
[ "Read", "the", "PNG", "file", "and", "decode", "it", ".", "Returns", "(", "width", "height", "pixels", "metadata", ")", "." ]
def read(self): """ Read the PNG file and decode it. Returns (`width`, `height`, `pixels`, `metadata`). May use excessive memory. `pixels` are returned in boxed row flat pixel format. """ def iteridat(): """Iterator that yields all the ``IDAT`` chunks as strings.""" while True: try: type, data = self.chunk() except ValueError as e: raise ChunkError(e.args[0]) if type == 'IEND': # http://www.w3.org/TR/PNG/#11IEND break if type != 'IDAT': continue # type == 'IDAT' # http://www.w3.org/TR/PNG/#11IDAT if self.colormap and not self.plte: warnings.warn("PLTE chunk is required before IDAT chunk") yield data def iterdecomp(idat): """Iterator that yields decompressed strings. `idat` should be an iterator that yields the ``IDAT`` chunk data. """ # Currently, with no max_length paramter to decompress, this # routine will do one yield per IDAT chunk. So not very # incremental. d = zlib.decompressobj() # Each IDAT chunk is passed to the decompressor, then any # remaining state is decompressed out. for data in idat: # :todo: add a max_length argument here to limit output # size. yield array('B', d.decompress(data)) yield array('B', d.flush()) self.preamble() raw = iterdecomp(iteridat()) if self.interlace: raw = array('B', itertools.chain(*raw)) arraycode = 'BH'[self.bitdepth>8] # Like :meth:`group` but producing an array.array object for # each row. pixels = itertools.imap(lambda *row: array(arraycode, row), *[iter(self.deinterlace(raw))]*self.width*self.planes) else: pixels = self.iterboxed(self.iterstraight(raw)) meta = dict() for attr in 'greyscale alpha planes bitdepth interlace'.split(): meta[attr] = getattr(self, attr) meta['size'] = (self.width, self.height) for attr in 'gamma transparent background'.split(): a = getattr(self, attr, None) if a is not None: meta[attr] = a return self.width, self.height, pixels, meta
[ "def", "read", "(", "self", ")", ":", "def", "iteridat", "(", ")", ":", "\"\"\"Iterator that yields all the ``IDAT`` chunks as strings.\"\"\"", "while", "True", ":", "try", ":", "type", ",", "data", "=", "self", ".", "chunk", "(", ")", "except", "ValueError", "as", "e", ":", "raise", "ChunkError", "(", "e", ".", "args", "[", "0", "]", ")", "if", "type", "==", "'IEND'", ":", "# http://www.w3.org/TR/PNG/#11IEND", "break", "if", "type", "!=", "'IDAT'", ":", "continue", "# type == 'IDAT'", "# http://www.w3.org/TR/PNG/#11IDAT", "if", "self", ".", "colormap", "and", "not", "self", ".", "plte", ":", "warnings", ".", "warn", "(", "\"PLTE chunk is required before IDAT chunk\"", ")", "yield", "data", "def", "iterdecomp", "(", "idat", ")", ":", "\"\"\"Iterator that yields decompressed strings. `idat` should\n be an iterator that yields the ``IDAT`` chunk data.\n \"\"\"", "# Currently, with no max_length paramter to decompress, this", "# routine will do one yield per IDAT chunk. So not very", "# incremental.", "d", "=", "zlib", ".", "decompressobj", "(", ")", "# Each IDAT chunk is passed to the decompressor, then any", "# remaining state is decompressed out.", "for", "data", "in", "idat", ":", "# :todo: add a max_length argument here to limit output", "# size.", "yield", "array", "(", "'B'", ",", "d", ".", "decompress", "(", "data", ")", ")", "yield", "array", "(", "'B'", ",", "d", ".", "flush", "(", ")", ")", "self", ".", "preamble", "(", ")", "raw", "=", "iterdecomp", "(", "iteridat", "(", ")", ")", "if", "self", ".", "interlace", ":", "raw", "=", "array", "(", "'B'", ",", "itertools", ".", "chain", "(", "*", "raw", ")", ")", "arraycode", "=", "'BH'", "[", "self", ".", "bitdepth", ">", "8", "]", "# Like :meth:`group` but producing an array.array object for", "# each row.", "pixels", "=", "itertools", ".", "imap", "(", "lambda", "*", "row", ":", "array", "(", "arraycode", ",", "row", ")", ",", "*", "[", "iter", "(", "self", ".", "deinterlace", "(", "raw", ")", ")", "]", "*", "self", ".", "width", "*", "self", ".", "planes", ")", "else", ":", "pixels", "=", "self", ".", "iterboxed", "(", "self", ".", "iterstraight", "(", "raw", ")", ")", "meta", "=", "dict", "(", ")", "for", "attr", "in", "'greyscale alpha planes bitdepth interlace'", ".", "split", "(", ")", ":", "meta", "[", "attr", "]", "=", "getattr", "(", "self", ",", "attr", ")", "meta", "[", "'size'", "]", "=", "(", "self", ".", "width", ",", "self", ".", "height", ")", "for", "attr", "in", "'gamma transparent background'", ".", "split", "(", ")", ":", "a", "=", "getattr", "(", "self", ",", "attr", ",", "None", ")", "if", "a", "is", "not", "None", ":", "meta", "[", "attr", "]", "=", "a", "return", "self", ".", "width", ",", "self", ".", "height", ",", "pixels", ",", "meta" ]
https://github.com/floooh/oryol/blob/eb08cffe1b1cb6b05ed14ec692bca9372cef064e/fips-files/generators/util/png.py#L1849-L1914
CRYTEK/CRYENGINE
232227c59a220cbbd311576f0fbeba7bb53b2a8c
Code/Tools/waf-1.7.13/waflib/Tools/msvc.py
python
gather_wsdk_versions
(conf, versions)
Use winreg to add the msvc versions to the input list :param versions: list to modify :type versions: list
Use winreg to add the msvc versions to the input list
[ "Use", "winreg", "to", "add", "the", "msvc", "versions", "to", "the", "input", "list" ]
def gather_wsdk_versions(conf, versions): """ Use winreg to add the msvc versions to the input list :param versions: list to modify :type versions: list """ version_pattern = re.compile('^v..?.?\...?.?') try: all_versions = Utils.winreg.OpenKey(Utils.winreg.HKEY_LOCAL_MACHINE, 'SOFTWARE\\Wow6432node\\Microsoft\\Microsoft SDKs\\Windows') except WindowsError: try: all_versions = Utils.winreg.OpenKey(Utils.winreg.HKEY_LOCAL_MACHINE, 'SOFTWARE\\Microsoft\\Microsoft SDKs\\Windows') except WindowsError: return index = 0 while 1: try: version = Utils.winreg.EnumKey(all_versions, index) except WindowsError: break index = index + 1 if not version_pattern.match(version): continue try: msvc_version = Utils.winreg.OpenKey(all_versions, version) path,type = Utils.winreg.QueryValueEx(msvc_version,'InstallationFolder') except WindowsError: continue if os.path.isfile(os.path.join(path, 'bin', 'SetEnv.cmd')): targets = [] for target,arch in all_msvc_platforms: try: targets.append((target, (arch, conf.get_msvc_version('wsdk', version, '/'+target, os.path.join(path, 'bin', 'SetEnv.cmd'))))) except conf.errors.ConfigurationError: pass versions.append(('wsdk ' + version[1:], targets))
[ "def", "gather_wsdk_versions", "(", "conf", ",", "versions", ")", ":", "version_pattern", "=", "re", ".", "compile", "(", "'^v..?.?\\...?.?'", ")", "try", ":", "all_versions", "=", "Utils", ".", "winreg", ".", "OpenKey", "(", "Utils", ".", "winreg", ".", "HKEY_LOCAL_MACHINE", ",", "'SOFTWARE\\\\Wow6432node\\\\Microsoft\\\\Microsoft SDKs\\\\Windows'", ")", "except", "WindowsError", ":", "try", ":", "all_versions", "=", "Utils", ".", "winreg", ".", "OpenKey", "(", "Utils", ".", "winreg", ".", "HKEY_LOCAL_MACHINE", ",", "'SOFTWARE\\\\Microsoft\\\\Microsoft SDKs\\\\Windows'", ")", "except", "WindowsError", ":", "return", "index", "=", "0", "while", "1", ":", "try", ":", "version", "=", "Utils", ".", "winreg", ".", "EnumKey", "(", "all_versions", ",", "index", ")", "except", "WindowsError", ":", "break", "index", "=", "index", "+", "1", "if", "not", "version_pattern", ".", "match", "(", "version", ")", ":", "continue", "try", ":", "msvc_version", "=", "Utils", ".", "winreg", ".", "OpenKey", "(", "all_versions", ",", "version", ")", "path", ",", "type", "=", "Utils", ".", "winreg", ".", "QueryValueEx", "(", "msvc_version", ",", "'InstallationFolder'", ")", "except", "WindowsError", ":", "continue", "if", "os", ".", "path", ".", "isfile", "(", "os", ".", "path", ".", "join", "(", "path", ",", "'bin'", ",", "'SetEnv.cmd'", ")", ")", ":", "targets", "=", "[", "]", "for", "target", ",", "arch", "in", "all_msvc_platforms", ":", "try", ":", "targets", ".", "append", "(", "(", "target", ",", "(", "arch", ",", "conf", ".", "get_msvc_version", "(", "'wsdk'", ",", "version", ",", "'/'", "+", "target", ",", "os", ".", "path", ".", "join", "(", "path", ",", "'bin'", ",", "'SetEnv.cmd'", ")", ")", ")", ")", ")", "except", "conf", ".", "errors", ".", "ConfigurationError", ":", "pass", "versions", ".", "append", "(", "(", "'wsdk '", "+", "version", "[", "1", ":", "]", ",", "targets", ")", ")" ]
https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Code/Tools/waf-1.7.13/waflib/Tools/msvc.py#L185-L221
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/indexes/base.py
python
Index.to_frame
(self, index=True, name=None)
return result
Create a DataFrame with a column containing the Index. .. versionadded:: 0.24.0 Parameters ---------- index : bool, default True Set the index of the returned DataFrame as the original Index. name : object, default None The passed name should substitute for the index name (if it has one). Returns ------- DataFrame DataFrame containing the original Index data. See Also -------- Index.to_series : Convert an Index to a Series. Series.to_frame : Convert Series to DataFrame. Examples -------- >>> idx = pd.Index(['Ant', 'Bear', 'Cow'], name='animal') >>> idx.to_frame() animal animal Ant Ant Bear Bear Cow Cow By default, the original Index is reused. To enforce a new Index: >>> idx.to_frame(index=False) animal 0 Ant 1 Bear 2 Cow To override the name of the resulting column, specify `name`: >>> idx.to_frame(index=False, name='zoo') zoo 0 Ant 1 Bear 2 Cow
Create a DataFrame with a column containing the Index.
[ "Create", "a", "DataFrame", "with", "a", "column", "containing", "the", "Index", "." ]
def to_frame(self, index=True, name=None): """ Create a DataFrame with a column containing the Index. .. versionadded:: 0.24.0 Parameters ---------- index : bool, default True Set the index of the returned DataFrame as the original Index. name : object, default None The passed name should substitute for the index name (if it has one). Returns ------- DataFrame DataFrame containing the original Index data. See Also -------- Index.to_series : Convert an Index to a Series. Series.to_frame : Convert Series to DataFrame. Examples -------- >>> idx = pd.Index(['Ant', 'Bear', 'Cow'], name='animal') >>> idx.to_frame() animal animal Ant Ant Bear Bear Cow Cow By default, the original Index is reused. To enforce a new Index: >>> idx.to_frame(index=False) animal 0 Ant 1 Bear 2 Cow To override the name of the resulting column, specify `name`: >>> idx.to_frame(index=False, name='zoo') zoo 0 Ant 1 Bear 2 Cow """ from pandas import DataFrame if name is None: name = self.name or 0 result = DataFrame({name: self._values.copy()}) if index: result.index = self return result
[ "def", "to_frame", "(", "self", ",", "index", "=", "True", ",", "name", "=", "None", ")", ":", "from", "pandas", "import", "DataFrame", "if", "name", "is", "None", ":", "name", "=", "self", ".", "name", "or", "0", "result", "=", "DataFrame", "(", "{", "name", ":", "self", ".", "_values", ".", "copy", "(", ")", "}", ")", "if", "index", ":", "result", ".", "index", "=", "self", "return", "result" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/indexes/base.py#L1117-L1177
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python/src/Lib/distutils/msvccompiler.py
python
MSVCCompiler.get_msvc_paths
(self, path, platform='x86')
return []
Get a list of devstudio directories (include, lib or path). Return a list of strings. The list will be empty if unable to access the registry or appropriate registry keys not found.
Get a list of devstudio directories (include, lib or path).
[ "Get", "a", "list", "of", "devstudio", "directories", "(", "include", "lib", "or", "path", ")", "." ]
def get_msvc_paths(self, path, platform='x86'): """Get a list of devstudio directories (include, lib or path). Return a list of strings. The list will be empty if unable to access the registry or appropriate registry keys not found. """ if not _can_read_reg: return [] path = path + " dirs" if self.__version >= 7: key = (r"%s\%0.1f\VC\VC_OBJECTS_PLATFORM_INFO\Win32\Directories" % (self.__root, self.__version)) else: key = (r"%s\6.0\Build System\Components\Platforms" r"\Win32 (%s)\Directories" % (self.__root, platform)) for base in HKEYS: d = read_values(base, key) if d: if self.__version >= 7: return string.split(self.__macros.sub(d[path]), ";") else: return string.split(d[path], ";") # MSVC 6 seems to create the registry entries we need only when # the GUI is run. if self.__version == 6: for base in HKEYS: if read_values(base, r"%s\6.0" % self.__root) is not None: self.warn("It seems you have Visual Studio 6 installed, " "but the expected registry settings are not present.\n" "You must at least run the Visual Studio GUI once " "so that these entries are created.") break return []
[ "def", "get_msvc_paths", "(", "self", ",", "path", ",", "platform", "=", "'x86'", ")", ":", "if", "not", "_can_read_reg", ":", "return", "[", "]", "path", "=", "path", "+", "\" dirs\"", "if", "self", ".", "__version", ">=", "7", ":", "key", "=", "(", "r\"%s\\%0.1f\\VC\\VC_OBJECTS_PLATFORM_INFO\\Win32\\Directories\"", "%", "(", "self", ".", "__root", ",", "self", ".", "__version", ")", ")", "else", ":", "key", "=", "(", "r\"%s\\6.0\\Build System\\Components\\Platforms\"", "r\"\\Win32 (%s)\\Directories\"", "%", "(", "self", ".", "__root", ",", "platform", ")", ")", "for", "base", "in", "HKEYS", ":", "d", "=", "read_values", "(", "base", ",", "key", ")", "if", "d", ":", "if", "self", ".", "__version", ">=", "7", ":", "return", "string", ".", "split", "(", "self", ".", "__macros", ".", "sub", "(", "d", "[", "path", "]", ")", ",", "\";\"", ")", "else", ":", "return", "string", ".", "split", "(", "d", "[", "path", "]", ",", "\";\"", ")", "# MSVC 6 seems to create the registry entries we need only when", "# the GUI is run.", "if", "self", ".", "__version", "==", "6", ":", "for", "base", "in", "HKEYS", ":", "if", "read_values", "(", "base", ",", "r\"%s\\6.0\"", "%", "self", ".", "__root", ")", "is", "not", "None", ":", "self", ".", "warn", "(", "\"It seems you have Visual Studio 6 installed, \"", "\"but the expected registry settings are not present.\\n\"", "\"You must at least run the Visual Studio GUI once \"", "\"so that these entries are created.\"", ")", "break", "return", "[", "]" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/distutils/msvccompiler.py#L602-L637
fifengine/fifengine
4b62c42e85bec19893cef8e63e6855927cff2c47
engine/python/fife/extensions/pychan/widgets/slider.py
python
Slider._getScaleEnd
(self)
return self.real_widget.getScaleEnd()
getScaleEnd(self) -> double
getScaleEnd(self) -> double
[ "getScaleEnd", "(", "self", ")", "-", ">", "double" ]
def _getScaleEnd(self): """getScaleEnd(self) -> double""" return self.real_widget.getScaleEnd()
[ "def", "_getScaleEnd", "(", "self", ")", ":", "return", "self", ".", "real_widget", ".", "getScaleEnd", "(", ")" ]
https://github.com/fifengine/fifengine/blob/4b62c42e85bec19893cef8e63e6855927cff2c47/engine/python/fife/extensions/pychan/widgets/slider.py#L196-L198
domino-team/openwrt-cc
8b181297c34d14d3ca521cc9f31430d561dbc688
package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/cmake.py
python
WriteRules
(target_name, rules, extra_sources, extra_deps, path_to_gyp, output)
Write CMake for the 'rules' in the target. Args: target_name: the name of the CMake target being generated. actions: the Gyp 'actions' dict for this target. extra_sources: [(<cmake_src>, <src>)] to append with generated source files. extra_deps: [<cmake_taget>] to append with generated targets. path_to_gyp: relative path from CMakeLists.txt being generated to the Gyp file in which the target being generated is defined.
Write CMake for the 'rules' in the target.
[ "Write", "CMake", "for", "the", "rules", "in", "the", "target", "." ]
def WriteRules(target_name, rules, extra_sources, extra_deps, path_to_gyp, output): """Write CMake for the 'rules' in the target. Args: target_name: the name of the CMake target being generated. actions: the Gyp 'actions' dict for this target. extra_sources: [(<cmake_src>, <src>)] to append with generated source files. extra_deps: [<cmake_taget>] to append with generated targets. path_to_gyp: relative path from CMakeLists.txt being generated to the Gyp file in which the target being generated is defined. """ for rule in rules: rule_name = StringToCMakeTargetName(target_name + '__' + rule['rule_name']) inputs = rule.get('inputs', []) inputs_name = rule_name + '__input' SetVariableList(output, inputs_name, [NormjoinPathForceCMakeSource(path_to_gyp, dep) for dep in inputs]) outputs = rule['outputs'] var_outputs = [] for count, rule_source in enumerate(rule.get('rule_sources', [])): action_name = rule_name + '_' + str(count) rule_source_dirname, rule_source_basename = os.path.split(rule_source) rule_source_root, rule_source_ext = os.path.splitext(rule_source_basename) SetVariable(output, 'RULE_INPUT_PATH', rule_source) SetVariable(output, 'RULE_INPUT_DIRNAME', rule_source_dirname) SetVariable(output, 'RULE_INPUT_NAME', rule_source_basename) SetVariable(output, 'RULE_INPUT_ROOT', rule_source_root) SetVariable(output, 'RULE_INPUT_EXT', rule_source_ext) # Build up a list of outputs. # Collect the output dirs we'll need. dirs = set(dir for dir in (os.path.dirname(o) for o in outputs) if dir) # Create variables for the output, as 'local' variable will be unset. these_outputs = [] for output_index, out in enumerate(outputs): output_name = action_name + '_' + str(output_index) SetVariable(output, output_name, NormjoinRulePathForceCMakeSource(path_to_gyp, out, rule_source)) if int(rule.get('process_outputs_as_sources', False)): extra_sources.append(('${' + output_name + '}', out)) these_outputs.append('${' + output_name + '}') var_outputs.append('${' + output_name + '}') # add_custom_command output.write('add_custom_command(OUTPUT\n') for out in these_outputs: output.write(' ') output.write(out) output.write('\n') for directory in dirs: output.write(' COMMAND ${CMAKE_COMMAND} -E make_directory ') output.write(directory) output.write('\n') output.write(' COMMAND ') output.write(gyp.common.EncodePOSIXShellList(rule['action'])) output.write('\n') output.write(' DEPENDS ') WriteVariable(output, inputs_name) output.write(' ') output.write(NormjoinPath(path_to_gyp, rule_source)) output.write('\n') # CMAKE_CURRENT_LIST_DIR is where the CMakeLists.txt lives. # The cwd is the current build directory. output.write(' WORKING_DIRECTORY ${CMAKE_CURRENT_LIST_DIR}/') output.write(path_to_gyp) output.write('\n') output.write(' COMMENT ') if 'message' in rule: output.write(rule['message']) else: output.write(action_name) output.write('\n') output.write(' VERBATIM\n') output.write(')\n') UnsetVariable(output, 'RULE_INPUT_PATH') UnsetVariable(output, 'RULE_INPUT_DIRNAME') UnsetVariable(output, 'RULE_INPUT_NAME') UnsetVariable(output, 'RULE_INPUT_ROOT') UnsetVariable(output, 'RULE_INPUT_EXT') # add_custom_target output.write('add_custom_target(') output.write(rule_name) output.write(' DEPENDS\n') for out in var_outputs: output.write(' ') output.write(out) output.write('\n') output.write('SOURCES ') WriteVariable(output, inputs_name) output.write('\n') for rule_source in rule.get('rule_sources', []): output.write(' ') output.write(NormjoinPath(path_to_gyp, rule_source)) output.write('\n') output.write(')\n') extra_deps.append(rule_name)
[ "def", "WriteRules", "(", "target_name", ",", "rules", ",", "extra_sources", ",", "extra_deps", ",", "path_to_gyp", ",", "output", ")", ":", "for", "rule", "in", "rules", ":", "rule_name", "=", "StringToCMakeTargetName", "(", "target_name", "+", "'__'", "+", "rule", "[", "'rule_name'", "]", ")", "inputs", "=", "rule", ".", "get", "(", "'inputs'", ",", "[", "]", ")", "inputs_name", "=", "rule_name", "+", "'__input'", "SetVariableList", "(", "output", ",", "inputs_name", ",", "[", "NormjoinPathForceCMakeSource", "(", "path_to_gyp", ",", "dep", ")", "for", "dep", "in", "inputs", "]", ")", "outputs", "=", "rule", "[", "'outputs'", "]", "var_outputs", "=", "[", "]", "for", "count", ",", "rule_source", "in", "enumerate", "(", "rule", ".", "get", "(", "'rule_sources'", ",", "[", "]", ")", ")", ":", "action_name", "=", "rule_name", "+", "'_'", "+", "str", "(", "count", ")", "rule_source_dirname", ",", "rule_source_basename", "=", "os", ".", "path", ".", "split", "(", "rule_source", ")", "rule_source_root", ",", "rule_source_ext", "=", "os", ".", "path", ".", "splitext", "(", "rule_source_basename", ")", "SetVariable", "(", "output", ",", "'RULE_INPUT_PATH'", ",", "rule_source", ")", "SetVariable", "(", "output", ",", "'RULE_INPUT_DIRNAME'", ",", "rule_source_dirname", ")", "SetVariable", "(", "output", ",", "'RULE_INPUT_NAME'", ",", "rule_source_basename", ")", "SetVariable", "(", "output", ",", "'RULE_INPUT_ROOT'", ",", "rule_source_root", ")", "SetVariable", "(", "output", ",", "'RULE_INPUT_EXT'", ",", "rule_source_ext", ")", "# Build up a list of outputs.", "# Collect the output dirs we'll need.", "dirs", "=", "set", "(", "dir", "for", "dir", "in", "(", "os", ".", "path", ".", "dirname", "(", "o", ")", "for", "o", "in", "outputs", ")", "if", "dir", ")", "# Create variables for the output, as 'local' variable will be unset.", "these_outputs", "=", "[", "]", "for", "output_index", ",", "out", "in", "enumerate", "(", "outputs", ")", ":", "output_name", "=", "action_name", "+", "'_'", "+", "str", "(", "output_index", ")", "SetVariable", "(", "output", ",", "output_name", ",", "NormjoinRulePathForceCMakeSource", "(", "path_to_gyp", ",", "out", ",", "rule_source", ")", ")", "if", "int", "(", "rule", ".", "get", "(", "'process_outputs_as_sources'", ",", "False", ")", ")", ":", "extra_sources", ".", "append", "(", "(", "'${'", "+", "output_name", "+", "'}'", ",", "out", ")", ")", "these_outputs", ".", "append", "(", "'${'", "+", "output_name", "+", "'}'", ")", "var_outputs", ".", "append", "(", "'${'", "+", "output_name", "+", "'}'", ")", "# add_custom_command", "output", ".", "write", "(", "'add_custom_command(OUTPUT\\n'", ")", "for", "out", "in", "these_outputs", ":", "output", ".", "write", "(", "' '", ")", "output", ".", "write", "(", "out", ")", "output", ".", "write", "(", "'\\n'", ")", "for", "directory", "in", "dirs", ":", "output", ".", "write", "(", "' COMMAND ${CMAKE_COMMAND} -E make_directory '", ")", "output", ".", "write", "(", "directory", ")", "output", ".", "write", "(", "'\\n'", ")", "output", ".", "write", "(", "' COMMAND '", ")", "output", ".", "write", "(", "gyp", ".", "common", ".", "EncodePOSIXShellList", "(", "rule", "[", "'action'", "]", ")", ")", "output", ".", "write", "(", "'\\n'", ")", "output", ".", "write", "(", "' DEPENDS '", ")", "WriteVariable", "(", "output", ",", "inputs_name", ")", "output", ".", "write", "(", "' '", ")", "output", ".", "write", "(", "NormjoinPath", "(", "path_to_gyp", ",", "rule_source", ")", ")", "output", ".", "write", "(", "'\\n'", ")", "# CMAKE_CURRENT_LIST_DIR is where the CMakeLists.txt lives.", "# The cwd is the current build directory.", "output", ".", "write", "(", "' WORKING_DIRECTORY ${CMAKE_CURRENT_LIST_DIR}/'", ")", "output", ".", "write", "(", "path_to_gyp", ")", "output", ".", "write", "(", "'\\n'", ")", "output", ".", "write", "(", "' COMMENT '", ")", "if", "'message'", "in", "rule", ":", "output", ".", "write", "(", "rule", "[", "'message'", "]", ")", "else", ":", "output", ".", "write", "(", "action_name", ")", "output", ".", "write", "(", "'\\n'", ")", "output", ".", "write", "(", "' VERBATIM\\n'", ")", "output", ".", "write", "(", "')\\n'", ")", "UnsetVariable", "(", "output", ",", "'RULE_INPUT_PATH'", ")", "UnsetVariable", "(", "output", ",", "'RULE_INPUT_DIRNAME'", ")", "UnsetVariable", "(", "output", ",", "'RULE_INPUT_NAME'", ")", "UnsetVariable", "(", "output", ",", "'RULE_INPUT_ROOT'", ")", "UnsetVariable", "(", "output", ",", "'RULE_INPUT_EXT'", ")", "# add_custom_target", "output", ".", "write", "(", "'add_custom_target('", ")", "output", ".", "write", "(", "rule_name", ")", "output", ".", "write", "(", "' DEPENDS\\n'", ")", "for", "out", "in", "var_outputs", ":", "output", ".", "write", "(", "' '", ")", "output", ".", "write", "(", "out", ")", "output", ".", "write", "(", "'\\n'", ")", "output", ".", "write", "(", "'SOURCES '", ")", "WriteVariable", "(", "output", ",", "inputs_name", ")", "output", ".", "write", "(", "'\\n'", ")", "for", "rule_source", "in", "rule", ".", "get", "(", "'rule_sources'", ",", "[", "]", ")", ":", "output", ".", "write", "(", "' '", ")", "output", ".", "write", "(", "NormjoinPath", "(", "path_to_gyp", ",", "rule_source", ")", ")", "output", ".", "write", "(", "'\\n'", ")", "output", ".", "write", "(", "')\\n'", ")", "extra_deps", ".", "append", "(", "rule_name", ")" ]
https://github.com/domino-team/openwrt-cc/blob/8b181297c34d14d3ca521cc9f31430d561dbc688/package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/cmake.py#L329-L440
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
scripts/BilbyCustomFunctions_Reduction.py
python
string_boolean
(line)
return bool_string
Convert string to boolean; needed to read "true" and "false" from the csv Data reduction settings table
Convert string to boolean; needed to read "true" and "false" from the csv Data reduction settings table
[ "Convert", "string", "to", "boolean", ";", "needed", "to", "read", "true", "and", "false", "from", "the", "csv", "Data", "reduction", "settings", "table" ]
def string_boolean(line): """ Convert string to boolean; needed to read "true" and "false" from the csv Data reduction settings table """ if line == 'false': bool_string = False elif line == 'true': bool_string = True else: print("Check value of {}".format(line)) print("It must be either True or False") sys.exit() return bool_string
[ "def", "string_boolean", "(", "line", ")", ":", "if", "line", "==", "'false'", ":", "bool_string", "=", "False", "elif", "line", "==", "'true'", ":", "bool_string", "=", "True", "else", ":", "print", "(", "\"Check value of {}\"", ".", "format", "(", "line", ")", ")", "print", "(", "\"It must be either True or False\"", ")", "sys", ".", "exit", "(", ")", "return", "bool_string" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/scripts/BilbyCustomFunctions_Reduction.py#L20-L31
blackberry/Boost
fc90c3fde129c62565c023f091eddc4a7ed9902b
tools/build/v2/build/engine.py
python
Engine.register_action
(self, action_name, command, bound_list = [], flags = [], function = None)
Creates a new build engine action. Creates on bjam side an action named 'action_name', with 'command' as the command to be executed, 'bound_variables' naming the list of variables bound when the command is executed and specified flag. If 'function' is not None, it should be a callable taking three parameters: - targets - sources - instance of the property_set class This function will be called by set_update_action, and can set additional target variables.
Creates a new build engine action.
[ "Creates", "a", "new", "build", "engine", "action", "." ]
def register_action (self, action_name, command, bound_list = [], flags = [], function = None): """Creates a new build engine action. Creates on bjam side an action named 'action_name', with 'command' as the command to be executed, 'bound_variables' naming the list of variables bound when the command is executed and specified flag. If 'function' is not None, it should be a callable taking three parameters: - targets - sources - instance of the property_set class This function will be called by set_update_action, and can set additional target variables. """ if self.actions.has_key(action_name): raise "Bjam action %s is already defined" % action_name assert(isinstance(flags, list)) bjam_flags = reduce(operator.or_, (action_modifiers[flag] for flag in flags), 0) # We allow command to be empty so that we can define 'action' as pure # python function that would do some conditional logic and then relay # to other actions. assert command or function if command: bjam_interface.define_action(action_name, command, bound_list, bjam_flags) self.actions[action_name] = BjamAction(action_name, function)
[ "def", "register_action", "(", "self", ",", "action_name", ",", "command", ",", "bound_list", "=", "[", "]", ",", "flags", "=", "[", "]", ",", "function", "=", "None", ")", ":", "if", "self", ".", "actions", ".", "has_key", "(", "action_name", ")", ":", "raise", "\"Bjam action %s is already defined\"", "%", "action_name", "assert", "(", "isinstance", "(", "flags", ",", "list", ")", ")", "bjam_flags", "=", "reduce", "(", "operator", ".", "or_", ",", "(", "action_modifiers", "[", "flag", "]", "for", "flag", "in", "flags", ")", ",", "0", ")", "# We allow command to be empty so that we can define 'action' as pure", "# python function that would do some conditional logic and then relay", "# to other actions.", "assert", "command", "or", "function", "if", "command", ":", "bjam_interface", ".", "define_action", "(", "action_name", ",", "command", ",", "bound_list", ",", "bjam_flags", ")", "self", ".", "actions", "[", "action_name", "]", "=", "BjamAction", "(", "action_name", ",", "function", ")" ]
https://github.com/blackberry/Boost/blob/fc90c3fde129c62565c023f091eddc4a7ed9902b/tools/build/v2/build/engine.py#L111-L142
pmq20/node-packer
12c46c6e44fbc14d9ee645ebd17d5296b324f7e0
current/tools/gyp/pylib/gyp/xcode_emulation.py
python
XcodeSettings._GetBundleBinaryPath
(self)
return os.path.join(self.GetBundleExecutableFolderPath(), \ self.GetExecutableName())
Returns the name of the bundle binary of by this target. E.g. Chromium.app/Contents/MacOS/Chromium. Only valid for bundles.
Returns the name of the bundle binary of by this target. E.g. Chromium.app/Contents/MacOS/Chromium. Only valid for bundles.
[ "Returns", "the", "name", "of", "the", "bundle", "binary", "of", "by", "this", "target", ".", "E", ".", "g", ".", "Chromium", ".", "app", "/", "Contents", "/", "MacOS", "/", "Chromium", ".", "Only", "valid", "for", "bundles", "." ]
def _GetBundleBinaryPath(self): """Returns the name of the bundle binary of by this target. E.g. Chromium.app/Contents/MacOS/Chromium. Only valid for bundles.""" assert self._IsBundle() return os.path.join(self.GetBundleExecutableFolderPath(), \ self.GetExecutableName())
[ "def", "_GetBundleBinaryPath", "(", "self", ")", ":", "assert", "self", ".", "_IsBundle", "(", ")", "return", "os", ".", "path", ".", "join", "(", "self", ".", "GetBundleExecutableFolderPath", "(", ")", ",", "self", ".", "GetExecutableName", "(", ")", ")" ]
https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/current/tools/gyp/pylib/gyp/xcode_emulation.py#L424-L429
Alexhuszagh/rust-lexical
01fcdcf8efc8850edb35d8fc65fd5f31bd0981a0
scripts/size.py
python
plot_bar
( xlabel=None, data=None, path=None, title=None, key=None )
Plot a generic bar chart.
Plot a generic bar chart.
[ "Plot", "a", "generic", "bar", "chart", "." ]
def plot_bar( xlabel=None, data=None, path=None, title=None, key=None ): '''Plot a generic bar chart.''' keys = [i.split('_') for i in data.keys()] xticks = sorted({i[1] for i in keys}) libraries = sorted({i[0] for i in keys}) def plot_ax(ax, xticks): '''Plot an axis with various subfigures.''' length = len(xticks) width = 0.4 / len(libraries) x = np.arange(length) for index, library in enumerate(libraries): xi = x + width * index yi = [data[f'{library}_{i}'] for i in xticks] plt.bar(xi, yi, width, label=library, alpha=.7) ax.grid(color='white', linestyle='solid') ax.set_title(title) ax.set_xlabel(xlabel) ax.set_ylabel('Size (B)') ax.set_yscale('log') ax.set_xticks(x + width * len(libraries) / 4) ax.set_xticklabels(xticks, rotation=-45) ax.yaxis.set_major_formatter(ticker.FuncFormatter(lambda x, p: prettyify(x))) ax.legend(libraries, fancybox=True, framealpha=1, shadow=True, borderpad=1) fig = plt.figure(figsize=(10, 8)) index = 1 ax = fig.add_subplot(1, 1, 1) plot_ax(ax, xticks) fig.savefig(path, format='svg') fig.clf()
[ "def", "plot_bar", "(", "xlabel", "=", "None", ",", "data", "=", "None", ",", "path", "=", "None", ",", "title", "=", "None", ",", "key", "=", "None", ")", ":", "keys", "=", "[", "i", ".", "split", "(", "'_'", ")", "for", "i", "in", "data", ".", "keys", "(", ")", "]", "xticks", "=", "sorted", "(", "{", "i", "[", "1", "]", "for", "i", "in", "keys", "}", ")", "libraries", "=", "sorted", "(", "{", "i", "[", "0", "]", "for", "i", "in", "keys", "}", ")", "def", "plot_ax", "(", "ax", ",", "xticks", ")", ":", "'''Plot an axis with various subfigures.'''", "length", "=", "len", "(", "xticks", ")", "width", "=", "0.4", "/", "len", "(", "libraries", ")", "x", "=", "np", ".", "arange", "(", "length", ")", "for", "index", ",", "library", "in", "enumerate", "(", "libraries", ")", ":", "xi", "=", "x", "+", "width", "*", "index", "yi", "=", "[", "data", "[", "f'{library}_{i}'", "]", "for", "i", "in", "xticks", "]", "plt", ".", "bar", "(", "xi", ",", "yi", ",", "width", ",", "label", "=", "library", ",", "alpha", "=", ".7", ")", "ax", ".", "grid", "(", "color", "=", "'white'", ",", "linestyle", "=", "'solid'", ")", "ax", ".", "set_title", "(", "title", ")", "ax", ".", "set_xlabel", "(", "xlabel", ")", "ax", ".", "set_ylabel", "(", "'Size (B)'", ")", "ax", ".", "set_yscale", "(", "'log'", ")", "ax", ".", "set_xticks", "(", "x", "+", "width", "*", "len", "(", "libraries", ")", "/", "4", ")", "ax", ".", "set_xticklabels", "(", "xticks", ",", "rotation", "=", "-", "45", ")", "ax", ".", "yaxis", ".", "set_major_formatter", "(", "ticker", ".", "FuncFormatter", "(", "lambda", "x", ",", "p", ":", "prettyify", "(", "x", ")", ")", ")", "ax", ".", "legend", "(", "libraries", ",", "fancybox", "=", "True", ",", "framealpha", "=", "1", ",", "shadow", "=", "True", ",", "borderpad", "=", "1", ")", "fig", "=", "plt", ".", "figure", "(", "figsize", "=", "(", "10", ",", "8", ")", ")", "index", "=", "1", "ax", "=", "fig", ".", "add_subplot", "(", "1", ",", "1", ",", "1", ")", "plot_ax", "(", "ax", ",", "xticks", ")", "fig", ".", "savefig", "(", "path", ",", "format", "=", "'svg'", ")", "fig", ".", "clf", "(", ")" ]
https://github.com/Alexhuszagh/rust-lexical/blob/01fcdcf8efc8850edb35d8fc65fd5f31bd0981a0/scripts/size.py#L101-L141
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/matlib.py
python
eye
(n,M=None, k=0, dtype=float, order='C')
return asmatrix(np.eye(n, M=M, k=k, dtype=dtype, order=order))
Return a matrix with ones on the diagonal and zeros elsewhere. Parameters ---------- n : int Number of rows in the output. M : int, optional Number of columns in the output, defaults to `n`. k : int, optional Index of the diagonal: 0 refers to the main diagonal, a positive value refers to an upper diagonal, and a negative value to a lower diagonal. dtype : dtype, optional Data-type of the returned matrix. order : {'C', 'F'}, optional Whether the output should be stored in row-major (C-style) or column-major (Fortran-style) order in memory. .. versionadded:: 1.14.0 Returns ------- I : matrix A `n` x `M` matrix where all elements are equal to zero, except for the `k`-th diagonal, whose values are equal to one. See Also -------- numpy.eye : Equivalent array function. identity : Square identity matrix. Examples -------- >>> import numpy.matlib >>> np.matlib.eye(3, k=1, dtype=float) matrix([[0., 1., 0.], [0., 0., 1.], [0., 0., 0.]])
Return a matrix with ones on the diagonal and zeros elsewhere.
[ "Return", "a", "matrix", "with", "ones", "on", "the", "diagonal", "and", "zeros", "elsewhere", "." ]
def eye(n,M=None, k=0, dtype=float, order='C'): """ Return a matrix with ones on the diagonal and zeros elsewhere. Parameters ---------- n : int Number of rows in the output. M : int, optional Number of columns in the output, defaults to `n`. k : int, optional Index of the diagonal: 0 refers to the main diagonal, a positive value refers to an upper diagonal, and a negative value to a lower diagonal. dtype : dtype, optional Data-type of the returned matrix. order : {'C', 'F'}, optional Whether the output should be stored in row-major (C-style) or column-major (Fortran-style) order in memory. .. versionadded:: 1.14.0 Returns ------- I : matrix A `n` x `M` matrix where all elements are equal to zero, except for the `k`-th diagonal, whose values are equal to one. See Also -------- numpy.eye : Equivalent array function. identity : Square identity matrix. Examples -------- >>> import numpy.matlib >>> np.matlib.eye(3, k=1, dtype=float) matrix([[0., 1., 0.], [0., 0., 1.], [0., 0., 0.]]) """ return asmatrix(np.eye(n, M=M, k=k, dtype=dtype, order=order))
[ "def", "eye", "(", "n", ",", "M", "=", "None", ",", "k", "=", "0", ",", "dtype", "=", "float", ",", "order", "=", "'C'", ")", ":", "return", "asmatrix", "(", "np", ".", "eye", "(", "n", ",", "M", "=", "M", ",", "k", "=", "k", ",", "dtype", "=", "dtype", ",", "order", "=", "order", ")", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/matlib.py#L176-L218
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py3/pandas/core/dtypes/base.py
python
ExtensionDtype._get_common_dtype
(self, dtypes: list[DtypeObj])
Return the common dtype, if one exists. Used in `find_common_type` implementation. This is for example used to determine the resulting dtype in a concat operation. If no common dtype exists, return None (which gives the other dtypes the chance to determine a common dtype). If all dtypes in the list return None, then the common dtype will be "object" dtype (this means it is never needed to return "object" dtype from this method itself). Parameters ---------- dtypes : list of dtypes The dtypes for which to determine a common dtype. This is a list of np.dtype or ExtensionDtype instances. Returns ------- Common dtype (np.dtype or ExtensionDtype) or None
Return the common dtype, if one exists.
[ "Return", "the", "common", "dtype", "if", "one", "exists", "." ]
def _get_common_dtype(self, dtypes: list[DtypeObj]) -> DtypeObj | None: """ Return the common dtype, if one exists. Used in `find_common_type` implementation. This is for example used to determine the resulting dtype in a concat operation. If no common dtype exists, return None (which gives the other dtypes the chance to determine a common dtype). If all dtypes in the list return None, then the common dtype will be "object" dtype (this means it is never needed to return "object" dtype from this method itself). Parameters ---------- dtypes : list of dtypes The dtypes for which to determine a common dtype. This is a list of np.dtype or ExtensionDtype instances. Returns ------- Common dtype (np.dtype or ExtensionDtype) or None """ if len(set(dtypes)) == 1: # only itself return self else: return None
[ "def", "_get_common_dtype", "(", "self", ",", "dtypes", ":", "list", "[", "DtypeObj", "]", ")", "->", "DtypeObj", "|", "None", ":", "if", "len", "(", "set", "(", "dtypes", ")", ")", "==", "1", ":", "# only itself", "return", "self", "else", ":", "return", "None" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/core/dtypes/base.py#L335-L361
microsoft/BlingFire
7634ad43b521ee6a596266d82c3f0c46cd43e222
scripts/tokenization.py
python
_is_control
(char)
return False
Checks whether `chars` is a control character.
Checks whether `chars` is a control character.
[ "Checks", "whether", "chars", "is", "a", "control", "character", "." ]
def _is_control(char): """Checks whether `chars` is a control character.""" # These are technically control characters but we count them as whitespace # characters. if char == "\t" or char == "\n" or char == "\r": return False cat = unicodedata.category(char) if cat.startswith("C"): return True return False
[ "def", "_is_control", "(", "char", ")", ":", "# These are technically control characters but we count them as whitespace", "# characters.", "if", "char", "==", "\"\\t\"", "or", "char", "==", "\"\\n\"", "or", "char", "==", "\"\\r\"", ":", "return", "False", "cat", "=", "unicodedata", ".", "category", "(", "char", ")", "if", "cat", ".", "startswith", "(", "\"C\"", ")", ":", "return", "True", "return", "False" ]
https://github.com/microsoft/BlingFire/blob/7634ad43b521ee6a596266d82c3f0c46cd43e222/scripts/tokenization.py#L374-L383
PaddlePaddle/Paddle
1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c
python/paddle/fluid/dygraph/amp/loss_scaler.py
python
AmpScaler.set_incr_every_n_steps
(self, new_incr_every_n_steps)
Set the num `n` by `new_incr_every_n_steps`, `n` represent increases loss scaling every `n` consecutive steps with finite gradients. Args: new_incr_every_n_steps(int): The new_incr_every_n_steps used to update the num `n`, `n` represent increases loss scaling every `n` consecutive steps with finite gradients.
Set the num `n` by `new_incr_every_n_steps`, `n` represent increases loss scaling every `n` consecutive steps with finite gradients.
[ "Set", "the", "num", "n", "by", "new_incr_every_n_steps", "n", "represent", "increases", "loss", "scaling", "every", "n", "consecutive", "steps", "with", "finite", "gradients", "." ]
def set_incr_every_n_steps(self, new_incr_every_n_steps): """ Set the num `n` by `new_incr_every_n_steps`, `n` represent increases loss scaling every `n` consecutive steps with finite gradients. Args: new_incr_every_n_steps(int): The new_incr_every_n_steps used to update the num `n`, `n` represent increases loss scaling every `n` consecutive steps with finite gradients. """ self._incr_every_n_steps = new_incr_every_n_steps
[ "def", "set_incr_every_n_steps", "(", "self", ",", "new_incr_every_n_steps", ")", ":", "self", ".", "_incr_every_n_steps", "=", "new_incr_every_n_steps" ]
https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/fluid/dygraph/amp/loss_scaler.py#L418-L425
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/python2_version/klampt/src/motionplanning.py
python
CSpaceInterface.__init__
(self, *args)
__init__(CSpaceInterface self) -> CSpaceInterface __init__(CSpaceInterface self, CSpaceInterface arg2) -> CSpaceInterface
__init__(CSpaceInterface self) -> CSpaceInterface __init__(CSpaceInterface self, CSpaceInterface arg2) -> CSpaceInterface
[ "__init__", "(", "CSpaceInterface", "self", ")", "-", ">", "CSpaceInterface", "__init__", "(", "CSpaceInterface", "self", "CSpaceInterface", "arg2", ")", "-", ">", "CSpaceInterface" ]
def __init__(self, *args): """ __init__(CSpaceInterface self) -> CSpaceInterface __init__(CSpaceInterface self, CSpaceInterface arg2) -> CSpaceInterface """ this = _motionplanning.new_CSpaceInterface(*args) try: self.this.append(this) except Exception: self.this = this
[ "def", "__init__", "(", "self", ",", "*", "args", ")", ":", "this", "=", "_motionplanning", ".", "new_CSpaceInterface", "(", "*", "args", ")", "try", ":", "self", ".", "this", ".", "append", "(", "this", ")", "except", "Exception", ":", "self", ".", "this", "=", "this" ]
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/python2_version/klampt/src/motionplanning.py#L310-L322
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/pkg_resources/_vendor/pyparsing.py
python
ParserElement.leaveWhitespace
( self )
return self
Disables the skipping of whitespace before matching the characters in the C{ParserElement}'s defined pattern. This is normally only used internally by the pyparsing module, but may be needed in some whitespace-sensitive grammars.
Disables the skipping of whitespace before matching the characters in the C{ParserElement}'s defined pattern. This is normally only used internally by the pyparsing module, but may be needed in some whitespace-sensitive grammars.
[ "Disables", "the", "skipping", "of", "whitespace", "before", "matching", "the", "characters", "in", "the", "C", "{", "ParserElement", "}", "s", "defined", "pattern", ".", "This", "is", "normally", "only", "used", "internally", "by", "the", "pyparsing", "module", "but", "may", "be", "needed", "in", "some", "whitespace", "-", "sensitive", "grammars", "." ]
def leaveWhitespace( self ): """ Disables the skipping of whitespace before matching the characters in the C{ParserElement}'s defined pattern. This is normally only used internally by the pyparsing module, but may be needed in some whitespace-sensitive grammars. """ self.skipWhitespace = False return self
[ "def", "leaveWhitespace", "(", "self", ")", ":", "self", ".", "skipWhitespace", "=", "False", "return", "self" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/pkg_resources/_vendor/pyparsing.py#L2011-L2018
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/protobuf/py2/google/protobuf/text_format.py
python
Tokenizer.ParseErrorPreviousToken
(self, message)
return ParseError(message, self._previous_line + 1, self._previous_column + 1)
Creates and *returns* a ParseError for the previously read token. Args: message: A message to set for the exception. Returns: A ParseError instance.
Creates and *returns* a ParseError for the previously read token.
[ "Creates", "and", "*", "returns", "*", "a", "ParseError", "for", "the", "previously", "read", "token", "." ]
def ParseErrorPreviousToken(self, message): """Creates and *returns* a ParseError for the previously read token. Args: message: A message to set for the exception. Returns: A ParseError instance. """ return ParseError(message, self._previous_line + 1, self._previous_column + 1)
[ "def", "ParseErrorPreviousToken", "(", "self", ",", "message", ")", ":", "return", "ParseError", "(", "message", ",", "self", ".", "_previous_line", "+", "1", ",", "self", ".", "_previous_column", "+", "1", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/protobuf/py2/google/protobuf/text_format.py#L1531-L1541
etternagame/etterna
8775f74ac9c353320128609d4b4150672e9a6d04
extern/crashpad/crashpad/third_party/mini_chromium/mini_chromium/build/ios/sdk_info.py
python
SplitVersion
(version)
return itertools.islice(itertools.chain(version, itertools.repeat('0')), 0, 3)
Splits the Xcode version to 3 values. >>> list(SplitVersion('8.2.1.1')) ['8', '2', '1'] >>> list(SplitVersion('9.3')) ['9', '3', '0'] >>> list(SplitVersion('10.0')) ['10', '0', '0']
Splits the Xcode version to 3 values.
[ "Splits", "the", "Xcode", "version", "to", "3", "values", "." ]
def SplitVersion(version): """Splits the Xcode version to 3 values. >>> list(SplitVersion('8.2.1.1')) ['8', '2', '1'] >>> list(SplitVersion('9.3')) ['9', '3', '0'] >>> list(SplitVersion('10.0')) ['10', '0', '0'] """ version = version.split('.') return itertools.islice(itertools.chain(version, itertools.repeat('0')), 0, 3)
[ "def", "SplitVersion", "(", "version", ")", ":", "version", "=", "version", ".", "split", "(", "'.'", ")", "return", "itertools", ".", "islice", "(", "itertools", ".", "chain", "(", "version", ",", "itertools", ".", "repeat", "(", "'0'", ")", ")", ",", "0", ",", "3", ")" ]
https://github.com/etternagame/etterna/blob/8775f74ac9c353320128609d4b4150672e9a6d04/extern/crashpad/crashpad/third_party/mini_chromium/mini_chromium/build/ios/sdk_info.py#L21-L32
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/Jinja2/py2/jinja2/environment.py
python
Environment.compile_expression
(self, source, undefined_to_none=True)
return TemplateExpression(template, undefined_to_none)
A handy helper method that returns a callable that accepts keyword arguments that appear as variables in the expression. If called it returns the result of the expression. This is useful if applications want to use the same rules as Jinja in template "configuration files" or similar situations. Example usage: >>> env = Environment() >>> expr = env.compile_expression('foo == 42') >>> expr(foo=23) False >>> expr(foo=42) True Per default the return value is converted to `None` if the expression returns an undefined value. This can be changed by setting `undefined_to_none` to `False`. >>> env.compile_expression('var')() is None True >>> env.compile_expression('var', undefined_to_none=False)() Undefined .. versionadded:: 2.1
A handy helper method that returns a callable that accepts keyword arguments that appear as variables in the expression. If called it returns the result of the expression.
[ "A", "handy", "helper", "method", "that", "returns", "a", "callable", "that", "accepts", "keyword", "arguments", "that", "appear", "as", "variables", "in", "the", "expression", ".", "If", "called", "it", "returns", "the", "result", "of", "the", "expression", "." ]
def compile_expression(self, source, undefined_to_none=True): """A handy helper method that returns a callable that accepts keyword arguments that appear as variables in the expression. If called it returns the result of the expression. This is useful if applications want to use the same rules as Jinja in template "configuration files" or similar situations. Example usage: >>> env = Environment() >>> expr = env.compile_expression('foo == 42') >>> expr(foo=23) False >>> expr(foo=42) True Per default the return value is converted to `None` if the expression returns an undefined value. This can be changed by setting `undefined_to_none` to `False`. >>> env.compile_expression('var')() is None True >>> env.compile_expression('var', undefined_to_none=False)() Undefined .. versionadded:: 2.1 """ parser = Parser(self, source, state="variable") try: expr = parser.parse_expression() if not parser.stream.eos: raise TemplateSyntaxError( "chunk after expression", parser.stream.current.lineno, None, None ) expr.set_environment(self) except TemplateSyntaxError: if sys.exc_info() is not None: self.handle_exception(source=source) body = [nodes.Assign(nodes.Name("result", "store"), expr, lineno=1)] template = self.from_string(nodes.Template(body, lineno=1)) return TemplateExpression(template, undefined_to_none)
[ "def", "compile_expression", "(", "self", ",", "source", ",", "undefined_to_none", "=", "True", ")", ":", "parser", "=", "Parser", "(", "self", ",", "source", ",", "state", "=", "\"variable\"", ")", "try", ":", "expr", "=", "parser", ".", "parse_expression", "(", ")", "if", "not", "parser", ".", "stream", ".", "eos", ":", "raise", "TemplateSyntaxError", "(", "\"chunk after expression\"", ",", "parser", ".", "stream", ".", "current", ".", "lineno", ",", "None", ",", "None", ")", "expr", ".", "set_environment", "(", "self", ")", "except", "TemplateSyntaxError", ":", "if", "sys", ".", "exc_info", "(", ")", "is", "not", "None", ":", "self", ".", "handle_exception", "(", "source", "=", "source", ")", "body", "=", "[", "nodes", ".", "Assign", "(", "nodes", ".", "Name", "(", "\"result\"", ",", "\"store\"", ")", ",", "expr", ",", "lineno", "=", "1", ")", "]", "template", "=", "self", ".", "from_string", "(", "nodes", ".", "Template", "(", "body", ",", "lineno", "=", "1", ")", ")", "return", "TemplateExpression", "(", "template", ",", "undefined_to_none", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/Jinja2/py2/jinja2/environment.py#L640-L682
jackaudio/jack2
21b293dbc37d42446141a08922cdec0d2550c6a0
waflib/Utils.py
python
lru_cache.__init__
(self, maxlen=100)
Maximum amount of elements in the cache
Maximum amount of elements in the cache
[ "Maximum", "amount", "of", "elements", "in", "the", "cache" ]
def __init__(self, maxlen=100): self.maxlen = maxlen """ Maximum amount of elements in the cache """ self.table = {} """ Mapping key-value """ self.head = lru_node() self.head.next = self.head self.head.prev = self.head
[ "def", "__init__", "(", "self", ",", "maxlen", "=", "100", ")", ":", "self", ".", "maxlen", "=", "maxlen", "self", ".", "table", "=", "{", "}", "\"\"\"\n\t\tMapping key-value\n\t\t\"\"\"", "self", ".", "head", "=", "lru_node", "(", ")", "self", ".", "head", ".", "next", "=", "self", ".", "head", "self", ".", "head", ".", "prev", "=", "self", ".", "head" ]
https://github.com/jackaudio/jack2/blob/21b293dbc37d42446141a08922cdec0d2550c6a0/waflib/Utils.py#L133-L144
microsoft/ivy
9f3c7ecc0b2383129fdd0953e10890d98d09a82d
ivy/ivy_dafny_grammar.py
python
p_expr_expr_LE_expr
(p)
expr : expr LE expr
expr : expr LE expr
[ "expr", ":", "expr", "LE", "expr" ]
def p_expr_expr_LE_expr(p): 'expr : expr LE expr' p[0] = da.App(da.InfixRelation(p[2]),p[1],p[3]) p[0].lineno = p.lineno(2)
[ "def", "p_expr_expr_LE_expr", "(", "p", ")", ":", "p", "[", "0", "]", "=", "da", ".", "App", "(", "da", ".", "InfixRelation", "(", "p", "[", "2", "]", ")", ",", "p", "[", "1", "]", ",", "p", "[", "3", "]", ")", "p", "[", "0", "]", ".", "lineno", "=", "p", ".", "lineno", "(", "2", ")" ]
https://github.com/microsoft/ivy/blob/9f3c7ecc0b2383129fdd0953e10890d98d09a82d/ivy/ivy_dafny_grammar.py#L212-L215
natanielruiz/android-yolo
1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f
jni-build/jni/include/tensorflow/contrib/distributions/python/ops/exponential.py
python
Exponential.__init__
( self, lam, validate_args=True, allow_nan_stats=False, name="Exponential")
Construct Exponential distribution with parameter `lam`. Args: lam: Floating point tensor, the rate of the distribution(s). `lam` must contain only positive values. validate_args: Whether to assert that `lam > 0`, and that `x > 0` in the methods `prob(x)` and `log_prob(x)`. If `validate_args` is `False` and the inputs are invalid, correct behavior is not guaranteed. allow_nan_stats: Boolean, default `False`. If `False`, raise an exception if a statistic (e.g. mean/mode/etc...) is undefined for any batch member. If `True`, batch members with valid parameters leading to undefined statistics will return NaN for this statistic. name: The name to prepend to all ops created by this distribution.
Construct Exponential distribution with parameter `lam`.
[ "Construct", "Exponential", "distribution", "with", "parameter", "lam", "." ]
def __init__( self, lam, validate_args=True, allow_nan_stats=False, name="Exponential"): """Construct Exponential distribution with parameter `lam`. Args: lam: Floating point tensor, the rate of the distribution(s). `lam` must contain only positive values. validate_args: Whether to assert that `lam > 0`, and that `x > 0` in the methods `prob(x)` and `log_prob(x)`. If `validate_args` is `False` and the inputs are invalid, correct behavior is not guaranteed. allow_nan_stats: Boolean, default `False`. If `False`, raise an exception if a statistic (e.g. mean/mode/etc...) is undefined for any batch member. If `True`, batch members with valid parameters leading to undefined statistics will return NaN for this statistic. name: The name to prepend to all ops created by this distribution. """ # Even though all statistics of are defined for valid inputs, this is not # true in the parent class "Gamma." Therefore, passing # allow_nan_stats=False # through to the parent class results in unnecessary asserts. with ops.op_scope([lam], name): lam = ops.convert_to_tensor(lam) self._lam = lam super(Exponential, self).__init__( alpha=constant_op.constant(1.0, dtype=lam.dtype), beta=lam, allow_nan_stats=allow_nan_stats, validate_args=validate_args)
[ "def", "__init__", "(", "self", ",", "lam", ",", "validate_args", "=", "True", ",", "allow_nan_stats", "=", "False", ",", "name", "=", "\"Exponential\"", ")", ":", "# Even though all statistics of are defined for valid inputs, this is not", "# true in the parent class \"Gamma.\" Therefore, passing", "# allow_nan_stats=False", "# through to the parent class results in unnecessary asserts.", "with", "ops", ".", "op_scope", "(", "[", "lam", "]", ",", "name", ")", ":", "lam", "=", "ops", ".", "convert_to_tensor", "(", "lam", ")", "self", ".", "_lam", "=", "lam", "super", "(", "Exponential", ",", "self", ")", ".", "__init__", "(", "alpha", "=", "constant_op", ".", "constant", "(", "1.0", ",", "dtype", "=", "lam", ".", "dtype", ")", ",", "beta", "=", "lam", ",", "allow_nan_stats", "=", "allow_nan_stats", ",", "validate_args", "=", "validate_args", ")" ]
https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/contrib/distributions/python/ops/exponential.py#L44-L71
physercoe/starquant
c00cad64d1de2da05081b3dc320ef264c6295e08
cppsrc/fmt-5.3.0/doc/build.py
python
pip_install
(package, commit=None, **kwargs)
Install package using pip.
Install package using pip.
[ "Install", "package", "using", "pip", "." ]
def pip_install(package, commit=None, **kwargs): "Install package using pip." min_version = kwargs.get('min_version') if min_version: from pkg_resources import get_distribution, DistributionNotFound try: installed_version = get_distribution(os.path.basename(package)).version if LooseVersion(installed_version) >= min_version: print('{} {} already installed'.format(package, min_version)) return except DistributionNotFound: pass if commit: package = 'git+https://github.com/{0}.git@{1}'.format(package, commit) print('Installing {0}'.format(package)) check_call(['pip', 'install', package])
[ "def", "pip_install", "(", "package", ",", "commit", "=", "None", ",", "*", "*", "kwargs", ")", ":", "min_version", "=", "kwargs", ".", "get", "(", "'min_version'", ")", "if", "min_version", ":", "from", "pkg_resources", "import", "get_distribution", ",", "DistributionNotFound", "try", ":", "installed_version", "=", "get_distribution", "(", "os", ".", "path", ".", "basename", "(", "package", ")", ")", ".", "version", "if", "LooseVersion", "(", "installed_version", ")", ">=", "min_version", ":", "print", "(", "'{} {} already installed'", ".", "format", "(", "package", ",", "min_version", ")", ")", "return", "except", "DistributionNotFound", ":", "pass", "if", "commit", ":", "package", "=", "'git+https://github.com/{0}.git@{1}'", ".", "format", "(", "package", ",", "commit", ")", "print", "(", "'Installing {0}'", ".", "format", "(", "package", ")", ")", "check_call", "(", "[", "'pip'", ",", "'install'", ",", "package", "]", ")" ]
https://github.com/physercoe/starquant/blob/c00cad64d1de2da05081b3dc320ef264c6295e08/cppsrc/fmt-5.3.0/doc/build.py#L11-L26
Polidea/SiriusObfuscator
b0e590d8130e97856afe578869b83a209e2b19be
SymbolExtractorAndRenamer/ninja/misc/write_fake_manifests.py
python
FileWriter
(path)
Context manager for a ninja_syntax object writing to a file.
Context manager for a ninja_syntax object writing to a file.
[ "Context", "manager", "for", "a", "ninja_syntax", "object", "writing", "to", "a", "file", "." ]
def FileWriter(path): """Context manager for a ninja_syntax object writing to a file.""" try: os.makedirs(os.path.dirname(path)) except OSError: pass f = open(path, 'w') yield ninja_syntax.Writer(f) f.close()
[ "def", "FileWriter", "(", "path", ")", ":", "try", ":", "os", ".", "makedirs", "(", "os", ".", "path", ".", "dirname", "(", "path", ")", ")", "except", "OSError", ":", "pass", "f", "=", "open", "(", "path", ",", "'w'", ")", "yield", "ninja_syntax", ".", "Writer", "(", "f", ")", "f", ".", "close", "(", ")" ]
https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/ninja/misc/write_fake_manifests.py#L215-L223
stack-of-tasks/pinocchio
593d4d43fded997bb9aa2421f4e55294dbd233c4
bindings/python/pinocchio/robot_wrapper.py
python
RobotWrapper.initViewer
(self, *args, **kwargs)
Init the viewer
Init the viewer
[ "Init", "the", "viewer" ]
def initViewer(self, *args, **kwargs): """Init the viewer""" # Set viewer to use to gepetto-gui. if self.viz is None: from .visualize import GepettoVisualizer self.viz = GepettoVisualizer(self.model, self.collision_model, self.visual_model) self.viz.initViewer(*args, **kwargs)
[ "def", "initViewer", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# Set viewer to use to gepetto-gui.", "if", "self", ".", "viz", "is", "None", ":", "from", ".", "visualize", "import", "GepettoVisualizer", "self", ".", "viz", "=", "GepettoVisualizer", "(", "self", ".", "model", ",", "self", ".", "collision_model", ",", "self", ".", "visual_model", ")", "self", ".", "viz", ".", "initViewer", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/stack-of-tasks/pinocchio/blob/593d4d43fded997bb9aa2421f4e55294dbd233c4/bindings/python/pinocchio/robot_wrapper.py#L265-L272
openvinotoolkit/openvino
dedcbeafa8b84cccdc55ca64b8da516682b381c7
src/bindings/python/src/openvino/runtime/opset1/ops.py
python
proposal
( class_probs: Node, bbox_deltas: Node, image_shape: NodeInput, attrs: dict, name: Optional[str] = None, )
return _get_node_factory_opset1().create( "Proposal", [class_probs, bbox_deltas, as_node(image_shape)], attrs )
Filter bounding boxes and outputs only those with the highest prediction confidence. @param class_probs: 4D input floating point tensor with class prediction scores. @param bbox_deltas: 4D input floating point tensor with box logits. @param image_shape: The 1D input tensor with 3 or 4 elements describing image shape. @param attrs: The dictionary containing key, value pairs for attributes. @param name: Optional name for the output node. @return Node representing Proposal operation. * base_size The size of the anchor to which scale and ratio attributes are applied. Range of values: a positive unsigned integer number Default value: None Required: yes * pre_nms_topn The number of bounding boxes before the NMS operation. Range of values: a positive unsigned integer number Default value: None Required: yes * post_nms_topn The number of bounding boxes after the NMS operation. Range of values: a positive unsigned integer number Default value: None Required: yes * nms_thresh The minimum value of the proposal to be taken into consideration. Range of values: a positive floating-point number Default value: None Required: yes * feat_stride The step size to slide over boxes (in pixels). Range of values: a positive unsigned integer Default value: None Required: yes * min_size The minimum size of box to be taken into consideration. Range of values: a positive unsigned integer number Default value: None Required: yes * ratio The ratios for anchor generation. Range of values: a list of floating-point numbers Default value: None Required: yes * scale The scales for anchor generation. Range of values: a list of floating-point numbers Default value: None Required: yes * clip_before_nms The flag that specifies whether to perform clip bounding boxes before non-maximum suppression or not. Range of values: True or False Default value: True Required: no * clip_after_nms The flag that specifies whether to perform clip bounding boxes after non-maximum suppression or not. Range of values: True or False Default value: False Required: no * normalize The flag that specifies whether to perform normalization of output boxes to [0,1] interval or not. Range of values: True or False Default value: False Required: no * box_size_scale Specifies the scale factor applied to logits of box sizes before decoding. Range of values: a positive floating-point number Default value: 1.0 Required: no * box_coordinate_scale Specifies the scale factor applied to logits of box coordinates before decoding. Range of values: a positive floating-point number Default value: 1.0 Required: no * framework Specifies how the box coordinates are calculated. Range of values: "" (empty string) - calculate box coordinates like in Caffe* tensorflow - calculate box coordinates like in the TensorFlow* Object Detection API models Default value: "" (empty string) Required: no Example of attribute dictionary: @code{.py} # just required ones attrs = { 'base_size': 85, 'pre_nms_topn': 10, 'post_nms_topn': 20, 'nms_thresh': 0.34, 'feat_stride': 16, 'min_size': 32, 'ratio': [0.1, 1.5, 2.0, 2.5], 'scale': [2, 3, 3, 4], } @endcode Optional attributes which are absent from dictionary will be set with corresponding default.
Filter bounding boxes and outputs only those with the highest prediction confidence.
[ "Filter", "bounding", "boxes", "and", "outputs", "only", "those", "with", "the", "highest", "prediction", "confidence", "." ]
def proposal( class_probs: Node, bbox_deltas: Node, image_shape: NodeInput, attrs: dict, name: Optional[str] = None, ) -> Node: """Filter bounding boxes and outputs only those with the highest prediction confidence. @param class_probs: 4D input floating point tensor with class prediction scores. @param bbox_deltas: 4D input floating point tensor with box logits. @param image_shape: The 1D input tensor with 3 or 4 elements describing image shape. @param attrs: The dictionary containing key, value pairs for attributes. @param name: Optional name for the output node. @return Node representing Proposal operation. * base_size The size of the anchor to which scale and ratio attributes are applied. Range of values: a positive unsigned integer number Default value: None Required: yes * pre_nms_topn The number of bounding boxes before the NMS operation. Range of values: a positive unsigned integer number Default value: None Required: yes * post_nms_topn The number of bounding boxes after the NMS operation. Range of values: a positive unsigned integer number Default value: None Required: yes * nms_thresh The minimum value of the proposal to be taken into consideration. Range of values: a positive floating-point number Default value: None Required: yes * feat_stride The step size to slide over boxes (in pixels). Range of values: a positive unsigned integer Default value: None Required: yes * min_size The minimum size of box to be taken into consideration. Range of values: a positive unsigned integer number Default value: None Required: yes * ratio The ratios for anchor generation. Range of values: a list of floating-point numbers Default value: None Required: yes * scale The scales for anchor generation. Range of values: a list of floating-point numbers Default value: None Required: yes * clip_before_nms The flag that specifies whether to perform clip bounding boxes before non-maximum suppression or not. Range of values: True or False Default value: True Required: no * clip_after_nms The flag that specifies whether to perform clip bounding boxes after non-maximum suppression or not. Range of values: True or False Default value: False Required: no * normalize The flag that specifies whether to perform normalization of output boxes to [0,1] interval or not. Range of values: True or False Default value: False Required: no * box_size_scale Specifies the scale factor applied to logits of box sizes before decoding. Range of values: a positive floating-point number Default value: 1.0 Required: no * box_coordinate_scale Specifies the scale factor applied to logits of box coordinates before decoding. Range of values: a positive floating-point number Default value: 1.0 Required: no * framework Specifies how the box coordinates are calculated. Range of values: "" (empty string) - calculate box coordinates like in Caffe* tensorflow - calculate box coordinates like in the TensorFlow* Object Detection API models Default value: "" (empty string) Required: no Example of attribute dictionary: @code{.py} # just required ones attrs = { 'base_size': 85, 'pre_nms_topn': 10, 'post_nms_topn': 20, 'nms_thresh': 0.34, 'feat_stride': 16, 'min_size': 32, 'ratio': [0.1, 1.5, 2.0, 2.5], 'scale': [2, 3, 3, 4], } @endcode Optional attributes which are absent from dictionary will be set with corresponding default. """ requirements = [ ("base_size", True, np.unsignedinteger, is_positive_value), ("pre_nms_topn", True, np.unsignedinteger, is_positive_value), ("post_nms_topn", True, np.unsignedinteger, is_positive_value), ("nms_thresh", True, np.floating, is_positive_value), ("feat_stride", True, np.unsignedinteger, is_positive_value), ("min_size", True, np.unsignedinteger, is_positive_value), ("ratio", True, np.floating, None), ("scale", True, np.floating, None), ("clip_before_nms", False, np.bool_, None), ("clip_after_nms", False, np.bool_, None), ("normalize", False, np.bool_, None), ("box_size_scale", False, np.floating, is_positive_value), ("box_coordinate_scale", False, np.floating, is_positive_value), ("framework", False, np.str_, None), ] check_valid_attributes("Proposal", attrs, requirements) return _get_node_factory_opset1().create( "Proposal", [class_probs, bbox_deltas, as_node(image_shape)], attrs )
[ "def", "proposal", "(", "class_probs", ":", "Node", ",", "bbox_deltas", ":", "Node", ",", "image_shape", ":", "NodeInput", ",", "attrs", ":", "dict", ",", "name", ":", "Optional", "[", "str", "]", "=", "None", ",", ")", "->", "Node", ":", "requirements", "=", "[", "(", "\"base_size\"", ",", "True", ",", "np", ".", "unsignedinteger", ",", "is_positive_value", ")", ",", "(", "\"pre_nms_topn\"", ",", "True", ",", "np", ".", "unsignedinteger", ",", "is_positive_value", ")", ",", "(", "\"post_nms_topn\"", ",", "True", ",", "np", ".", "unsignedinteger", ",", "is_positive_value", ")", ",", "(", "\"nms_thresh\"", ",", "True", ",", "np", ".", "floating", ",", "is_positive_value", ")", ",", "(", "\"feat_stride\"", ",", "True", ",", "np", ".", "unsignedinteger", ",", "is_positive_value", ")", ",", "(", "\"min_size\"", ",", "True", ",", "np", ".", "unsignedinteger", ",", "is_positive_value", ")", ",", "(", "\"ratio\"", ",", "True", ",", "np", ".", "floating", ",", "None", ")", ",", "(", "\"scale\"", ",", "True", ",", "np", ".", "floating", ",", "None", ")", ",", "(", "\"clip_before_nms\"", ",", "False", ",", "np", ".", "bool_", ",", "None", ")", ",", "(", "\"clip_after_nms\"", ",", "False", ",", "np", ".", "bool_", ",", "None", ")", ",", "(", "\"normalize\"", ",", "False", ",", "np", ".", "bool_", ",", "None", ")", ",", "(", "\"box_size_scale\"", ",", "False", ",", "np", ".", "floating", ",", "is_positive_value", ")", ",", "(", "\"box_coordinate_scale\"", ",", "False", ",", "np", ".", "floating", ",", "is_positive_value", ")", ",", "(", "\"framework\"", ",", "False", ",", "np", ".", "str_", ",", "None", ")", ",", "]", "check_valid_attributes", "(", "\"Proposal\"", ",", "attrs", ",", "requirements", ")", "return", "_get_node_factory_opset1", "(", ")", ".", "create", "(", "\"Proposal\"", ",", "[", "class_probs", ",", "bbox_deltas", ",", "as_node", "(", "image_shape", ")", "]", ",", "attrs", ")" ]
https://github.com/openvinotoolkit/openvino/blob/dedcbeafa8b84cccdc55ca64b8da516682b381c7/src/bindings/python/src/openvino/runtime/opset1/ops.py#L2043-L2174
cvxpy/cvxpy
5165b4fb750dfd237de8659383ef24b4b2e33aaf
cvxpy/atoms/affine/diag.py
python
diag_vec.is_atom_log_log_concave
(self)
return True
Is the atom log-log concave?
Is the atom log-log concave?
[ "Is", "the", "atom", "log", "-", "log", "concave?" ]
def is_atom_log_log_concave(self) -> bool: """Is the atom log-log concave? """ return True
[ "def", "is_atom_log_log_concave", "(", "self", ")", "->", "bool", ":", "return", "True" ]
https://github.com/cvxpy/cvxpy/blob/5165b4fb750dfd237de8659383ef24b4b2e33aaf/cvxpy/atoms/affine/diag.py#L61-L64
eclipse/sumo
7132a9b8b6eea734bdec38479026b4d8c4336d03
tools/contributed/sumopy/coremodules/simulation/wxgui.py
python
WxGui.on_maroute
(self, event=None)
Simulate scenario with Macrosopic router (marouter).
Simulate scenario with Macrosopic router (marouter).
[ "Simulate", "scenario", "with", "Macrosopic", "router", "(", "marouter", ")", "." ]
def on_maroute(self, event=None): """Simulate scenario with Macrosopic router (marouter). """ p = routing.MaRouter(self.get_scenario(), results=self._simulation.results, logger=self._mainframe.get_logger(), ) dlg = ProcessDialog(self._mainframe, p) dlg.CenterOnScreen() # this does not return until the dialog is closed. val = dlg.ShowModal() # print ' val,val == wx.ID_OK',val,wx.ID_OK,wx.ID_CANCEL,val == wx.ID_CANCEL # print ' status =',dlg.get_status() if dlg.get_status() != 'success': # val == wx.ID_CANCEL: # print ">>>>>>>>>Unsuccessful\n" dlg.Destroy() if dlg.get_status() == 'success': # print ">>>>>>>>>successful\n" # apply current widget values to scenario instance dlg.apply() dlg.Destroy() # self._mainframe.browse_obj(self._simulation.results) p.import_results() self._mainframe.browse_obj(p.get_results()) self._mainframe.select_view(name="Result viewer") # !!!!!!!!tricky, crashes without self.refresh_widgets()
[ "def", "on_maroute", "(", "self", ",", "event", "=", "None", ")", ":", "p", "=", "routing", ".", "MaRouter", "(", "self", ".", "get_scenario", "(", ")", ",", "results", "=", "self", ".", "_simulation", ".", "results", ",", "logger", "=", "self", ".", "_mainframe", ".", "get_logger", "(", ")", ",", ")", "dlg", "=", "ProcessDialog", "(", "self", ".", "_mainframe", ",", "p", ")", "dlg", ".", "CenterOnScreen", "(", ")", "# this does not return until the dialog is closed.", "val", "=", "dlg", ".", "ShowModal", "(", ")", "# print ' val,val == wx.ID_OK',val,wx.ID_OK,wx.ID_CANCEL,val == wx.ID_CANCEL", "# print ' status =',dlg.get_status()", "if", "dlg", ".", "get_status", "(", ")", "!=", "'success'", ":", "# val == wx.ID_CANCEL:", "# print \">>>>>>>>>Unsuccessful\\n\"", "dlg", ".", "Destroy", "(", ")", "if", "dlg", ".", "get_status", "(", ")", "==", "'success'", ":", "# print \">>>>>>>>>successful\\n\"", "# apply current widget values to scenario instance", "dlg", ".", "apply", "(", ")", "dlg", ".", "Destroy", "(", ")", "# self._mainframe.browse_obj(self._simulation.results)", "p", ".", "import_results", "(", ")", "self", ".", "_mainframe", ".", "browse_obj", "(", "p", ".", "get_results", "(", ")", ")", "self", ".", "_mainframe", ".", "select_view", "(", "name", "=", "\"Result viewer\"", ")", "# !!!!!!!!tricky, crashes without", "self", ".", "refresh_widgets", "(", ")" ]
https://github.com/eclipse/sumo/blob/7132a9b8b6eea734bdec38479026b4d8c4336d03/tools/contributed/sumopy/coremodules/simulation/wxgui.py#L872-L901
openvinotoolkit/openvino
dedcbeafa8b84cccdc55ca64b8da516682b381c7
tools/mo/openvino/tools/mo/front/kaldi/loader/utils.py
python
find_end_of_component
(file_desc: io.BufferedReader, component: str, end_tags: tuple = ())
return next_tag, file_desc.tell()
Find an index and a tag of the ent of the component :param file_desc: file descriptor :param component: component from supported_components :param end_tags: specific end tags :return: the index and the tag of the end of the component
Find an index and a tag of the ent of the component :param file_desc: file descriptor :param component: component from supported_components :param end_tags: specific end tags :return: the index and the tag of the end of the component
[ "Find", "an", "index", "and", "a", "tag", "of", "the", "ent", "of", "the", "component", ":", "param", "file_desc", ":", "file", "descriptor", ":", "param", "component", ":", "component", "from", "supported_components", ":", "param", "end_tags", ":", "specific", "end", "tags", ":", "return", ":", "the", "index", "and", "the", "tag", "of", "the", "end", "of", "the", "component" ]
def find_end_of_component(file_desc: io.BufferedReader, component: str, end_tags: tuple = ()): """ Find an index and a tag of the ent of the component :param file_desc: file descriptor :param component: component from supported_components :param end_tags: specific end tags :return: the index and the tag of the end of the component """ end_tags_of_component = ['</{}>'.format(component), end_of_component_tag.lower(), end_of_nnet_tag.lower(), *end_tags, *['<{}>'.format(component) for component in supported_components]] next_tag = find_next_tag(file_desc) while next_tag.lower() not in end_tags_of_component: next_tag = find_next_tag(file_desc) return next_tag, file_desc.tell()
[ "def", "find_end_of_component", "(", "file_desc", ":", "io", ".", "BufferedReader", ",", "component", ":", "str", ",", "end_tags", ":", "tuple", "=", "(", ")", ")", ":", "end_tags_of_component", "=", "[", "'</{}>'", ".", "format", "(", "component", ")", ",", "end_of_component_tag", ".", "lower", "(", ")", ",", "end_of_nnet_tag", ".", "lower", "(", ")", ",", "*", "end_tags", ",", "*", "[", "'<{}>'", ".", "format", "(", "component", ")", "for", "component", "in", "supported_components", "]", "]", "next_tag", "=", "find_next_tag", "(", "file_desc", ")", "while", "next_tag", ".", "lower", "(", ")", "not", "in", "end_tags_of_component", ":", "next_tag", "=", "find_next_tag", "(", "file_desc", ")", "return", "next_tag", ",", "file_desc", ".", "tell", "(", ")" ]
https://github.com/openvinotoolkit/openvino/blob/dedcbeafa8b84cccdc55ca64b8da516682b381c7/tools/mo/openvino/tools/mo/front/kaldi/loader/utils.py#L216-L232
llvm-mirror/lldb
d01083a850f577b85501a0902b52fd0930de72c7
utils/vim-lldb/python-vim-lldb/vim_panes.py
python
BacktracePane.get_selected_line
(self)
Returns the line number in the buffer with the selected frame. Formula: selected_line = selected_frame_id + 2 FIXME: the above formula hack does not work when the function return value is printed in the bt window; the wrong line is highlighted.
Returns the line number in the buffer with the selected frame. Formula: selected_line = selected_frame_id + 2 FIXME: the above formula hack does not work when the function return value is printed in the bt window; the wrong line is highlighted.
[ "Returns", "the", "line", "number", "in", "the", "buffer", "with", "the", "selected", "frame", ".", "Formula", ":", "selected_line", "=", "selected_frame_id", "+", "2", "FIXME", ":", "the", "above", "formula", "hack", "does", "not", "work", "when", "the", "function", "return", "value", "is", "printed", "in", "the", "bt", "window", ";", "the", "wrong", "line", "is", "highlighted", "." ]
def get_selected_line(self): """ Returns the line number in the buffer with the selected frame. Formula: selected_line = selected_frame_id + 2 FIXME: the above formula hack does not work when the function return value is printed in the bt window; the wrong line is highlighted. """ (frame, err) = get_selected_frame(self.target) if frame is None: return None else: return frame.GetFrameID() + 2
[ "def", "get_selected_line", "(", "self", ")", ":", "(", "frame", ",", "err", ")", "=", "get_selected_frame", "(", "self", ".", "target", ")", "if", "frame", "is", "None", ":", "return", "None", "else", ":", "return", "frame", ".", "GetFrameID", "(", ")", "+", "2" ]
https://github.com/llvm-mirror/lldb/blob/d01083a850f577b85501a0902b52fd0930de72c7/utils/vim-lldb/python-vim-lldb/vim_panes.py#L645-L656
adobe/chromium
cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7
tools/symsrc/pefile.py
python
PE.dump_info
(self, dump=None)
return dump.get_text()
Dump all the PE header information into human readable string.
Dump all the PE header information into human readable string.
[ "Dump", "all", "the", "PE", "header", "information", "into", "human", "readable", "string", "." ]
def dump_info(self, dump=None): """Dump all the PE header information into human readable string.""" if dump is None: dump = Dump() warnings = self.get_warnings() if warnings: dump.add_header('Parsing Warnings') for warning in warnings: dump.add_line(warning) dump.add_newline() dump.add_header('DOS_HEADER') dump.add_lines(self.DOS_HEADER.dump()) dump.add_newline() dump.add_header('NT_HEADERS') dump.add_lines(self.NT_HEADERS.dump()) dump.add_newline() dump.add_header('FILE_HEADER') dump.add_lines(self.FILE_HEADER.dump()) image_flags = self.retrieve_flags(IMAGE_CHARACTERISTICS, 'IMAGE_FILE_') dump.add('Flags: ') flags = [] for flag in image_flags: if getattr(self.FILE_HEADER, flag[0]): flags.append(flag[0]) dump.add_line(', '.join(flags)) dump.add_newline() if hasattr(self, 'OPTIONAL_HEADER') and self.OPTIONAL_HEADER is not None: dump.add_header('OPTIONAL_HEADER') dump.add_lines(self.OPTIONAL_HEADER.dump()) dll_characteristics_flags = self.retrieve_flags(DLL_CHARACTERISTICS, 'IMAGE_DLL_CHARACTERISTICS_') dump.add('DllCharacteristics: ') flags = [] for flag in dll_characteristics_flags: if getattr(self.OPTIONAL_HEADER, flag[0]): flags.append(flag[0]) dump.add_line(', '.join(flags)) dump.add_newline() dump.add_header('PE Sections') section_flags = self.retrieve_flags(SECTION_CHARACTERISTICS, 'IMAGE_SCN_') for section in self.sections: dump.add_lines(section.dump()) dump.add('Flags: ') flags = [] for flag in section_flags: if getattr(section, flag[0]): flags.append(flag[0]) dump.add_line(', '.join(flags)) dump.add_line('Entropy: %f (Min=0.0, Max=8.0)' % section.get_entropy() ) if md5 is not None: dump.add_line('MD5 hash: %s' % section.get_hash_md5() ) if sha1 is not None: dump.add_line('SHA-1 hash: %s' % section.get_hash_sha1() ) if sha256 is not None: dump.add_line('SHA-256 hash: %s' % section.get_hash_sha256() ) if sha512 is not None: dump.add_line('SHA-512 hash: %s' % section.get_hash_sha512() ) dump.add_newline() if (hasattr(self, 'OPTIONAL_HEADER') and hasattr(self.OPTIONAL_HEADER, 'DATA_DIRECTORY') ): dump.add_header('Directories') for idx in xrange(len(self.OPTIONAL_HEADER.DATA_DIRECTORY)): directory = self.OPTIONAL_HEADER.DATA_DIRECTORY[idx] dump.add_lines(directory.dump()) dump.add_newline() if hasattr(self, 'VS_VERSIONINFO'): dump.add_header('Version Information') dump.add_lines(self.VS_VERSIONINFO.dump()) dump.add_newline() if hasattr(self, 'VS_FIXEDFILEINFO'): dump.add_lines(self.VS_FIXEDFILEINFO.dump()) dump.add_newline() if hasattr(self, 'FileInfo'): for entry in self.FileInfo: dump.add_lines(entry.dump()) dump.add_newline() if hasattr(entry, 'StringTable'): for st_entry in entry.StringTable: [dump.add_line(' '+line) for line in st_entry.dump()] dump.add_line(' LangID: '+st_entry.LangID) dump.add_newline() for str_entry in st_entry.entries.items(): dump.add_line(' '+str_entry[0]+': '+str_entry[1]) dump.add_newline() elif hasattr(entry, 'Var'): for var_entry in entry.Var: if hasattr(var_entry, 'entry'): [dump.add_line(' '+line) for line in var_entry.dump()] dump.add_line( ' ' + var_entry.entry.keys()[0] + ': ' + var_entry.entry.values()[0]) dump.add_newline() if hasattr(self, 'DIRECTORY_ENTRY_EXPORT'): dump.add_header('Exported symbols') dump.add_lines(self.DIRECTORY_ENTRY_EXPORT.struct.dump()) dump.add_newline() dump.add_line('%-10s %-10s %s' % ('Ordinal', 'RVA', 'Name')) for export in self.DIRECTORY_ENTRY_EXPORT.symbols: dump.add('%-10d 0x%08Xh %s' % ( export.ordinal, export.address, export.name)) if export.forwarder: dump.add_line(' forwarder: %s' % export.forwarder) else: dump.add_newline() dump.add_newline() if hasattr(self, 'DIRECTORY_ENTRY_IMPORT'): dump.add_header('Imported symbols') for module in self.DIRECTORY_ENTRY_IMPORT: dump.add_lines(module.struct.dump()) dump.add_newline() for symbol in module.imports: if symbol.import_by_ordinal is True: dump.add('%s Ordinal[%s] (Imported by Ordinal)' % ( module.dll, str(symbol.ordinal))) else: dump.add('%s.%s Hint[%s]' % ( module.dll, symbol.name, str(symbol.hint))) if symbol.bound: dump.add_line(' Bound: 0x%08X' % (symbol.bound)) else: dump.add_newline() dump.add_newline() if hasattr(self, 'DIRECTORY_ENTRY_BOUND_IMPORT'): dump.add_header('Bound imports') for bound_imp_desc in self.DIRECTORY_ENTRY_BOUND_IMPORT: dump.add_lines(bound_imp_desc.struct.dump()) dump.add_line('DLL: %s' % bound_imp_desc.name) dump.add_newline() for bound_imp_ref in bound_imp_desc.entries: dump.add_lines(bound_imp_ref.struct.dump(), 4) dump.add_line('DLL: %s' % bound_imp_ref.name, 4) dump.add_newline() if hasattr(self, 'DIRECTORY_ENTRY_DELAY_IMPORT'): dump.add_header('Delay Imported symbols') for module in self.DIRECTORY_ENTRY_DELAY_IMPORT: dump.add_lines(module.struct.dump()) dump.add_newline() for symbol in module.imports: if symbol.import_by_ordinal is True: dump.add('%s Ordinal[%s] (Imported by Ordinal)' % ( module.dll, str(symbol.ordinal))) else: dump.add('%s.%s Hint[%s]' % ( module.dll, symbol.name, str(symbol.hint))) if symbol.bound: dump.add_line(' Bound: 0x%08X' % (symbol.bound)) else: dump.add_newline() dump.add_newline() if hasattr(self, 'DIRECTORY_ENTRY_RESOURCE'): dump.add_header('Resource directory') dump.add_lines(self.DIRECTORY_ENTRY_RESOURCE.struct.dump()) for resource_type in self.DIRECTORY_ENTRY_RESOURCE.entries: if resource_type.name is not None: dump.add_line('Name: [%s]' % resource_type.name, 2) else: dump.add_line('Id: [0x%X] (%s)' % ( resource_type.struct.Id, RESOURCE_TYPE.get( resource_type.struct.Id, '-')), 2) dump.add_lines(resource_type.struct.dump(), 2) if hasattr(resource_type, 'directory'): dump.add_lines(resource_type.directory.struct.dump(), 4) for resource_id in resource_type.directory.entries: if resource_id.name is not None: dump.add_line('Name: [%s]' % resource_id.name, 6) else: dump.add_line('Id: [0x%X]' % resource_id.struct.Id, 6) dump.add_lines(resource_id.struct.dump(), 6) if hasattr(resource_id, 'directory'): dump.add_lines(resource_id.directory.struct.dump(), 8) for resource_lang in resource_id.directory.entries: # dump.add_line('\\--- LANG [%d,%d][%s]' % ( # resource_lang.data.lang, # resource_lang.data.sublang, # LANG[resource_lang.data.lang]), 8) dump.add_lines(resource_lang.struct.dump(), 10) dump.add_lines(resource_lang.data.struct.dump(), 12) dump.add_newline() dump.add_newline() if ( hasattr(self, 'DIRECTORY_ENTRY_TLS') and self.DIRECTORY_ENTRY_TLS and self.DIRECTORY_ENTRY_TLS.struct ): dump.add_header('TLS') dump.add_lines(self.DIRECTORY_ENTRY_TLS.struct.dump()) dump.add_newline() if hasattr(self, 'DIRECTORY_ENTRY_DEBUG'): dump.add_header('Debug information') for dbg in self.DIRECTORY_ENTRY_DEBUG: dump.add_lines(dbg.struct.dump()) try: dump.add_line('Type: '+DEBUG_TYPE[dbg.struct.Type]) except KeyError: dump.add_line('Type: 0x%x(Unknown)' % dbg.struct.Type) dump.add_newline() if hasattr(self, 'DIRECTORY_ENTRY_BASERELOC'): dump.add_header('Base relocations') for base_reloc in self.DIRECTORY_ENTRY_BASERELOC: dump.add_lines(base_reloc.struct.dump()) for reloc in base_reloc.entries: try: dump.add_line('%08Xh %s' % ( reloc.rva, RELOCATION_TYPE[reloc.type][16:]), 4) except KeyError: dump.add_line('0x%08X 0x%x(Unknown)' % ( reloc.rva, reloc.type), 4) dump.add_newline() return dump.get_text()
[ "def", "dump_info", "(", "self", ",", "dump", "=", "None", ")", ":", "if", "dump", "is", "None", ":", "dump", "=", "Dump", "(", ")", "warnings", "=", "self", ".", "get_warnings", "(", ")", "if", "warnings", ":", "dump", ".", "add_header", "(", "'Parsing Warnings'", ")", "for", "warning", "in", "warnings", ":", "dump", ".", "add_line", "(", "warning", ")", "dump", ".", "add_newline", "(", ")", "dump", ".", "add_header", "(", "'DOS_HEADER'", ")", "dump", ".", "add_lines", "(", "self", ".", "DOS_HEADER", ".", "dump", "(", ")", ")", "dump", ".", "add_newline", "(", ")", "dump", ".", "add_header", "(", "'NT_HEADERS'", ")", "dump", ".", "add_lines", "(", "self", ".", "NT_HEADERS", ".", "dump", "(", ")", ")", "dump", ".", "add_newline", "(", ")", "dump", ".", "add_header", "(", "'FILE_HEADER'", ")", "dump", ".", "add_lines", "(", "self", ".", "FILE_HEADER", ".", "dump", "(", ")", ")", "image_flags", "=", "self", ".", "retrieve_flags", "(", "IMAGE_CHARACTERISTICS", ",", "'IMAGE_FILE_'", ")", "dump", ".", "add", "(", "'Flags: '", ")", "flags", "=", "[", "]", "for", "flag", "in", "image_flags", ":", "if", "getattr", "(", "self", ".", "FILE_HEADER", ",", "flag", "[", "0", "]", ")", ":", "flags", ".", "append", "(", "flag", "[", "0", "]", ")", "dump", ".", "add_line", "(", "', '", ".", "join", "(", "flags", ")", ")", "dump", ".", "add_newline", "(", ")", "if", "hasattr", "(", "self", ",", "'OPTIONAL_HEADER'", ")", "and", "self", ".", "OPTIONAL_HEADER", "is", "not", "None", ":", "dump", ".", "add_header", "(", "'OPTIONAL_HEADER'", ")", "dump", ".", "add_lines", "(", "self", ".", "OPTIONAL_HEADER", ".", "dump", "(", ")", ")", "dll_characteristics_flags", "=", "self", ".", "retrieve_flags", "(", "DLL_CHARACTERISTICS", ",", "'IMAGE_DLL_CHARACTERISTICS_'", ")", "dump", ".", "add", "(", "'DllCharacteristics: '", ")", "flags", "=", "[", "]", "for", "flag", "in", "dll_characteristics_flags", ":", "if", "getattr", "(", "self", ".", "OPTIONAL_HEADER", ",", "flag", "[", "0", "]", ")", ":", "flags", ".", "append", "(", "flag", "[", "0", "]", ")", "dump", ".", "add_line", "(", "', '", ".", "join", "(", "flags", ")", ")", "dump", ".", "add_newline", "(", ")", "dump", ".", "add_header", "(", "'PE Sections'", ")", "section_flags", "=", "self", ".", "retrieve_flags", "(", "SECTION_CHARACTERISTICS", ",", "'IMAGE_SCN_'", ")", "for", "section", "in", "self", ".", "sections", ":", "dump", ".", "add_lines", "(", "section", ".", "dump", "(", ")", ")", "dump", ".", "add", "(", "'Flags: '", ")", "flags", "=", "[", "]", "for", "flag", "in", "section_flags", ":", "if", "getattr", "(", "section", ",", "flag", "[", "0", "]", ")", ":", "flags", ".", "append", "(", "flag", "[", "0", "]", ")", "dump", ".", "add_line", "(", "', '", ".", "join", "(", "flags", ")", ")", "dump", ".", "add_line", "(", "'Entropy: %f (Min=0.0, Max=8.0)'", "%", "section", ".", "get_entropy", "(", ")", ")", "if", "md5", "is", "not", "None", ":", "dump", ".", "add_line", "(", "'MD5 hash: %s'", "%", "section", ".", "get_hash_md5", "(", ")", ")", "if", "sha1", "is", "not", "None", ":", "dump", ".", "add_line", "(", "'SHA-1 hash: %s'", "%", "section", ".", "get_hash_sha1", "(", ")", ")", "if", "sha256", "is", "not", "None", ":", "dump", ".", "add_line", "(", "'SHA-256 hash: %s'", "%", "section", ".", "get_hash_sha256", "(", ")", ")", "if", "sha512", "is", "not", "None", ":", "dump", ".", "add_line", "(", "'SHA-512 hash: %s'", "%", "section", ".", "get_hash_sha512", "(", ")", ")", "dump", ".", "add_newline", "(", ")", "if", "(", "hasattr", "(", "self", ",", "'OPTIONAL_HEADER'", ")", "and", "hasattr", "(", "self", ".", "OPTIONAL_HEADER", ",", "'DATA_DIRECTORY'", ")", ")", ":", "dump", ".", "add_header", "(", "'Directories'", ")", "for", "idx", "in", "xrange", "(", "len", "(", "self", ".", "OPTIONAL_HEADER", ".", "DATA_DIRECTORY", ")", ")", ":", "directory", "=", "self", ".", "OPTIONAL_HEADER", ".", "DATA_DIRECTORY", "[", "idx", "]", "dump", ".", "add_lines", "(", "directory", ".", "dump", "(", ")", ")", "dump", ".", "add_newline", "(", ")", "if", "hasattr", "(", "self", ",", "'VS_VERSIONINFO'", ")", ":", "dump", ".", "add_header", "(", "'Version Information'", ")", "dump", ".", "add_lines", "(", "self", ".", "VS_VERSIONINFO", ".", "dump", "(", ")", ")", "dump", ".", "add_newline", "(", ")", "if", "hasattr", "(", "self", ",", "'VS_FIXEDFILEINFO'", ")", ":", "dump", ".", "add_lines", "(", "self", ".", "VS_FIXEDFILEINFO", ".", "dump", "(", ")", ")", "dump", ".", "add_newline", "(", ")", "if", "hasattr", "(", "self", ",", "'FileInfo'", ")", ":", "for", "entry", "in", "self", ".", "FileInfo", ":", "dump", ".", "add_lines", "(", "entry", ".", "dump", "(", ")", ")", "dump", ".", "add_newline", "(", ")", "if", "hasattr", "(", "entry", ",", "'StringTable'", ")", ":", "for", "st_entry", "in", "entry", ".", "StringTable", ":", "[", "dump", ".", "add_line", "(", "' '", "+", "line", ")", "for", "line", "in", "st_entry", ".", "dump", "(", ")", "]", "dump", ".", "add_line", "(", "' LangID: '", "+", "st_entry", ".", "LangID", ")", "dump", ".", "add_newline", "(", ")", "for", "str_entry", "in", "st_entry", ".", "entries", ".", "items", "(", ")", ":", "dump", ".", "add_line", "(", "' '", "+", "str_entry", "[", "0", "]", "+", "': '", "+", "str_entry", "[", "1", "]", ")", "dump", ".", "add_newline", "(", ")", "elif", "hasattr", "(", "entry", ",", "'Var'", ")", ":", "for", "var_entry", "in", "entry", ".", "Var", ":", "if", "hasattr", "(", "var_entry", ",", "'entry'", ")", ":", "[", "dump", ".", "add_line", "(", "' '", "+", "line", ")", "for", "line", "in", "var_entry", ".", "dump", "(", ")", "]", "dump", ".", "add_line", "(", "' '", "+", "var_entry", ".", "entry", ".", "keys", "(", ")", "[", "0", "]", "+", "': '", "+", "var_entry", ".", "entry", ".", "values", "(", ")", "[", "0", "]", ")", "dump", ".", "add_newline", "(", ")", "if", "hasattr", "(", "self", ",", "'DIRECTORY_ENTRY_EXPORT'", ")", ":", "dump", ".", "add_header", "(", "'Exported symbols'", ")", "dump", ".", "add_lines", "(", "self", ".", "DIRECTORY_ENTRY_EXPORT", ".", "struct", ".", "dump", "(", ")", ")", "dump", ".", "add_newline", "(", ")", "dump", ".", "add_line", "(", "'%-10s %-10s %s'", "%", "(", "'Ordinal'", ",", "'RVA'", ",", "'Name'", ")", ")", "for", "export", "in", "self", ".", "DIRECTORY_ENTRY_EXPORT", ".", "symbols", ":", "dump", ".", "add", "(", "'%-10d 0x%08Xh %s'", "%", "(", "export", ".", "ordinal", ",", "export", ".", "address", ",", "export", ".", "name", ")", ")", "if", "export", ".", "forwarder", ":", "dump", ".", "add_line", "(", "' forwarder: %s'", "%", "export", ".", "forwarder", ")", "else", ":", "dump", ".", "add_newline", "(", ")", "dump", ".", "add_newline", "(", ")", "if", "hasattr", "(", "self", ",", "'DIRECTORY_ENTRY_IMPORT'", ")", ":", "dump", ".", "add_header", "(", "'Imported symbols'", ")", "for", "module", "in", "self", ".", "DIRECTORY_ENTRY_IMPORT", ":", "dump", ".", "add_lines", "(", "module", ".", "struct", ".", "dump", "(", ")", ")", "dump", ".", "add_newline", "(", ")", "for", "symbol", "in", "module", ".", "imports", ":", "if", "symbol", ".", "import_by_ordinal", "is", "True", ":", "dump", ".", "add", "(", "'%s Ordinal[%s] (Imported by Ordinal)'", "%", "(", "module", ".", "dll", ",", "str", "(", "symbol", ".", "ordinal", ")", ")", ")", "else", ":", "dump", ".", "add", "(", "'%s.%s Hint[%s]'", "%", "(", "module", ".", "dll", ",", "symbol", ".", "name", ",", "str", "(", "symbol", ".", "hint", ")", ")", ")", "if", "symbol", ".", "bound", ":", "dump", ".", "add_line", "(", "' Bound: 0x%08X'", "%", "(", "symbol", ".", "bound", ")", ")", "else", ":", "dump", ".", "add_newline", "(", ")", "dump", ".", "add_newline", "(", ")", "if", "hasattr", "(", "self", ",", "'DIRECTORY_ENTRY_BOUND_IMPORT'", ")", ":", "dump", ".", "add_header", "(", "'Bound imports'", ")", "for", "bound_imp_desc", "in", "self", ".", "DIRECTORY_ENTRY_BOUND_IMPORT", ":", "dump", ".", "add_lines", "(", "bound_imp_desc", ".", "struct", ".", "dump", "(", ")", ")", "dump", ".", "add_line", "(", "'DLL: %s'", "%", "bound_imp_desc", ".", "name", ")", "dump", ".", "add_newline", "(", ")", "for", "bound_imp_ref", "in", "bound_imp_desc", ".", "entries", ":", "dump", ".", "add_lines", "(", "bound_imp_ref", ".", "struct", ".", "dump", "(", ")", ",", "4", ")", "dump", ".", "add_line", "(", "'DLL: %s'", "%", "bound_imp_ref", ".", "name", ",", "4", ")", "dump", ".", "add_newline", "(", ")", "if", "hasattr", "(", "self", ",", "'DIRECTORY_ENTRY_DELAY_IMPORT'", ")", ":", "dump", ".", "add_header", "(", "'Delay Imported symbols'", ")", "for", "module", "in", "self", ".", "DIRECTORY_ENTRY_DELAY_IMPORT", ":", "dump", ".", "add_lines", "(", "module", ".", "struct", ".", "dump", "(", ")", ")", "dump", ".", "add_newline", "(", ")", "for", "symbol", "in", "module", ".", "imports", ":", "if", "symbol", ".", "import_by_ordinal", "is", "True", ":", "dump", ".", "add", "(", "'%s Ordinal[%s] (Imported by Ordinal)'", "%", "(", "module", ".", "dll", ",", "str", "(", "symbol", ".", "ordinal", ")", ")", ")", "else", ":", "dump", ".", "add", "(", "'%s.%s Hint[%s]'", "%", "(", "module", ".", "dll", ",", "symbol", ".", "name", ",", "str", "(", "symbol", ".", "hint", ")", ")", ")", "if", "symbol", ".", "bound", ":", "dump", ".", "add_line", "(", "' Bound: 0x%08X'", "%", "(", "symbol", ".", "bound", ")", ")", "else", ":", "dump", ".", "add_newline", "(", ")", "dump", ".", "add_newline", "(", ")", "if", "hasattr", "(", "self", ",", "'DIRECTORY_ENTRY_RESOURCE'", ")", ":", "dump", ".", "add_header", "(", "'Resource directory'", ")", "dump", ".", "add_lines", "(", "self", ".", "DIRECTORY_ENTRY_RESOURCE", ".", "struct", ".", "dump", "(", ")", ")", "for", "resource_type", "in", "self", ".", "DIRECTORY_ENTRY_RESOURCE", ".", "entries", ":", "if", "resource_type", ".", "name", "is", "not", "None", ":", "dump", ".", "add_line", "(", "'Name: [%s]'", "%", "resource_type", ".", "name", ",", "2", ")", "else", ":", "dump", ".", "add_line", "(", "'Id: [0x%X] (%s)'", "%", "(", "resource_type", ".", "struct", ".", "Id", ",", "RESOURCE_TYPE", ".", "get", "(", "resource_type", ".", "struct", ".", "Id", ",", "'-'", ")", ")", ",", "2", ")", "dump", ".", "add_lines", "(", "resource_type", ".", "struct", ".", "dump", "(", ")", ",", "2", ")", "if", "hasattr", "(", "resource_type", ",", "'directory'", ")", ":", "dump", ".", "add_lines", "(", "resource_type", ".", "directory", ".", "struct", ".", "dump", "(", ")", ",", "4", ")", "for", "resource_id", "in", "resource_type", ".", "directory", ".", "entries", ":", "if", "resource_id", ".", "name", "is", "not", "None", ":", "dump", ".", "add_line", "(", "'Name: [%s]'", "%", "resource_id", ".", "name", ",", "6", ")", "else", ":", "dump", ".", "add_line", "(", "'Id: [0x%X]'", "%", "resource_id", ".", "struct", ".", "Id", ",", "6", ")", "dump", ".", "add_lines", "(", "resource_id", ".", "struct", ".", "dump", "(", ")", ",", "6", ")", "if", "hasattr", "(", "resource_id", ",", "'directory'", ")", ":", "dump", ".", "add_lines", "(", "resource_id", ".", "directory", ".", "struct", ".", "dump", "(", ")", ",", "8", ")", "for", "resource_lang", "in", "resource_id", ".", "directory", ".", "entries", ":", "# dump.add_line('\\\\--- LANG [%d,%d][%s]' % (", "# resource_lang.data.lang,", "# resource_lang.data.sublang,", "# LANG[resource_lang.data.lang]), 8)", "dump", ".", "add_lines", "(", "resource_lang", ".", "struct", ".", "dump", "(", ")", ",", "10", ")", "dump", ".", "add_lines", "(", "resource_lang", ".", "data", ".", "struct", ".", "dump", "(", ")", ",", "12", ")", "dump", ".", "add_newline", "(", ")", "dump", ".", "add_newline", "(", ")", "if", "(", "hasattr", "(", "self", ",", "'DIRECTORY_ENTRY_TLS'", ")", "and", "self", ".", "DIRECTORY_ENTRY_TLS", "and", "self", ".", "DIRECTORY_ENTRY_TLS", ".", "struct", ")", ":", "dump", ".", "add_header", "(", "'TLS'", ")", "dump", ".", "add_lines", "(", "self", ".", "DIRECTORY_ENTRY_TLS", ".", "struct", ".", "dump", "(", ")", ")", "dump", ".", "add_newline", "(", ")", "if", "hasattr", "(", "self", ",", "'DIRECTORY_ENTRY_DEBUG'", ")", ":", "dump", ".", "add_header", "(", "'Debug information'", ")", "for", "dbg", "in", "self", ".", "DIRECTORY_ENTRY_DEBUG", ":", "dump", ".", "add_lines", "(", "dbg", ".", "struct", ".", "dump", "(", ")", ")", "try", ":", "dump", ".", "add_line", "(", "'Type: '", "+", "DEBUG_TYPE", "[", "dbg", ".", "struct", ".", "Type", "]", ")", "except", "KeyError", ":", "dump", ".", "add_line", "(", "'Type: 0x%x(Unknown)'", "%", "dbg", ".", "struct", ".", "Type", ")", "dump", ".", "add_newline", "(", ")", "if", "hasattr", "(", "self", ",", "'DIRECTORY_ENTRY_BASERELOC'", ")", ":", "dump", ".", "add_header", "(", "'Base relocations'", ")", "for", "base_reloc", "in", "self", ".", "DIRECTORY_ENTRY_BASERELOC", ":", "dump", ".", "add_lines", "(", "base_reloc", ".", "struct", ".", "dump", "(", ")", ")", "for", "reloc", "in", "base_reloc", ".", "entries", ":", "try", ":", "dump", ".", "add_line", "(", "'%08Xh %s'", "%", "(", "reloc", ".", "rva", ",", "RELOCATION_TYPE", "[", "reloc", ".", "type", "]", "[", "16", ":", "]", ")", ",", "4", ")", "except", "KeyError", ":", "dump", ".", "add_line", "(", "'0x%08X 0x%x(Unknown)'", "%", "(", "reloc", ".", "rva", ",", "reloc", ".", "type", ")", ",", "4", ")", "dump", ".", "add_newline", "(", ")", "return", "dump", ".", "get_text", "(", ")" ]
https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/tools/symsrc/pefile.py#L3106-L3378
pmq20/node-packer
12c46c6e44fbc14d9ee645ebd17d5296b324f7e0
lts/tools/inspector_protocol/jinja2/runtime.py
python
Macro._invoke
(self, arguments, autoescape)
return rv
This method is being swapped out by the async implementation.
This method is being swapped out by the async implementation.
[ "This", "method", "is", "being", "swapped", "out", "by", "the", "async", "implementation", "." ]
def _invoke(self, arguments, autoescape): """This method is being swapped out by the async implementation.""" rv = self._func(*arguments) if autoescape: rv = Markup(rv) return rv
[ "def", "_invoke", "(", "self", ",", "arguments", ",", "autoescape", ")", ":", "rv", "=", "self", ".", "_func", "(", "*", "arguments", ")", "if", "autoescape", ":", "rv", "=", "Markup", "(", "rv", ")", "return", "rv" ]
https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/lts/tools/inspector_protocol/jinja2/runtime.py#L577-L582
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/ftplib.py
python
FTP.getwelcome
(self)
return self.welcome
Get the welcome message from the server. (this is read and squirreled away by connect())
Get the welcome message from the server. (this is read and squirreled away by connect())
[ "Get", "the", "welcome", "message", "from", "the", "server", ".", "(", "this", "is", "read", "and", "squirreled", "away", "by", "connect", "()", ")" ]
def getwelcome(self): '''Get the welcome message from the server. (this is read and squirreled away by connect())''' if self.debugging: print '*welcome*', self.sanitize(self.welcome) return self.welcome
[ "def", "getwelcome", "(", "self", ")", ":", "if", "self", ".", "debugging", ":", "print", "'*welcome*'", ",", "self", ".", "sanitize", "(", "self", ".", "welcome", ")", "return", "self", ".", "welcome" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/ftplib.py#L138-L143
intel/caffe
3f494b442ee3f9d17a07b09ecbd5fa2bbda00836
scripts/cpp_lint.py
python
_NestingState.UpdatePreprocessor
(self, line)
Update preprocessor stack. We need to handle preprocessors due to classes like this: #ifdef SWIG struct ResultDetailsPageElementExtensionPoint { #else struct ResultDetailsPageElementExtensionPoint : public Extension { #endif We make the following assumptions (good enough for most files): - Preprocessor condition evaluates to true from #if up to first #else/#elif/#endif. - Preprocessor condition evaluates to false from #else/#elif up to #endif. We still perform lint checks on these lines, but these do not affect nesting stack. Args: line: current line to check.
Update preprocessor stack.
[ "Update", "preprocessor", "stack", "." ]
def UpdatePreprocessor(self, line): """Update preprocessor stack. We need to handle preprocessors due to classes like this: #ifdef SWIG struct ResultDetailsPageElementExtensionPoint { #else struct ResultDetailsPageElementExtensionPoint : public Extension { #endif We make the following assumptions (good enough for most files): - Preprocessor condition evaluates to true from #if up to first #else/#elif/#endif. - Preprocessor condition evaluates to false from #else/#elif up to #endif. We still perform lint checks on these lines, but these do not affect nesting stack. Args: line: current line to check. """ if Match(r'^\s*#\s*(if|ifdef|ifndef)\b', line): # Beginning of #if block, save the nesting stack here. The saved # stack will allow us to restore the parsing state in the #else case. self.pp_stack.append(_PreprocessorInfo(copy.deepcopy(self.stack))) elif Match(r'^\s*#\s*(else|elif)\b', line): # Beginning of #else block if self.pp_stack: if not self.pp_stack[-1].seen_else: # This is the first #else or #elif block. Remember the # whole nesting stack up to this point. This is what we # keep after the #endif. self.pp_stack[-1].seen_else = True self.pp_stack[-1].stack_before_else = copy.deepcopy(self.stack) # Restore the stack to how it was before the #if self.stack = copy.deepcopy(self.pp_stack[-1].stack_before_if) else: # TODO(unknown): unexpected #else, issue warning? pass elif Match(r'^\s*#\s*endif\b', line): # End of #if or #else blocks. if self.pp_stack: # If we saw an #else, we will need to restore the nesting # stack to its former state before the #else, otherwise we # will just continue from where we left off. if self.pp_stack[-1].seen_else: # Here we can just use a shallow copy since we are the last # reference to it. self.stack = self.pp_stack[-1].stack_before_else # Drop the corresponding #if self.pp_stack.pop() else: # TODO(unknown): unexpected #endif, issue warning? pass
[ "def", "UpdatePreprocessor", "(", "self", ",", "line", ")", ":", "if", "Match", "(", "r'^\\s*#\\s*(if|ifdef|ifndef)\\b'", ",", "line", ")", ":", "# Beginning of #if block, save the nesting stack here. The saved", "# stack will allow us to restore the parsing state in the #else case.", "self", ".", "pp_stack", ".", "append", "(", "_PreprocessorInfo", "(", "copy", ".", "deepcopy", "(", "self", ".", "stack", ")", ")", ")", "elif", "Match", "(", "r'^\\s*#\\s*(else|elif)\\b'", ",", "line", ")", ":", "# Beginning of #else block", "if", "self", ".", "pp_stack", ":", "if", "not", "self", ".", "pp_stack", "[", "-", "1", "]", ".", "seen_else", ":", "# This is the first #else or #elif block. Remember the", "# whole nesting stack up to this point. This is what we", "# keep after the #endif.", "self", ".", "pp_stack", "[", "-", "1", "]", ".", "seen_else", "=", "True", "self", ".", "pp_stack", "[", "-", "1", "]", ".", "stack_before_else", "=", "copy", ".", "deepcopy", "(", "self", ".", "stack", ")", "# Restore the stack to how it was before the #if", "self", ".", "stack", "=", "copy", ".", "deepcopy", "(", "self", ".", "pp_stack", "[", "-", "1", "]", ".", "stack_before_if", ")", "else", ":", "# TODO(unknown): unexpected #else, issue warning?", "pass", "elif", "Match", "(", "r'^\\s*#\\s*endif\\b'", ",", "line", ")", ":", "# End of #if or #else blocks.", "if", "self", ".", "pp_stack", ":", "# If we saw an #else, we will need to restore the nesting", "# stack to its former state before the #else, otherwise we", "# will just continue from where we left off.", "if", "self", ".", "pp_stack", "[", "-", "1", "]", ".", "seen_else", ":", "# Here we can just use a shallow copy since we are the last", "# reference to it.", "self", ".", "stack", "=", "self", ".", "pp_stack", "[", "-", "1", "]", ".", "stack_before_else", "# Drop the corresponding #if", "self", ".", "pp_stack", ".", "pop", "(", ")", "else", ":", "# TODO(unknown): unexpected #endif, issue warning?", "pass" ]
https://github.com/intel/caffe/blob/3f494b442ee3f9d17a07b09ecbd5fa2bbda00836/scripts/cpp_lint.py#L1952-L2006
microsoft/TSS.MSR
0f2516fca2cd9929c31d5450e39301c9bde43688
TSS.Py/src/Tpm.py
python
Tpm.HMAC_Start
(self, handle, auth, hashAlg)
return res.handle if res else None
This command starts an HMAC sequence. The TPM will create and initialize an HMAC sequence structure, assign a handle to the sequence, and set the authValue of the sequence object to the value in auth. Args: handle (TPM_HANDLE): Handle of an HMAC key Auth Index: 1 Auth Role: USER auth (bytes): Authorization value for subsequent use of the sequence hashAlg (TPM_ALG_ID): The hash algorithm to use for the HMAC Returns: handle - A handle to reference the sequence
This command starts an HMAC sequence. The TPM will create and initialize an HMAC sequence structure, assign a handle to the sequence, and set the authValue of the sequence object to the value in auth.
[ "This", "command", "starts", "an", "HMAC", "sequence", ".", "The", "TPM", "will", "create", "and", "initialize", "an", "HMAC", "sequence", "structure", "assign", "a", "handle", "to", "the", "sequence", "and", "set", "the", "authValue", "of", "the", "sequence", "object", "to", "the", "value", "in", "auth", "." ]
def HMAC_Start(self, handle, auth, hashAlg): """ This command starts an HMAC sequence. The TPM will create and initialize an HMAC sequence structure, assign a handle to the sequence, and set the authValue of the sequence object to the value in auth. Args: handle (TPM_HANDLE): Handle of an HMAC key Auth Index: 1 Auth Role: USER auth (bytes): Authorization value for subsequent use of the sequence hashAlg (TPM_ALG_ID): The hash algorithm to use for the HMAC Returns: handle - A handle to reference the sequence """ req = TPM2_HMAC_Start_REQUEST(handle, auth, hashAlg) respBuf = self.dispatchCommand(TPM_CC.HMAC_Start, req) res = self.processResponse(respBuf, HMAC_StartResponse) return res.handle if res else None
[ "def", "HMAC_Start", "(", "self", ",", "handle", ",", "auth", ",", "hashAlg", ")", ":", "req", "=", "TPM2_HMAC_Start_REQUEST", "(", "handle", ",", "auth", ",", "hashAlg", ")", "respBuf", "=", "self", ".", "dispatchCommand", "(", "TPM_CC", ".", "HMAC_Start", ",", "req", ")", "res", "=", "self", ".", "processResponse", "(", "respBuf", ",", "HMAC_StartResponse", ")", "return", "res", ".", "handle", "if", "res", "else", "None" ]
https://github.com/microsoft/TSS.MSR/blob/0f2516fca2cd9929c31d5450e39301c9bde43688/TSS.Py/src/Tpm.py#L805-L823
miyosuda/TensorFlowAndroidDemo
35903e0221aa5f109ea2dbef27f20b52e317f42d
jni-build/jni/include/tensorflow/contrib/slim/python/slim/data/tfexample_decoder.py
python
Image.__init__
(self, image_key=None, format_key=None, shape=None, channels=3)
Initializes the image. Args: image_key: the name of the TF-Example feature in which the encoded image is stored. format_key: the name of the TF-Example feature in which the encoded image is stored. shape: the output shape of the image. If provided, the image is reshaped accordingly. If left as None, no reshaping is done. A shape should be supplied only if all the stored images have the same shape. channels: the number of channels in the image.
Initializes the image.
[ "Initializes", "the", "image", "." ]
def __init__(self, image_key=None, format_key=None, shape=None, channels=3): """Initializes the image. Args: image_key: the name of the TF-Example feature in which the encoded image is stored. format_key: the name of the TF-Example feature in which the encoded image is stored. shape: the output shape of the image. If provided, the image is reshaped accordingly. If left as None, no reshaping is done. A shape should be supplied only if all the stored images have the same shape. channels: the number of channels in the image. """ if not image_key: image_key = 'image/encoded' if not format_key: format_key = 'image/format' super(Image, self).__init__([image_key, format_key]) self._image_key = image_key self._format_key = format_key self._shape = shape self._channels = channels
[ "def", "__init__", "(", "self", ",", "image_key", "=", "None", ",", "format_key", "=", "None", ",", "shape", "=", "None", ",", "channels", "=", "3", ")", ":", "if", "not", "image_key", ":", "image_key", "=", "'image/encoded'", "if", "not", "format_key", ":", "format_key", "=", "'image/format'", "super", "(", "Image", ",", "self", ")", ".", "__init__", "(", "[", "image_key", ",", "format_key", "]", ")", "self", ".", "_image_key", "=", "image_key", "self", ".", "_format_key", "=", "format_key", "self", ".", "_shape", "=", "shape", "self", ".", "_channels", "=", "channels" ]
https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/contrib/slim/python/slim/data/tfexample_decoder.py#L222-L245
eclipse/sumo
7132a9b8b6eea734bdec38479026b4d8c4336d03
tools/turn-defs/turndefinitions.py
python
TurnDefinitions.get_turning_probability
(self, source, destination)
return self.turn_definitions[source][destination]
Returns the turning probability related to the given turn definition. The source and destination must have been added before.
Returns the turning probability related to the given turn definition. The source and destination must have been added before.
[ "Returns", "the", "turning", "probability", "related", "to", "the", "given", "turn", "definition", ".", "The", "source", "and", "destination", "must", "have", "been", "added", "before", "." ]
def get_turning_probability(self, source, destination): """ Returns the turning probability related to the given turn definition. The source and destination must have been added before. """ return self.turn_definitions[source][destination]
[ "def", "get_turning_probability", "(", "self", ",", "source", ",", "destination", ")", ":", "return", "self", ".", "turn_definitions", "[", "source", "]", "[", "destination", "]" ]
https://github.com/eclipse/sumo/blob/7132a9b8b6eea734bdec38479026b4d8c4336d03/tools/turn-defs/turndefinitions.py#L85-L92
jeog/TDAmeritradeAPI
91c738afd7d57b54f6231170bd64c2550fafd34d
python/tdma_api/get.py
python
_APIGetter.get_timeout
(self)
return clib.get_val('APIGetter_GetTimeout_ABI', c_ulonglong, self._obj)
Get transfer timeout in milliseconds(NOT the connection timeout). 0 indicates no timeout(default).
Get transfer timeout in milliseconds(NOT the connection timeout).
[ "Get", "transfer", "timeout", "in", "milliseconds", "(", "NOT", "the", "connection", "timeout", ")", "." ]
def get_timeout(self): """Get transfer timeout in milliseconds(NOT the connection timeout). 0 indicates no timeout(default). """ return clib.get_val('APIGetter_GetTimeout_ABI', c_ulonglong, self._obj)
[ "def", "get_timeout", "(", "self", ")", ":", "return", "clib", ".", "get_val", "(", "'APIGetter_GetTimeout_ABI'", ",", "c_ulonglong", ",", "self", ".", "_obj", ")" ]
https://github.com/jeog/TDAmeritradeAPI/blob/91c738afd7d57b54f6231170bd64c2550fafd34d/python/tdma_api/get.py#L246-L251
gem5/gem5
141cc37c2d4b93959d4c249b8f7e6a8b2ef75338
src/python/m5/util/fdthelper.py
python
FdtNode.append
(self, subnodes)
Change the behavior of the normal append to override if a node with the same name already exists or merge if the name exists and is a node type. Can also take a list of subnodes, that each get appended.
Change the behavior of the normal append to override if a node with the same name already exists or merge if the name exists and is a node type. Can also take a list of subnodes, that each get appended.
[ "Change", "the", "behavior", "of", "the", "normal", "append", "to", "override", "if", "a", "node", "with", "the", "same", "name", "already", "exists", "or", "merge", "if", "the", "name", "exists", "and", "is", "a", "node", "type", ".", "Can", "also", "take", "a", "list", "of", "subnodes", "that", "each", "get", "appended", "." ]
def append(self, subnodes): """Change the behavior of the normal append to override if a node with the same name already exists or merge if the name exists and is a node type. Can also take a list of subnodes, that each get appended.""" if not hasattr(subnodes, '__iter__'): subnodes = [subnodes] for subnode in subnodes: try: if not issubclass(type(subnode), pyfdt.FdtNop): index = self.index(subnode.name) item = self.pop(index) else: item = None except ValueError: item = None if isinstance(item, pyfdt.FdtNode) and \ isinstance(subnode, pyfdt.FdtNode): item.merge(subnode) subnode = item super().append(subnode)
[ "def", "append", "(", "self", ",", "subnodes", ")", ":", "if", "not", "hasattr", "(", "subnodes", ",", "'__iter__'", ")", ":", "subnodes", "=", "[", "subnodes", "]", "for", "subnode", "in", "subnodes", ":", "try", ":", "if", "not", "issubclass", "(", "type", "(", "subnode", ")", ",", "pyfdt", ".", "FdtNop", ")", ":", "index", "=", "self", ".", "index", "(", "subnode", ".", "name", ")", "item", "=", "self", ".", "pop", "(", "index", ")", "else", ":", "item", "=", "None", "except", "ValueError", ":", "item", "=", "None", "if", "isinstance", "(", "item", ",", "pyfdt", ".", "FdtNode", ")", "and", "isinstance", "(", "subnode", ",", "pyfdt", ".", "FdtNode", ")", ":", "item", ".", "merge", "(", "subnode", ")", "subnode", "=", "item", "super", "(", ")", ".", "append", "(", "subnode", ")" ]
https://github.com/gem5/gem5/blob/141cc37c2d4b93959d4c249b8f7e6a8b2ef75338/src/python/m5/util/fdthelper.py#L179-L201
google/filament
d21f092645b8e1e312307cbf89f1484891347c63
third_party/libassimp/port/PyAssimp/scripts/transformations.py
python
projection_matrix
(point, normal, direction=None, perspective=None, pseudo=False)
return M
Return matrix to project onto plane defined by point and normal. Using either perspective point, projection direction, or none of both. If pseudo is True, perspective projections will preserve relative depth such that Perspective = dot(Orthogonal, PseudoPerspective). >>> P = projection_matrix((0, 0, 0), (1, 0, 0)) >>> numpy.allclose(P[1:, 1:], numpy.identity(4)[1:, 1:]) True >>> point = numpy.random.random(3) - 0.5 >>> normal = numpy.random.random(3) - 0.5 >>> direct = numpy.random.random(3) - 0.5 >>> persp = numpy.random.random(3) - 0.5 >>> P0 = projection_matrix(point, normal) >>> P1 = projection_matrix(point, normal, direction=direct) >>> P2 = projection_matrix(point, normal, perspective=persp) >>> P3 = projection_matrix(point, normal, perspective=persp, pseudo=True) >>> is_same_transform(P2, numpy.dot(P0, P3)) True >>> P = projection_matrix((3, 0, 0), (1, 1, 0), (1, 0, 0)) >>> v0 = (numpy.random.rand(4, 5) - 0.5) * 20.0 >>> v0[3] = 1.0 >>> v1 = numpy.dot(P, v0) >>> numpy.allclose(v1[1], v0[1]) True >>> numpy.allclose(v1[0], 3.0-v1[1]) True
Return matrix to project onto plane defined by point and normal.
[ "Return", "matrix", "to", "project", "onto", "plane", "defined", "by", "point", "and", "normal", "." ]
def projection_matrix(point, normal, direction=None, perspective=None, pseudo=False): """Return matrix to project onto plane defined by point and normal. Using either perspective point, projection direction, or none of both. If pseudo is True, perspective projections will preserve relative depth such that Perspective = dot(Orthogonal, PseudoPerspective). >>> P = projection_matrix((0, 0, 0), (1, 0, 0)) >>> numpy.allclose(P[1:, 1:], numpy.identity(4)[1:, 1:]) True >>> point = numpy.random.random(3) - 0.5 >>> normal = numpy.random.random(3) - 0.5 >>> direct = numpy.random.random(3) - 0.5 >>> persp = numpy.random.random(3) - 0.5 >>> P0 = projection_matrix(point, normal) >>> P1 = projection_matrix(point, normal, direction=direct) >>> P2 = projection_matrix(point, normal, perspective=persp) >>> P3 = projection_matrix(point, normal, perspective=persp, pseudo=True) >>> is_same_transform(P2, numpy.dot(P0, P3)) True >>> P = projection_matrix((3, 0, 0), (1, 1, 0), (1, 0, 0)) >>> v0 = (numpy.random.rand(4, 5) - 0.5) * 20.0 >>> v0[3] = 1.0 >>> v1 = numpy.dot(P, v0) >>> numpy.allclose(v1[1], v0[1]) True >>> numpy.allclose(v1[0], 3.0-v1[1]) True """ M = numpy.identity(4) point = numpy.array(point[:3], dtype=numpy.float64, copy=False) normal = unit_vector(normal[:3]) if perspective is not None: # perspective projection perspective = numpy.array(perspective[:3], dtype=numpy.float64, copy=False) M[0, 0] = M[1, 1] = M[2, 2] = numpy.dot(perspective-point, normal) M[:3, :3] -= numpy.outer(perspective, normal) if pseudo: # preserve relative depth M[:3, :3] -= numpy.outer(normal, normal) M[:3, 3] = numpy.dot(point, normal) * (perspective+normal) else: M[:3, 3] = numpy.dot(point, normal) * perspective M[3, :3] = -normal M[3, 3] = numpy.dot(perspective, normal) elif direction is not None: # parallel projection direction = numpy.array(direction[:3], dtype=numpy.float64, copy=False) scale = numpy.dot(direction, normal) M[:3, :3] -= numpy.outer(direction, normal) / scale M[:3, 3] = direction * (numpy.dot(point, normal) / scale) else: # orthogonal projection M[:3, :3] -= numpy.outer(normal, normal) M[:3, 3] = numpy.dot(point, normal) * normal return M
[ "def", "projection_matrix", "(", "point", ",", "normal", ",", "direction", "=", "None", ",", "perspective", "=", "None", ",", "pseudo", "=", "False", ")", ":", "M", "=", "numpy", ".", "identity", "(", "4", ")", "point", "=", "numpy", ".", "array", "(", "point", "[", ":", "3", "]", ",", "dtype", "=", "numpy", ".", "float64", ",", "copy", "=", "False", ")", "normal", "=", "unit_vector", "(", "normal", "[", ":", "3", "]", ")", "if", "perspective", "is", "not", "None", ":", "# perspective projection", "perspective", "=", "numpy", ".", "array", "(", "perspective", "[", ":", "3", "]", ",", "dtype", "=", "numpy", ".", "float64", ",", "copy", "=", "False", ")", "M", "[", "0", ",", "0", "]", "=", "M", "[", "1", ",", "1", "]", "=", "M", "[", "2", ",", "2", "]", "=", "numpy", ".", "dot", "(", "perspective", "-", "point", ",", "normal", ")", "M", "[", ":", "3", ",", ":", "3", "]", "-=", "numpy", ".", "outer", "(", "perspective", ",", "normal", ")", "if", "pseudo", ":", "# preserve relative depth", "M", "[", ":", "3", ",", ":", "3", "]", "-=", "numpy", ".", "outer", "(", "normal", ",", "normal", ")", "M", "[", ":", "3", ",", "3", "]", "=", "numpy", ".", "dot", "(", "point", ",", "normal", ")", "*", "(", "perspective", "+", "normal", ")", "else", ":", "M", "[", ":", "3", ",", "3", "]", "=", "numpy", ".", "dot", "(", "point", ",", "normal", ")", "*", "perspective", "M", "[", "3", ",", ":", "3", "]", "=", "-", "normal", "M", "[", "3", ",", "3", "]", "=", "numpy", ".", "dot", "(", "perspective", ",", "normal", ")", "elif", "direction", "is", "not", "None", ":", "# parallel projection", "direction", "=", "numpy", ".", "array", "(", "direction", "[", ":", "3", "]", ",", "dtype", "=", "numpy", ".", "float64", ",", "copy", "=", "False", ")", "scale", "=", "numpy", ".", "dot", "(", "direction", ",", "normal", ")", "M", "[", ":", "3", ",", ":", "3", "]", "-=", "numpy", ".", "outer", "(", "direction", ",", "normal", ")", "/", "scale", "M", "[", ":", "3", ",", "3", "]", "=", "direction", "*", "(", "numpy", ".", "dot", "(", "point", ",", "normal", ")", "/", "scale", ")", "else", ":", "# orthogonal projection", "M", "[", ":", "3", ",", ":", "3", "]", "-=", "numpy", ".", "outer", "(", "normal", ",", "normal", ")", "M", "[", ":", "3", ",", "3", "]", "=", "numpy", ".", "dot", "(", "point", ",", "normal", ")", "*", "normal", "return", "M" ]
https://github.com/google/filament/blob/d21f092645b8e1e312307cbf89f1484891347c63/third_party/libassimp/port/PyAssimp/scripts/transformations.py#L437-L496
shogun-toolbox/shogun
9b8d856971af5a295dd6ad70623ae45647a6334c
applications/easysvm/esvm/experiment.py
python
create_kernel
(kname,kparam,feats_train)
return kernel
Call the corresponding constructor for the kernel
Call the corresponding constructor for the kernel
[ "Call", "the", "corresponding", "constructor", "for", "the", "kernel" ]
def create_kernel(kname,kparam,feats_train): """Call the corresponding constructor for the kernel""" if kname == 'gauss': kernel = GaussianKernel(feats_train, feats_train, kparam['width']) elif kname == 'linear': kernel = LinearKernel(feats_train, feats_train) kernel.set_normalizer(AvgDiagKernelNormalizer(kparam['scale'])) elif kname == 'poly': kernel = PolyKernel(feats_train, feats_train, kparam['degree'], kparam['inhomogene'], kparam['normal']) elif kname == 'wd': kernel=WeightedDegreePositionStringKernel(feats_train, feats_train, kparam['degree']) kernel.set_normalizer(AvgDiagKernelNormalizer(float(kparam['seqlength']))) kernel.set_shifts(kparam['shift']*numpy.ones(kparam['seqlength'],dtype=numpy.int32)) #kernel=WeightedDegreeStringKernel(feats_train, feats_train, kparam['degree']) elif kname == 'spec': kernel = CommUlongStringKernel(feats_train, feats_train) elif kname == 'cumspec': kernel = WeightedCommWordStringKernel(feats_train, feats_train) kernel.set_weights(numpy.ones(kparam['degree'])) elif kname == 'spec2': kernel = CombinedKernel() k0 = CommWordStringKernel(feats_train['f0'], feats_train['f0']) k0.io.disable_progress() kernel.append_kernel(k0) k1 = CommWordStringKernel(feats_train['f1'], feats_train['f1']) k1.io.disable_progress() kernel.append_kernel(k1) elif kname == 'cumspec2': kernel = CombinedKernel() k0 = WeightedCommWordStringKernel(feats_train['f0'], feats_train['f0']) k0.set_weights(numpy.ones(kparam['degree'])) k0.io.disable_progress() kernel.append_kernel(k0) k1 = WeightedCommWordStringKernel(feats_train['f1'], feats_train['f1']) k1.set_weights(numpy.ones(kparam['degree'])) k1.io.disable_progress() kernel.append_kernel(k1) elif kname == 'localalign': kernel = LocalAlignmentStringKernel(feats_train, feats_train) elif kname == 'localimprove': kernel = LocalityImprovedStringKernel(feats_train, feats_train, kparam['length'],\ kparam['indeg'], kparam['outdeg']) else: print 'Unknown kernel %s' % kname kernel.set_cache_size(32) return kernel
[ "def", "create_kernel", "(", "kname", ",", "kparam", ",", "feats_train", ")", ":", "if", "kname", "==", "'gauss'", ":", "kernel", "=", "GaussianKernel", "(", "feats_train", ",", "feats_train", ",", "kparam", "[", "'width'", "]", ")", "elif", "kname", "==", "'linear'", ":", "kernel", "=", "LinearKernel", "(", "feats_train", ",", "feats_train", ")", "kernel", ".", "set_normalizer", "(", "AvgDiagKernelNormalizer", "(", "kparam", "[", "'scale'", "]", ")", ")", "elif", "kname", "==", "'poly'", ":", "kernel", "=", "PolyKernel", "(", "feats_train", ",", "feats_train", ",", "kparam", "[", "'degree'", "]", ",", "kparam", "[", "'inhomogene'", "]", ",", "kparam", "[", "'normal'", "]", ")", "elif", "kname", "==", "'wd'", ":", "kernel", "=", "WeightedDegreePositionStringKernel", "(", "feats_train", ",", "feats_train", ",", "kparam", "[", "'degree'", "]", ")", "kernel", ".", "set_normalizer", "(", "AvgDiagKernelNormalizer", "(", "float", "(", "kparam", "[", "'seqlength'", "]", ")", ")", ")", "kernel", ".", "set_shifts", "(", "kparam", "[", "'shift'", "]", "*", "numpy", ".", "ones", "(", "kparam", "[", "'seqlength'", "]", ",", "dtype", "=", "numpy", ".", "int32", ")", ")", "#kernel=WeightedDegreeStringKernel(feats_train, feats_train, kparam['degree'])", "elif", "kname", "==", "'spec'", ":", "kernel", "=", "CommUlongStringKernel", "(", "feats_train", ",", "feats_train", ")", "elif", "kname", "==", "'cumspec'", ":", "kernel", "=", "WeightedCommWordStringKernel", "(", "feats_train", ",", "feats_train", ")", "kernel", ".", "set_weights", "(", "numpy", ".", "ones", "(", "kparam", "[", "'degree'", "]", ")", ")", "elif", "kname", "==", "'spec2'", ":", "kernel", "=", "CombinedKernel", "(", ")", "k0", "=", "CommWordStringKernel", "(", "feats_train", "[", "'f0'", "]", ",", "feats_train", "[", "'f0'", "]", ")", "k0", ".", "io", ".", "disable_progress", "(", ")", "kernel", ".", "append_kernel", "(", "k0", ")", "k1", "=", "CommWordStringKernel", "(", "feats_train", "[", "'f1'", "]", ",", "feats_train", "[", "'f1'", "]", ")", "k1", ".", "io", ".", "disable_progress", "(", ")", "kernel", ".", "append_kernel", "(", "k1", ")", "elif", "kname", "==", "'cumspec2'", ":", "kernel", "=", "CombinedKernel", "(", ")", "k0", "=", "WeightedCommWordStringKernel", "(", "feats_train", "[", "'f0'", "]", ",", "feats_train", "[", "'f0'", "]", ")", "k0", ".", "set_weights", "(", "numpy", ".", "ones", "(", "kparam", "[", "'degree'", "]", ")", ")", "k0", ".", "io", ".", "disable_progress", "(", ")", "kernel", ".", "append_kernel", "(", "k0", ")", "k1", "=", "WeightedCommWordStringKernel", "(", "feats_train", "[", "'f1'", "]", ",", "feats_train", "[", "'f1'", "]", ")", "k1", ".", "set_weights", "(", "numpy", ".", "ones", "(", "kparam", "[", "'degree'", "]", ")", ")", "k1", ".", "io", ".", "disable_progress", "(", ")", "kernel", ".", "append_kernel", "(", "k1", ")", "elif", "kname", "==", "'localalign'", ":", "kernel", "=", "LocalAlignmentStringKernel", "(", "feats_train", ",", "feats_train", ")", "elif", "kname", "==", "'localimprove'", ":", "kernel", "=", "LocalityImprovedStringKernel", "(", "feats_train", ",", "feats_train", ",", "kparam", "[", "'length'", "]", ",", "kparam", "[", "'indeg'", "]", ",", "kparam", "[", "'outdeg'", "]", ")", "else", ":", "print", "'Unknown kernel %s'", "%", "kname", "kernel", ".", "set_cache_size", "(", "32", ")", "return", "kernel" ]
https://github.com/shogun-toolbox/shogun/blob/9b8d856971af5a295dd6ad70623ae45647a6334c/applications/easysvm/esvm/experiment.py#L195-L242
alibaba/graph-learn
54cafee9db3054dc310a28b856be7f97c7d5aee9
graphlearn/python/sampler/negative_sampler.py
python
NegativeSampler.get
(self, ids)
return neg_nbrs
Get batched negative samples. Args: ids (numpy.array): A 1d numpy array of whose negative dst nodes will be sampled. Return: A `Nodes` object, shape=[ids.shape, `expand_factor`].
Get batched negative samples.
[ "Get", "batched", "negative", "samples", "." ]
def get(self, ids): """ Get batched negative samples. Args: ids (numpy.array): A 1d numpy array of whose negative dst nodes will be sampled. Return: A `Nodes` object, shape=[ids.shape, `expand_factor`]. """ ids = np.array(ids).flatten() req = self._make_req(ids) res = pywrap.new_sampling_response() status = self._client.sample_neighbor(req, res) if status.ok(): nbrs = pywrap.get_sampling_node_ids(res) neg_nbrs = self._graph.get_nodes( self._dst_type, nbrs, shape=(ids.shape[0], self._expand_factor)) pywrap.del_op_response(res) pywrap.del_op_request(req) errors.raise_exception_on_not_ok_status(status) return neg_nbrs
[ "def", "get", "(", "self", ",", "ids", ")", ":", "ids", "=", "np", ".", "array", "(", "ids", ")", ".", "flatten", "(", ")", "req", "=", "self", ".", "_make_req", "(", "ids", ")", "res", "=", "pywrap", ".", "new_sampling_response", "(", ")", "status", "=", "self", ".", "_client", ".", "sample_neighbor", "(", "req", ",", "res", ")", "if", "status", ".", "ok", "(", ")", ":", "nbrs", "=", "pywrap", ".", "get_sampling_node_ids", "(", "res", ")", "neg_nbrs", "=", "self", ".", "_graph", ".", "get_nodes", "(", "self", ".", "_dst_type", ",", "nbrs", ",", "shape", "=", "(", "ids", ".", "shape", "[", "0", "]", ",", "self", ".", "_expand_factor", ")", ")", "pywrap", ".", "del_op_response", "(", "res", ")", "pywrap", ".", "del_op_request", "(", "req", ")", "errors", ".", "raise_exception_on_not_ok_status", "(", "status", ")", "return", "neg_nbrs" ]
https://github.com/alibaba/graph-learn/blob/54cafee9db3054dc310a28b856be7f97c7d5aee9/graphlearn/python/sampler/negative_sampler.py#L64-L87
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/pip/vendor/distlib/_backport/tarfile.py
python
TarInfo._create_pax_generic_header
(cls, pax_headers, type, encoding)
return cls._create_header(info, USTAR_FORMAT, "ascii", "replace") + \ cls._create_payload(records)
Return a POSIX.1-2008 extended or global header sequence that contains a list of keyword, value pairs. The values must be strings.
Return a POSIX.1-2008 extended or global header sequence that contains a list of keyword, value pairs. The values must be strings.
[ "Return", "a", "POSIX", ".", "1", "-", "2008", "extended", "or", "global", "header", "sequence", "that", "contains", "a", "list", "of", "keyword", "value", "pairs", ".", "The", "values", "must", "be", "strings", "." ]
def _create_pax_generic_header(cls, pax_headers, type, encoding): """Return a POSIX.1-2008 extended or global header sequence that contains a list of keyword, value pairs. The values must be strings. """ # Check if one of the fields contains surrogate characters and thereby # forces hdrcharset=BINARY, see _proc_pax() for more information. binary = False for keyword, value in pax_headers.items(): try: value.encode("utf8", "strict") except UnicodeEncodeError: binary = True break records = b"" if binary: # Put the hdrcharset field at the beginning of the header. records += b"21 hdrcharset=BINARY\n" for keyword, value in pax_headers.items(): keyword = keyword.encode("utf8") if binary: # Try to restore the original byte representation of `value'. # Needless to say, that the encoding must match the string. value = value.encode(encoding, "surrogateescape") else: value = value.encode("utf8") l = len(keyword) + len(value) + 3 # ' ' + '=' + '\n' n = p = 0 while True: n = l + len(str(p)) if n == p: break p = n records += bytes(str(p), "ascii") + b" " + keyword + b"=" + value + b"\n" # We use a hardcoded "././@PaxHeader" name like star does # instead of the one that POSIX recommends. info = {} info["name"] = "././@PaxHeader" info["type"] = type info["size"] = len(records) info["magic"] = POSIX_MAGIC # Create pax header + record blocks. return cls._create_header(info, USTAR_FORMAT, "ascii", "replace") + \ cls._create_payload(records)
[ "def", "_create_pax_generic_header", "(", "cls", ",", "pax_headers", ",", "type", ",", "encoding", ")", ":", "# Check if one of the fields contains surrogate characters and thereby", "# forces hdrcharset=BINARY, see _proc_pax() for more information.", "binary", "=", "False", "for", "keyword", ",", "value", "in", "pax_headers", ".", "items", "(", ")", ":", "try", ":", "value", ".", "encode", "(", "\"utf8\"", ",", "\"strict\"", ")", "except", "UnicodeEncodeError", ":", "binary", "=", "True", "break", "records", "=", "b\"\"", "if", "binary", ":", "# Put the hdrcharset field at the beginning of the header.", "records", "+=", "b\"21 hdrcharset=BINARY\\n\"", "for", "keyword", ",", "value", "in", "pax_headers", ".", "items", "(", ")", ":", "keyword", "=", "keyword", ".", "encode", "(", "\"utf8\"", ")", "if", "binary", ":", "# Try to restore the original byte representation of `value'.", "# Needless to say, that the encoding must match the string.", "value", "=", "value", ".", "encode", "(", "encoding", ",", "\"surrogateescape\"", ")", "else", ":", "value", "=", "value", ".", "encode", "(", "\"utf8\"", ")", "l", "=", "len", "(", "keyword", ")", "+", "len", "(", "value", ")", "+", "3", "# ' ' + '=' + '\\n'", "n", "=", "p", "=", "0", "while", "True", ":", "n", "=", "l", "+", "len", "(", "str", "(", "p", ")", ")", "if", "n", "==", "p", ":", "break", "p", "=", "n", "records", "+=", "bytes", "(", "str", "(", "p", ")", ",", "\"ascii\"", ")", "+", "b\" \"", "+", "keyword", "+", "b\"=\"", "+", "value", "+", "b\"\\n\"", "# We use a hardcoded \"././@PaxHeader\" name like star does", "# instead of the one that POSIX recommends.", "info", "=", "{", "}", "info", "[", "\"name\"", "]", "=", "\"././@PaxHeader\"", "info", "[", "\"type\"", "]", "=", "type", "info", "[", "\"size\"", "]", "=", "len", "(", "records", ")", "info", "[", "\"magic\"", "]", "=", "POSIX_MAGIC", "# Create pax header + record blocks.", "return", "cls", ".", "_create_header", "(", "info", ",", "USTAR_FORMAT", ",", "\"ascii\"", ",", "\"replace\"", ")", "+", "cls", ".", "_create_payload", "(", "records", ")" ]
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/pip/vendor/distlib/_backport/tarfile.py#L1169-L1217