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
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/uuid.py
python
_unixdll_getnode
()
return UUID(bytes=_buffer.raw).node
Get the hardware address on Unix using ctypes.
Get the hardware address on Unix using ctypes.
[ "Get", "the", "hardware", "address", "on", "Unix", "using", "ctypes", "." ]
def _unixdll_getnode(): """Get the hardware address on Unix using ctypes.""" _buffer = ctypes.create_string_buffer(16) _uuid_generate_time(_buffer) return UUID(bytes=_buffer.raw).node
[ "def", "_unixdll_getnode", "(", ")", ":", "_buffer", "=", "ctypes", ".", "create_string_buffer", "(", "16", ")", "_uuid_generate_time", "(", "_buffer", ")", "return", "UUID", "(", "bytes", "=", "_buffer", ".", "raw", ")", ".", "node" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/uuid.py#L442-L446
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_controls.py
python
CheckListBox.GetChecked
(self)
return tuple([i for i in range(self.Count) if self.IsChecked(i)])
GetChecked(self) Return a tuple of integers corresponding to the checked items in the control, based on `IsChecked`.
GetChecked(self)
[ "GetChecked", "(", "self", ")" ]
def GetChecked(self): """ GetChecked(self) Return a tuple of integers corresponding to the checked items in the control, based on `IsChecked`. """ return tuple([i for i in range(self.Count) if self.IsChecked(i)])
[ "def", "GetChecked", "(", "self", ")", ":", "return", "tuple", "(", "[", "i", "for", "i", "in", "range", "(", "self", ".", "Count", ")", "if", "self", ".", "IsChecked", "(", "i", ")", "]", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_controls.py#L1334-L1341
isl-org/Open3D
79aec3ddde6a571ce2f28e4096477e52ec465244
util/check_style.py
python
_find_clang_format
()
return clang_format_bin
Find clang-format: - not found: throw exception - version mismatch: print warning
Find clang-format: - not found: throw exception - version mismatch: print warning
[ "Find", "clang", "-", "format", ":", "-", "not", "found", ":", "throw", "exception", "-", "version", "mismatch", ":", "print", "warning" ]
def _find_clang_format(): """ Find clang-format: - not found: throw exception - version mismatch: print warning """ preferred_clang_format_name = "clang-format-10" preferred_version_major = 10 clang_format_bin = shutil.which(preferred_clang_format_name) if clang_format_bin is None: clang_format_bin = shutil.which("clang-format") if clang_format_bin is None: raise RuntimeError( "clang-format not found. " "See http://www.open3d.org/docs/release/contribute/styleguide.html#style-guide " "for help on clang-format installation.") version_str = subprocess.check_output([clang_format_bin, "--version" ]).decode("utf-8").strip() try: m = re.match("^clang-format version ([0-9.]*).*$", version_str) if m: version_str = m.group(1) version_str_token = version_str.split(".") major = int(version_str_token[0]) if major != preferred_version_major: print("Warning: {} required, but got {}.".format( preferred_clang_format_name, version_str)) else: raise except: print("Warning: failed to parse clang-format version {}, " "please ensure {} is used.".format(version_str, preferred_clang_format_name)) print("Using clang-format version {}.".format(version_str)) return clang_format_bin
[ "def", "_find_clang_format", "(", ")", ":", "preferred_clang_format_name", "=", "\"clang-format-10\"", "preferred_version_major", "=", "10", "clang_format_bin", "=", "shutil", ".", "which", "(", "preferred_clang_format_name", ")", "if", "clang_format_bin", "is", "None", ":", "clang_format_bin", "=", "shutil", ".", "which", "(", "\"clang-format\"", ")", "if", "clang_format_bin", "is", "None", ":", "raise", "RuntimeError", "(", "\"clang-format not found. \"", "\"See http://www.open3d.org/docs/release/contribute/styleguide.html#style-guide \"", "\"for help on clang-format installation.\"", ")", "version_str", "=", "subprocess", ".", "check_output", "(", "[", "clang_format_bin", ",", "\"--version\"", "]", ")", ".", "decode", "(", "\"utf-8\"", ")", ".", "strip", "(", ")", "try", ":", "m", "=", "re", ".", "match", "(", "\"^clang-format version ([0-9.]*).*$\"", ",", "version_str", ")", "if", "m", ":", "version_str", "=", "m", ".", "group", "(", "1", ")", "version_str_token", "=", "version_str", ".", "split", "(", "\".\"", ")", "major", "=", "int", "(", "version_str_token", "[", "0", "]", ")", "if", "major", "!=", "preferred_version_major", ":", "print", "(", "\"Warning: {} required, but got {}.\"", ".", "format", "(", "preferred_clang_format_name", ",", "version_str", ")", ")", "else", ":", "raise", "except", ":", "print", "(", "\"Warning: failed to parse clang-format version {}, \"", "\"please ensure {} is used.\"", ".", "format", "(", "version_str", ",", "preferred_clang_format_name", ")", ")", "print", "(", "\"Using clang-format version {}.\"", ".", "format", "(", "version_str", ")", ")", "return", "clang_format_bin" ]
https://github.com/isl-org/Open3D/blob/79aec3ddde6a571ce2f28e4096477e52ec465244/util/check_style.py#L110-L145
deepmind/open_spiel
4ca53bea32bb2875c7385d215424048ae92f78c8
open_spiel/python/mfg/games/dynamic_routing.py
python
MeanFieldRoutingGame.make_py_observer
(self, iig_obs_type=None, params=None)
return IIGObserverForPublicInfoGame(iig_obs_type, params)
Returns a NetworkObserver object used for observing game state.
Returns a NetworkObserver object used for observing game state.
[ "Returns", "a", "NetworkObserver", "object", "used", "for", "observing", "game", "state", "." ]
def make_py_observer(self, iig_obs_type=None, params=None): """Returns a NetworkObserver object used for observing game state.""" if ((iig_obs_type is None) or (iig_obs_type.public_info and not iig_obs_type.perfect_recall)): return NetworkObserver(self.network.num_actions(), self.max_game_length()) return IIGObserverForPublicInfoGame(iig_obs_type, params)
[ "def", "make_py_observer", "(", "self", ",", "iig_obs_type", "=", "None", ",", "params", "=", "None", ")", ":", "if", "(", "(", "iig_obs_type", "is", "None", ")", "or", "(", "iig_obs_type", ".", "public_info", "and", "not", "iig_obs_type", ".", "perfect_recall", ")", ")", ":", "return", "NetworkObserver", "(", "self", ".", "network", ".", "num_actions", "(", ")", ",", "self", ".", "max_game_length", "(", ")", ")", "return", "IIGObserverForPublicInfoGame", "(", "iig_obs_type", ",", "params", ")" ]
https://github.com/deepmind/open_spiel/blob/4ca53bea32bb2875c7385d215424048ae92f78c8/open_spiel/python/mfg/games/dynamic_routing.py#L146-L151
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/richtext.py
python
RichTextParagraphLayoutBox.GetRichTextCtrl
(*args, **kwargs)
return _richtext.RichTextParagraphLayoutBox_GetRichTextCtrl(*args, **kwargs)
GetRichTextCtrl(self) -> RichTextCtrl
GetRichTextCtrl(self) -> RichTextCtrl
[ "GetRichTextCtrl", "(", "self", ")", "-", ">", "RichTextCtrl" ]
def GetRichTextCtrl(*args, **kwargs): """GetRichTextCtrl(self) -> RichTextCtrl""" return _richtext.RichTextParagraphLayoutBox_GetRichTextCtrl(*args, **kwargs)
[ "def", "GetRichTextCtrl", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_richtext", ".", "RichTextParagraphLayoutBox_GetRichTextCtrl", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/richtext.py#L1616-L1618
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/propgrid.py
python
PropertyGridInterface.Insert
(*args)
return _propgrid.PropertyGridInterface_Insert(*args)
Insert(self, PGPropArg priorThis, PGProperty newproperty) -> PGProperty Insert(self, PGPropArg parent, int index, PGProperty newproperty) -> PGProperty
Insert(self, PGPropArg priorThis, PGProperty newproperty) -> PGProperty Insert(self, PGPropArg parent, int index, PGProperty newproperty) -> PGProperty
[ "Insert", "(", "self", "PGPropArg", "priorThis", "PGProperty", "newproperty", ")", "-", ">", "PGProperty", "Insert", "(", "self", "PGPropArg", "parent", "int", "index", "PGProperty", "newproperty", ")", "-", ">", "PGProperty" ]
def Insert(*args): """ Insert(self, PGPropArg priorThis, PGProperty newproperty) -> PGProperty Insert(self, PGPropArg parent, int index, PGProperty newproperty) -> PGProperty """ return _propgrid.PropertyGridInterface_Insert(*args)
[ "def", "Insert", "(", "*", "args", ")", ":", "return", "_propgrid", ".", "PropertyGridInterface_Insert", "(", "*", "args", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/propgrid.py#L1297-L1302
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/difflib.py
python
SequenceMatcher.get_opcodes
(self)
return answer
Return list of 5-tuples describing how to turn a into b. Each tuple is of the form (tag, i1, i2, j1, j2). The first tuple has i1 == j1 == 0, and remaining tuples have i1 == the i2 from the tuple preceding it, and likewise for j1 == the previous j2. The tags are strings, with these meanings: 'replace': a[i1:i2] should be replaced by b[j1:j2] 'delete': a[i1:i2] should be deleted. Note that j1==j2 in this case. 'insert': b[j1:j2] should be inserted at a[i1:i1]. Note that i1==i2 in this case. 'equal': a[i1:i2] == b[j1:j2] >>> a = "qabxcd" >>> b = "abycdf" >>> s = SequenceMatcher(None, a, b) >>> for tag, i1, i2, j1, j2 in s.get_opcodes(): ... print(("%7s a[%d:%d] (%s) b[%d:%d] (%s)" % ... (tag, i1, i2, a[i1:i2], j1, j2, b[j1:j2]))) delete a[0:1] (q) b[0:0] () equal a[1:3] (ab) b[0:2] (ab) replace a[3:4] (x) b[2:3] (y) equal a[4:6] (cd) b[3:5] (cd) insert a[6:6] () b[5:6] (f)
Return list of 5-tuples describing how to turn a into b.
[ "Return", "list", "of", "5", "-", "tuples", "describing", "how", "to", "turn", "a", "into", "b", "." ]
def get_opcodes(self): """Return list of 5-tuples describing how to turn a into b. Each tuple is of the form (tag, i1, i2, j1, j2). The first tuple has i1 == j1 == 0, and remaining tuples have i1 == the i2 from the tuple preceding it, and likewise for j1 == the previous j2. The tags are strings, with these meanings: 'replace': a[i1:i2] should be replaced by b[j1:j2] 'delete': a[i1:i2] should be deleted. Note that j1==j2 in this case. 'insert': b[j1:j2] should be inserted at a[i1:i1]. Note that i1==i2 in this case. 'equal': a[i1:i2] == b[j1:j2] >>> a = "qabxcd" >>> b = "abycdf" >>> s = SequenceMatcher(None, a, b) >>> for tag, i1, i2, j1, j2 in s.get_opcodes(): ... print(("%7s a[%d:%d] (%s) b[%d:%d] (%s)" % ... (tag, i1, i2, a[i1:i2], j1, j2, b[j1:j2]))) delete a[0:1] (q) b[0:0] () equal a[1:3] (ab) b[0:2] (ab) replace a[3:4] (x) b[2:3] (y) equal a[4:6] (cd) b[3:5] (cd) insert a[6:6] () b[5:6] (f) """ if self.opcodes is not None: return self.opcodes i = j = 0 self.opcodes = answer = [] for ai, bj, size in self.get_matching_blocks(): # invariant: we've pumped out correct diffs to change # a[:i] into b[:j], and the next matching block is # a[ai:ai+size] == b[bj:bj+size]. So we need to pump # out a diff to change a[i:ai] into b[j:bj], pump out # the matching block, and move (i,j) beyond the match tag = '' if i < ai and j < bj: tag = 'replace' elif i < ai: tag = 'delete' elif j < bj: tag = 'insert' if tag: answer.append( (tag, i, ai, j, bj) ) i, j = ai+size, bj+size # the list of matching blocks is terminated by a # sentinel with size 0 if size: answer.append( ('equal', ai, i, bj, j) ) return answer
[ "def", "get_opcodes", "(", "self", ")", ":", "if", "self", ".", "opcodes", "is", "not", "None", ":", "return", "self", ".", "opcodes", "i", "=", "j", "=", "0", "self", ".", "opcodes", "=", "answer", "=", "[", "]", "for", "ai", ",", "bj", ",", "size", "in", "self", ".", "get_matching_blocks", "(", ")", ":", "# invariant: we've pumped out correct diffs to change", "# a[:i] into b[:j], and the next matching block is", "# a[ai:ai+size] == b[bj:bj+size]. So we need to pump", "# out a diff to change a[i:ai] into b[j:bj], pump out", "# the matching block, and move (i,j) beyond the match", "tag", "=", "''", "if", "i", "<", "ai", "and", "j", "<", "bj", ":", "tag", "=", "'replace'", "elif", "i", "<", "ai", ":", "tag", "=", "'delete'", "elif", "j", "<", "bj", ":", "tag", "=", "'insert'", "if", "tag", ":", "answer", ".", "append", "(", "(", "tag", ",", "i", ",", "ai", ",", "j", ",", "bj", ")", ")", "i", ",", "j", "=", "ai", "+", "size", ",", "bj", "+", "size", "# the list of matching blocks is terminated by a", "# sentinel with size 0", "if", "size", ":", "answer", ".", "append", "(", "(", "'equal'", ",", "ai", ",", "i", ",", "bj", ",", "j", ")", ")", "return", "answer" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/difflib.py#L517-L570
facebook/ThreatExchange
31914a51820c73c8a0daffe62ccca29a6e3d359e
hasher-matcher-actioner/hmalib/common/models/bank.py
python
BanksTable.add_bank_member_signal
( self, bank_id: str, bank_member_id: str, signal_type: t.Type[SignalType], signal_value: str, )
return member_signal
Adds a BankMemberSignal entry. First, identifies if a signal for the corresponding (type, value) tuple exists, if so, reuses it, it not, creates a new one. Returns a BankMemberSignal object. Clients **should not** care whether this is a new signal_id or not. This check is being done here because signal uniqueness is enforced by the same table. If this were being done in a different table/store, we could be doing the check at a different layer eg. hmalib.banks.bank_operations.
Adds a BankMemberSignal entry. First, identifies if a signal for the corresponding (type, value) tuple exists, if so, reuses it, it not, creates a new one.
[ "Adds", "a", "BankMemberSignal", "entry", ".", "First", "identifies", "if", "a", "signal", "for", "the", "corresponding", "(", "type", "value", ")", "tuple", "exists", "if", "so", "reuses", "it", "it", "not", "creates", "a", "new", "one", "." ]
def add_bank_member_signal( self, bank_id: str, bank_member_id: str, signal_type: t.Type[SignalType], signal_value: str, ) -> BankMemberSignal: """ Adds a BankMemberSignal entry. First, identifies if a signal for the corresponding (type, value) tuple exists, if so, reuses it, it not, creates a new one. Returns a BankMemberSignal object. Clients **should not** care whether this is a new signal_id or not. This check is being done here because signal uniqueness is enforced by the same table. If this were being done in a different table/store, we could be doing the check at a different layer eg. hmalib.banks.bank_operations. """ # First, we get a unique signal_id! signal_id = BankedSignalEntry.get_unique( self._table, signal_type=signal_type, signal_value=signal_value ).signal_id # Next, we create the bank member signal member_signal = BankMemberSignal( bank_id=bank_id, bank_member_id=bank_member_id, signal_id=signal_id, signal_type=signal_type, signal_value=signal_value, updated_at=datetime.now(), ) member_signal.write_to_table(self._table) return member_signal
[ "def", "add_bank_member_signal", "(", "self", ",", "bank_id", ":", "str", ",", "bank_member_id", ":", "str", ",", "signal_type", ":", "t", ".", "Type", "[", "SignalType", "]", ",", "signal_value", ":", "str", ",", ")", "->", "BankMemberSignal", ":", "# First, we get a unique signal_id!", "signal_id", "=", "BankedSignalEntry", ".", "get_unique", "(", "self", ".", "_table", ",", "signal_type", "=", "signal_type", ",", "signal_value", "=", "signal_value", ")", ".", "signal_id", "# Next, we create the bank member signal", "member_signal", "=", "BankMemberSignal", "(", "bank_id", "=", "bank_id", ",", "bank_member_id", "=", "bank_member_id", ",", "signal_id", "=", "signal_id", ",", "signal_type", "=", "signal_type", ",", "signal_value", "=", "signal_value", ",", "updated_at", "=", "datetime", ".", "now", "(", ")", ",", ")", "member_signal", ".", "write_to_table", "(", "self", ".", "_table", ")", "return", "member_signal" ]
https://github.com/facebook/ThreatExchange/blob/31914a51820c73c8a0daffe62ccca29a6e3d359e/hasher-matcher-actioner/hmalib/common/models/bank.py#L587-L622
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/distlib/database.py
python
InstalledDistribution.write_installed_files
(self, paths, prefix, dry_run=False)
return record_path
Writes the ``RECORD`` file, using the ``paths`` iterable passed in. Any existing ``RECORD`` file is silently overwritten. prefix is used to determine when to write absolute paths.
Writes the ``RECORD`` file, using the ``paths`` iterable passed in. Any existing ``RECORD`` file is silently overwritten.
[ "Writes", "the", "RECORD", "file", "using", "the", "paths", "iterable", "passed", "in", ".", "Any", "existing", "RECORD", "file", "is", "silently", "overwritten", "." ]
def write_installed_files(self, paths, prefix, dry_run=False): """ Writes the ``RECORD`` file, using the ``paths`` iterable passed in. Any existing ``RECORD`` file is silently overwritten. prefix is used to determine when to write absolute paths. """ prefix = os.path.join(prefix, '') base = os.path.dirname(self.path) base_under_prefix = base.startswith(prefix) base = os.path.join(base, '') record_path = self.get_distinfo_file('RECORD') logger.info('creating %s', record_path) if dry_run: return None with CSVWriter(record_path) as writer: for path in paths: if os.path.isdir(path) or path.endswith(('.pyc', '.pyo')): # do not put size and hash, as in PEP-376 hash_value = size = '' else: size = '%d' % os.path.getsize(path) with open(path, 'rb') as fp: hash_value = self.get_hash(fp.read()) if path.startswith(base) or (base_under_prefix and path.startswith(prefix)): path = os.path.relpath(path, base) writer.writerow((path, hash_value, size)) # add the RECORD file itself if record_path.startswith(base): record_path = os.path.relpath(record_path, base) writer.writerow((record_path, '', '')) return record_path
[ "def", "write_installed_files", "(", "self", ",", "paths", ",", "prefix", ",", "dry_run", "=", "False", ")", ":", "prefix", "=", "os", ".", "path", ".", "join", "(", "prefix", ",", "''", ")", "base", "=", "os", ".", "path", ".", "dirname", "(", "self", ".", "path", ")", "base_under_prefix", "=", "base", ".", "startswith", "(", "prefix", ")", "base", "=", "os", ".", "path", ".", "join", "(", "base", ",", "''", ")", "record_path", "=", "self", ".", "get_distinfo_file", "(", "'RECORD'", ")", "logger", ".", "info", "(", "'creating %s'", ",", "record_path", ")", "if", "dry_run", ":", "return", "None", "with", "CSVWriter", "(", "record_path", ")", "as", "writer", ":", "for", "path", "in", "paths", ":", "if", "os", ".", "path", ".", "isdir", "(", "path", ")", "or", "path", ".", "endswith", "(", "(", "'.pyc'", ",", "'.pyo'", ")", ")", ":", "# do not put size and hash, as in PEP-376", "hash_value", "=", "size", "=", "''", "else", ":", "size", "=", "'%d'", "%", "os", ".", "path", ".", "getsize", "(", "path", ")", "with", "open", "(", "path", ",", "'rb'", ")", "as", "fp", ":", "hash_value", "=", "self", ".", "get_hash", "(", "fp", ".", "read", "(", ")", ")", "if", "path", ".", "startswith", "(", "base", ")", "or", "(", "base_under_prefix", "and", "path", ".", "startswith", "(", "prefix", ")", ")", ":", "path", "=", "os", ".", "path", ".", "relpath", "(", "path", ",", "base", ")", "writer", ".", "writerow", "(", "(", "path", ",", "hash_value", ",", "size", ")", ")", "# add the RECORD file itself", "if", "record_path", ".", "startswith", "(", "base", ")", ":", "record_path", "=", "os", ".", "path", ".", "relpath", "(", "record_path", ",", "base", ")", "writer", ".", "writerow", "(", "(", "record_path", ",", "''", ",", "''", ")", ")", "return", "record_path" ]
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/distlib/database.py#L673-L706
BlzFans/wke
b0fa21158312e40c5fbd84682d643022b6c34a93
cygwin/lib/python2.6/urllib.py
python
proxy_bypass_environment
(host)
return 0
Test if proxies should not be used for a particular host. Checks the environment for a variable named no_proxy, which should be a list of DNS suffixes separated by commas, or '*' for all hosts.
Test if proxies should not be used for a particular host.
[ "Test", "if", "proxies", "should", "not", "be", "used", "for", "a", "particular", "host", "." ]
def proxy_bypass_environment(host): """Test if proxies should not be used for a particular host. Checks the environment for a variable named no_proxy, which should be a list of DNS suffixes separated by commas, or '*' for all hosts. """ no_proxy = os.environ.get('no_proxy', '') or os.environ.get('NO_PROXY', '') # '*' is special case for always bypass if no_proxy == '*': return 1 # strip port off host hostonly, port = splitport(host) # check if the host ends with any of the DNS suffixes for name in no_proxy.split(','): if name and (hostonly.endswith(name) or host.endswith(name)): return 1 # otherwise, don't bypass return 0
[ "def", "proxy_bypass_environment", "(", "host", ")", ":", "no_proxy", "=", "os", ".", "environ", ".", "get", "(", "'no_proxy'", ",", "''", ")", "or", "os", ".", "environ", ".", "get", "(", "'NO_PROXY'", ",", "''", ")", "# '*' is special case for always bypass", "if", "no_proxy", "==", "'*'", ":", "return", "1", "# strip port off host", "hostonly", ",", "port", "=", "splitport", "(", "host", ")", "# check if the host ends with any of the DNS suffixes", "for", "name", "in", "no_proxy", ".", "split", "(", "','", ")", ":", "if", "name", "and", "(", "hostonly", ".", "endswith", "(", "name", ")", "or", "host", ".", "endswith", "(", "name", ")", ")", ":", "return", "1", "# otherwise, don't bypass", "return", "0" ]
https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/urllib.py#L1312-L1329
emscripten-core/emscripten
0d413d3c5af8b28349682496edc14656f5700c2f
third_party/ply/example/ansic/cparse.py
python
p_expression_statement
(t)
expression_statement : expression_opt SEMI
expression_statement : expression_opt SEMI
[ "expression_statement", ":", "expression_opt", "SEMI" ]
def p_expression_statement(t): 'expression_statement : expression_opt SEMI' pass
[ "def", "p_expression_statement", "(", "t", ")", ":", "pass" ]
https://github.com/emscripten-core/emscripten/blob/0d413d3c5af8b28349682496edc14656f5700c2f/third_party/ply/example/ansic/cparse.py#L479-L481
BlzFans/wke
b0fa21158312e40c5fbd84682d643022b6c34a93
cygwin/lib/python2.6/distutils/command/install.py
python
install.create_home_path
(self)
Create directories under ~
Create directories under ~
[ "Create", "directories", "under", "~" ]
def create_home_path(self): """Create directories under ~ """ if not self.user: return home = convert_path(os.path.expanduser("~")) for name, path in self.config_vars.iteritems(): if path.startswith(home) and not os.path.isdir(path): self.debug_print("os.makedirs('%s', 0700)" % path) os.makedirs(path, 0700)
[ "def", "create_home_path", "(", "self", ")", ":", "if", "not", "self", ".", "user", ":", "return", "home", "=", "convert_path", "(", "os", ".", "path", ".", "expanduser", "(", "\"~\"", ")", ")", "for", "name", ",", "path", "in", "self", ".", "config_vars", ".", "iteritems", "(", ")", ":", "if", "path", ".", "startswith", "(", "home", ")", "and", "not", "os", ".", "path", ".", "isdir", "(", "path", ")", ":", "self", ".", "debug_print", "(", "\"os.makedirs('%s', 0700)\"", "%", "path", ")", "os", ".", "makedirs", "(", "path", ",", "0700", ")" ]
https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/distutils/command/install.py#L560-L569
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/x86/toolchain/lib/python2.7/idlelib/AutoComplete.py
python
AutoComplete.fetch_completions
(self, what, mode)
Return a pair of lists of completions for something. The first list is a sublist of the second. Both are sorted. If there is a Python subprocess, get the comp. list there. Otherwise, either fetch_completions() is running in the subprocess itself or it was called in an IDLE EditorWindow before any script had been run. The subprocess environment is that of the most recently run script. If two unrelated modules are being edited some calltips in the current module may be inoperative if the module was not the last to run.
Return a pair of lists of completions for something. The first list is a sublist of the second. Both are sorted.
[ "Return", "a", "pair", "of", "lists", "of", "completions", "for", "something", ".", "The", "first", "list", "is", "a", "sublist", "of", "the", "second", ".", "Both", "are", "sorted", "." ]
def fetch_completions(self, what, mode): """Return a pair of lists of completions for something. The first list is a sublist of the second. Both are sorted. If there is a Python subprocess, get the comp. list there. Otherwise, either fetch_completions() is running in the subprocess itself or it was called in an IDLE EditorWindow before any script had been run. The subprocess environment is that of the most recently run script. If two unrelated modules are being edited some calltips in the current module may be inoperative if the module was not the last to run. """ try: rpcclt = self.editwin.flist.pyshell.interp.rpcclt except: rpcclt = None if rpcclt: return rpcclt.remotecall("exec", "get_the_completion_list", (what, mode), {}) else: if mode == COMPLETE_ATTRIBUTES: if what == "": namespace = __main__.__dict__.copy() namespace.update(__main__.__builtins__.__dict__) bigl = eval("dir()", namespace) bigl.sort() if "__all__" in bigl: smalll = sorted(eval("__all__", namespace)) else: smalll = [s for s in bigl if s[:1] != '_'] else: try: entity = self.get_entity(what) bigl = dir(entity) bigl.sort() if "__all__" in bigl: smalll = sorted(entity.__all__) else: smalll = [s for s in bigl if s[:1] != '_'] except: return [], [] elif mode == COMPLETE_FILES: if what == "": what = "." try: expandedpath = os.path.expanduser(what) bigl = os.listdir(expandedpath) bigl.sort() smalll = [s for s in bigl if s[:1] != '.'] except OSError: return [], [] if not smalll: smalll = bigl return smalll, bigl
[ "def", "fetch_completions", "(", "self", ",", "what", ",", "mode", ")", ":", "try", ":", "rpcclt", "=", "self", ".", "editwin", ".", "flist", ".", "pyshell", ".", "interp", ".", "rpcclt", "except", ":", "rpcclt", "=", "None", "if", "rpcclt", ":", "return", "rpcclt", ".", "remotecall", "(", "\"exec\"", ",", "\"get_the_completion_list\"", ",", "(", "what", ",", "mode", ")", ",", "{", "}", ")", "else", ":", "if", "mode", "==", "COMPLETE_ATTRIBUTES", ":", "if", "what", "==", "\"\"", ":", "namespace", "=", "__main__", ".", "__dict__", ".", "copy", "(", ")", "namespace", ".", "update", "(", "__main__", ".", "__builtins__", ".", "__dict__", ")", "bigl", "=", "eval", "(", "\"dir()\"", ",", "namespace", ")", "bigl", ".", "sort", "(", ")", "if", "\"__all__\"", "in", "bigl", ":", "smalll", "=", "sorted", "(", "eval", "(", "\"__all__\"", ",", "namespace", ")", ")", "else", ":", "smalll", "=", "[", "s", "for", "s", "in", "bigl", "if", "s", "[", ":", "1", "]", "!=", "'_'", "]", "else", ":", "try", ":", "entity", "=", "self", ".", "get_entity", "(", "what", ")", "bigl", "=", "dir", "(", "entity", ")", "bigl", ".", "sort", "(", ")", "if", "\"__all__\"", "in", "bigl", ":", "smalll", "=", "sorted", "(", "entity", ".", "__all__", ")", "else", ":", "smalll", "=", "[", "s", "for", "s", "in", "bigl", "if", "s", "[", ":", "1", "]", "!=", "'_'", "]", "except", ":", "return", "[", "]", ",", "[", "]", "elif", "mode", "==", "COMPLETE_FILES", ":", "if", "what", "==", "\"\"", ":", "what", "=", "\".\"", "try", ":", "expandedpath", "=", "os", ".", "path", ".", "expanduser", "(", "what", ")", "bigl", "=", "os", ".", "listdir", "(", "expandedpath", ")", "bigl", ".", "sort", "(", ")", "smalll", "=", "[", "s", "for", "s", "in", "bigl", "if", "s", "[", ":", "1", "]", "!=", "'.'", "]", "except", "OSError", ":", "return", "[", "]", ",", "[", "]", "if", "not", "smalll", ":", "smalll", "=", "bigl", "return", "smalll", ",", "bigl" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/idlelib/AutoComplete.py#L166-L221
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/contrib/layers/python/layers/feature_column.py
python
_BucketizedColumn.to_sparse_tensor
(self, input_tensor)
return sparse_id_values
Creates a SparseTensor from the bucketized Tensor.
Creates a SparseTensor from the bucketized Tensor.
[ "Creates", "a", "SparseTensor", "from", "the", "bucketized", "Tensor", "." ]
def to_sparse_tensor(self, input_tensor): """Creates a SparseTensor from the bucketized Tensor.""" dimension = self.source_column.dimension batch_size = array_ops.shape(input_tensor, name="shape")[0] if dimension > 1: i1 = array_ops.reshape( array_ops.tile( array_ops.expand_dims( math_ops.range(0, batch_size), 1, name="expand_dims"), [1, dimension], name="tile"), [-1], name="reshape") i2 = array_ops.tile( math_ops.range(0, dimension), [batch_size], name="tile") # Flatten the bucket indices and unique them across dimensions # E.g. 2nd dimension indices will range from k to 2*k-1 with k buckets bucket_indices = array_ops.reshape( input_tensor, [-1], name="reshape") + self.length * i2 else: # Simpler indices when dimension=1 i1 = math_ops.range(0, batch_size) i2 = array_ops.zeros([batch_size], dtype=dtypes.int32, name="zeros") bucket_indices = array_ops.reshape(input_tensor, [-1], name="reshape") indices = math_ops.to_int64(array_ops.transpose(array_ops.stack((i1, i2)))) shape = math_ops.to_int64(array_ops.stack([batch_size, dimension])) sparse_id_values = sparse_tensor_py.SparseTensor( indices, bucket_indices, shape) return sparse_id_values
[ "def", "to_sparse_tensor", "(", "self", ",", "input_tensor", ")", ":", "dimension", "=", "self", ".", "source_column", ".", "dimension", "batch_size", "=", "array_ops", ".", "shape", "(", "input_tensor", ",", "name", "=", "\"shape\"", ")", "[", "0", "]", "if", "dimension", ">", "1", ":", "i1", "=", "array_ops", ".", "reshape", "(", "array_ops", ".", "tile", "(", "array_ops", ".", "expand_dims", "(", "math_ops", ".", "range", "(", "0", ",", "batch_size", ")", ",", "1", ",", "name", "=", "\"expand_dims\"", ")", ",", "[", "1", ",", "dimension", "]", ",", "name", "=", "\"tile\"", ")", ",", "[", "-", "1", "]", ",", "name", "=", "\"reshape\"", ")", "i2", "=", "array_ops", ".", "tile", "(", "math_ops", ".", "range", "(", "0", ",", "dimension", ")", ",", "[", "batch_size", "]", ",", "name", "=", "\"tile\"", ")", "# Flatten the bucket indices and unique them across dimensions", "# E.g. 2nd dimension indices will range from k to 2*k-1 with k buckets", "bucket_indices", "=", "array_ops", ".", "reshape", "(", "input_tensor", ",", "[", "-", "1", "]", ",", "name", "=", "\"reshape\"", ")", "+", "self", ".", "length", "*", "i2", "else", ":", "# Simpler indices when dimension=1", "i1", "=", "math_ops", ".", "range", "(", "0", ",", "batch_size", ")", "i2", "=", "array_ops", ".", "zeros", "(", "[", "batch_size", "]", ",", "dtype", "=", "dtypes", ".", "int32", ",", "name", "=", "\"zeros\"", ")", "bucket_indices", "=", "array_ops", ".", "reshape", "(", "input_tensor", ",", "[", "-", "1", "]", ",", "name", "=", "\"reshape\"", ")", "indices", "=", "math_ops", ".", "to_int64", "(", "array_ops", ".", "transpose", "(", "array_ops", ".", "stack", "(", "(", "i1", ",", "i2", ")", ")", ")", ")", "shape", "=", "math_ops", ".", "to_int64", "(", "array_ops", ".", "stack", "(", "[", "batch_size", ",", "dimension", "]", ")", ")", "sparse_id_values", "=", "sparse_tensor_py", ".", "SparseTensor", "(", "indices", ",", "bucket_indices", ",", "shape", ")", "return", "sparse_id_values" ]
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/contrib/layers/python/layers/feature_column.py#L2057-L2087
klzgrad/naiveproxy
ed2c513637c77b18721fe428d7ed395b4d284c83
src/tools/grit/grit/format/data_pack.py
python
RePack
(output_file, input_files, allowlist_file=None, suppress_removed_key_output=False, output_info_filepath=None)
Write a new data pack file by combining input pack files. Args: output_file: path to the new data pack file. input_files: a list of paths to the data pack files to combine. allowlist_file: path to the file that contains the list of resource IDs that should be kept in the output file or None to include all resources. suppress_removed_key_output: allows the caller to suppress the output from RePackFromDataPackStrings. output_info_file: If not None, specify the output .info filepath. Raises: KeyError: if there are duplicate keys or resource encoding is inconsistent.
Write a new data pack file by combining input pack files.
[ "Write", "a", "new", "data", "pack", "file", "by", "combining", "input", "pack", "files", "." ]
def RePack(output_file, input_files, allowlist_file=None, suppress_removed_key_output=False, output_info_filepath=None): """Write a new data pack file by combining input pack files. Args: output_file: path to the new data pack file. input_files: a list of paths to the data pack files to combine. allowlist_file: path to the file that contains the list of resource IDs that should be kept in the output file or None to include all resources. suppress_removed_key_output: allows the caller to suppress the output from RePackFromDataPackStrings. output_info_file: If not None, specify the output .info filepath. Raises: KeyError: if there are duplicate keys or resource encoding is inconsistent. """ input_data_packs = [ReadDataPack(filename) for filename in input_files] input_info_files = [filename + '.info' for filename in input_files] allowlist = None if allowlist_file: lines = util.ReadFile(allowlist_file, 'utf-8').strip().splitlines() if not lines: raise Exception('Allowlist file should not be empty') allowlist = set(int(x) for x in lines) inputs = [(p.resources, p.encoding) for p in input_data_packs] resources, encoding = RePackFromDataPackStrings(inputs, allowlist, suppress_removed_key_output) WriteDataPack(resources, output_file, encoding) if output_info_filepath is None: output_info_filepath = output_file + '.info' with open(output_info_filepath, 'w') as output_info_file: for filename in input_info_files: with open(filename, 'r') as info_file: output_info_file.writelines(info_file.readlines())
[ "def", "RePack", "(", "output_file", ",", "input_files", ",", "allowlist_file", "=", "None", ",", "suppress_removed_key_output", "=", "False", ",", "output_info_filepath", "=", "None", ")", ":", "input_data_packs", "=", "[", "ReadDataPack", "(", "filename", ")", "for", "filename", "in", "input_files", "]", "input_info_files", "=", "[", "filename", "+", "'.info'", "for", "filename", "in", "input_files", "]", "allowlist", "=", "None", "if", "allowlist_file", ":", "lines", "=", "util", ".", "ReadFile", "(", "allowlist_file", ",", "'utf-8'", ")", ".", "strip", "(", ")", ".", "splitlines", "(", ")", "if", "not", "lines", ":", "raise", "Exception", "(", "'Allowlist file should not be empty'", ")", "allowlist", "=", "set", "(", "int", "(", "x", ")", "for", "x", "in", "lines", ")", "inputs", "=", "[", "(", "p", ".", "resources", ",", "p", ".", "encoding", ")", "for", "p", "in", "input_data_packs", "]", "resources", ",", "encoding", "=", "RePackFromDataPackStrings", "(", "inputs", ",", "allowlist", ",", "suppress_removed_key_output", ")", "WriteDataPack", "(", "resources", ",", "output_file", ",", "encoding", ")", "if", "output_info_filepath", "is", "None", ":", "output_info_filepath", "=", "output_file", "+", "'.info'", "with", "open", "(", "output_info_filepath", ",", "'w'", ")", "as", "output_info_file", ":", "for", "filename", "in", "input_info_files", ":", "with", "open", "(", "filename", ",", "'r'", ")", "as", "info_file", ":", "output_info_file", ".", "writelines", "(", "info_file", ".", "readlines", "(", ")", ")" ]
https://github.com/klzgrad/naiveproxy/blob/ed2c513637c77b18721fe428d7ed395b4d284c83/src/tools/grit/grit/format/data_pack.py#L221-L259
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/parso/py2/parso/python/tree.py
python
ImportFrom.get_paths
(self)
return [dotted + [name] for name, alias in self._as_name_tuples()]
The import paths defined in an import statement. Typically an array like this: ``[<Name: datetime>, <Name: date>]``. :return list of list of Name:
The import paths defined in an import statement. Typically an array like this: ``[<Name: datetime>, <Name: date>]``.
[ "The", "import", "paths", "defined", "in", "an", "import", "statement", ".", "Typically", "an", "array", "like", "this", ":", "[", "<Name", ":", "datetime", ">", "<Name", ":", "date", ">", "]", "." ]
def get_paths(self): """ The import paths defined in an import statement. Typically an array like this: ``[<Name: datetime>, <Name: date>]``. :return list of list of Name: """ dotted = self.get_from_names() if self.children[-1] == '*': return [dotted] return [dotted + [name] for name, alias in self._as_name_tuples()]
[ "def", "get_paths", "(", "self", ")", ":", "dotted", "=", "self", ".", "get_from_names", "(", ")", "if", "self", ".", "children", "[", "-", "1", "]", "==", "'*'", ":", "return", "[", "dotted", "]", "return", "[", "dotted", "+", "[", "name", "]", "for", "name", ",", "alias", "in", "self", ".", "_as_name_tuples", "(", ")", "]" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/parso/py2/parso/python/tree.py#L907-L918
sigmaai/self-driving-golf-cart
8d891600af3d851add27a10ae45cf3c2108bb87c
ros/src/ros_carla_bridge/carla_ros_bridge/src/carla_ros_bridge/bridge.py
python
CarlaRosBridge.run
(self)
Run the bridge functionality. Registers on shutdown callback at rospy and spins ROS. :return:
Run the bridge functionality.
[ "Run", "the", "bridge", "functionality", "." ]
def run(self): """ Run the bridge functionality. Registers on shutdown callback at rospy and spins ROS. :return: """ rospy.on_shutdown(self.on_shutdown) rospy.spin()
[ "def", "run", "(", "self", ")", ":", "rospy", ".", "on_shutdown", "(", "self", ".", "on_shutdown", ")", "rospy", ".", "spin", "(", ")" ]
https://github.com/sigmaai/self-driving-golf-cart/blob/8d891600af3d851add27a10ae45cf3c2108bb87c/ros/src/ros_carla_bridge/carla_ros_bridge/src/carla_ros_bridge/bridge.py#L418-L427
facebookincubator/BOLT
88c70afe9d388ad430cc150cc158641701397f70
openmp/runtime/tools/summarizeStats.py
python
setRadarFigure
(titles)
return {'ax':ax, 'theta':theta}
Set the attributes for the radar plots
Set the attributes for the radar plots
[ "Set", "the", "attributes", "for", "the", "radar", "plots" ]
def setRadarFigure(titles): """Set the attributes for the radar plots""" fig = plt.figure(figsize=(9,9)) rect = [0.1, 0.1, 0.8, 0.8] labels = [0.2, 0.4, 0.6, 0.8, 1, 2, 3, 4, 5, 10] matplotlib.rcParams.update({'font.size':13}) theta = radar_factory(len(titles)) ax = fig.add_axes(rect, projection='radar') ax.set_rgrids(labels) ax.set_varlabels(titles) ax.text(theta[2], 1, "Linear->Log", horizontalalignment='center', color='green', fontsize=18) return {'ax':ax, 'theta':theta}
[ "def", "setRadarFigure", "(", "titles", ")", ":", "fig", "=", "plt", ".", "figure", "(", "figsize", "=", "(", "9", ",", "9", ")", ")", "rect", "=", "[", "0.1", ",", "0.1", ",", "0.8", ",", "0.8", "]", "labels", "=", "[", "0.2", ",", "0.4", ",", "0.6", ",", "0.8", ",", "1", ",", "2", ",", "3", ",", "4", ",", "5", ",", "10", "]", "matplotlib", ".", "rcParams", ".", "update", "(", "{", "'font.size'", ":", "13", "}", ")", "theta", "=", "radar_factory", "(", "len", "(", "titles", ")", ")", "ax", "=", "fig", ".", "add_axes", "(", "rect", ",", "projection", "=", "'radar'", ")", "ax", ".", "set_rgrids", "(", "labels", ")", "ax", ".", "set_varlabels", "(", "titles", ")", "ax", ".", "text", "(", "theta", "[", "2", "]", ",", "1", ",", "\"Linear->Log\"", ",", "horizontalalignment", "=", "'center'", ",", "color", "=", "'green'", ",", "fontsize", "=", "18", ")", "return", "{", "'ax'", ":", "ax", ",", "'theta'", ":", "theta", "}" ]
https://github.com/facebookincubator/BOLT/blob/88c70afe9d388ad430cc150cc158641701397f70/openmp/runtime/tools/summarizeStats.py#L177-L188
GoSSIP-SJTU/TripleDoggy
03648d6b19c812504b14e8b98c8c7b3f443f4e54
tools/clang/bindings/python/clang/cindex.py
python
Cursor.is_const_method
(self)
return conf.lib.clang_CXXMethod_isConst(self)
Returns True if the cursor refers to a C++ member function or member function template that is declared 'const'.
Returns True if the cursor refers to a C++ member function or member function template that is declared 'const'.
[ "Returns", "True", "if", "the", "cursor", "refers", "to", "a", "C", "++", "member", "function", "or", "member", "function", "template", "that", "is", "declared", "const", "." ]
def is_const_method(self): """Returns True if the cursor refers to a C++ member function or member function template that is declared 'const'. """ return conf.lib.clang_CXXMethod_isConst(self)
[ "def", "is_const_method", "(", "self", ")", ":", "return", "conf", ".", "lib", ".", "clang_CXXMethod_isConst", "(", "self", ")" ]
https://github.com/GoSSIP-SJTU/TripleDoggy/blob/03648d6b19c812504b14e8b98c8c7b3f443f4e54/tools/clang/bindings/python/clang/cindex.py#L1426-L1430
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scikit-learn/py3/sklearn/cluster/_agglomerative.py
python
_single_linkage_tree
(connectivity, n_samples, n_nodes, n_clusters, n_connected_components, return_distance)
return children_, n_connected_components, n_samples, parent
Perform single linkage clustering on sparse data via the minimum spanning tree from scipy.sparse.csgraph, then using union-find to label. The parent array is then generated by walking through the tree.
Perform single linkage clustering on sparse data via the minimum spanning tree from scipy.sparse.csgraph, then using union-find to label. The parent array is then generated by walking through the tree.
[ "Perform", "single", "linkage", "clustering", "on", "sparse", "data", "via", "the", "minimum", "spanning", "tree", "from", "scipy", ".", "sparse", ".", "csgraph", "then", "using", "union", "-", "find", "to", "label", ".", "The", "parent", "array", "is", "then", "generated", "by", "walking", "through", "the", "tree", "." ]
def _single_linkage_tree(connectivity, n_samples, n_nodes, n_clusters, n_connected_components, return_distance): """ Perform single linkage clustering on sparse data via the minimum spanning tree from scipy.sparse.csgraph, then using union-find to label. The parent array is then generated by walking through the tree. """ from scipy.sparse.csgraph import minimum_spanning_tree # explicitly cast connectivity to ensure safety connectivity = connectivity.astype('float64', **_astype_copy_false(connectivity)) # Ensure zero distances aren't ignored by setting them to "epsilon" epsilon_value = np.finfo(dtype=connectivity.data.dtype).eps connectivity.data[connectivity.data == 0] = epsilon_value # Use scipy.sparse.csgraph to generate a minimum spanning tree mst = minimum_spanning_tree(connectivity.tocsr()) # Convert the graph to scipy.cluster.hierarchy array format mst = mst.tocoo() # Undo the epsilon values mst.data[mst.data == epsilon_value] = 0 mst_array = np.vstack([mst.row, mst.col, mst.data]).T # Sort edges of the min_spanning_tree by weight mst_array = mst_array[np.argsort(mst_array.T[2]), :] # Convert edge list into standard hierarchical clustering format single_linkage_tree = _hierarchical._single_linkage_label(mst_array) children_ = single_linkage_tree[:, :2].astype(np.int) # Compute parents parent = np.arange(n_nodes, dtype=np.intp) for i, (left, right) in enumerate(children_, n_samples): if n_clusters is not None and i >= n_nodes: break if left < n_nodes: parent[left] = i if right < n_nodes: parent[right] = i if return_distance: distances = single_linkage_tree[:, 2] return children_, n_connected_components, n_samples, parent, distances return children_, n_connected_components, n_samples, parent
[ "def", "_single_linkage_tree", "(", "connectivity", ",", "n_samples", ",", "n_nodes", ",", "n_clusters", ",", "n_connected_components", ",", "return_distance", ")", ":", "from", "scipy", ".", "sparse", ".", "csgraph", "import", "minimum_spanning_tree", "# explicitly cast connectivity to ensure safety", "connectivity", "=", "connectivity", ".", "astype", "(", "'float64'", ",", "*", "*", "_astype_copy_false", "(", "connectivity", ")", ")", "# Ensure zero distances aren't ignored by setting them to \"epsilon\"", "epsilon_value", "=", "np", ".", "finfo", "(", "dtype", "=", "connectivity", ".", "data", ".", "dtype", ")", ".", "eps", "connectivity", ".", "data", "[", "connectivity", ".", "data", "==", "0", "]", "=", "epsilon_value", "# Use scipy.sparse.csgraph to generate a minimum spanning tree", "mst", "=", "minimum_spanning_tree", "(", "connectivity", ".", "tocsr", "(", ")", ")", "# Convert the graph to scipy.cluster.hierarchy array format", "mst", "=", "mst", ".", "tocoo", "(", ")", "# Undo the epsilon values", "mst", ".", "data", "[", "mst", ".", "data", "==", "epsilon_value", "]", "=", "0", "mst_array", "=", "np", ".", "vstack", "(", "[", "mst", ".", "row", ",", "mst", ".", "col", ",", "mst", ".", "data", "]", ")", ".", "T", "# Sort edges of the min_spanning_tree by weight", "mst_array", "=", "mst_array", "[", "np", ".", "argsort", "(", "mst_array", ".", "T", "[", "2", "]", ")", ",", ":", "]", "# Convert edge list into standard hierarchical clustering format", "single_linkage_tree", "=", "_hierarchical", ".", "_single_linkage_label", "(", "mst_array", ")", "children_", "=", "single_linkage_tree", "[", ":", ",", ":", "2", "]", ".", "astype", "(", "np", ".", "int", ")", "# Compute parents", "parent", "=", "np", ".", "arange", "(", "n_nodes", ",", "dtype", "=", "np", ".", "intp", ")", "for", "i", ",", "(", "left", ",", "right", ")", "in", "enumerate", "(", "children_", ",", "n_samples", ")", ":", "if", "n_clusters", "is", "not", "None", "and", "i", ">=", "n_nodes", ":", "break", "if", "left", "<", "n_nodes", ":", "parent", "[", "left", "]", "=", "i", "if", "right", "<", "n_nodes", ":", "parent", "[", "right", "]", "=", "i", "if", "return_distance", ":", "distances", "=", "single_linkage_tree", "[", ":", ",", "2", "]", "return", "children_", ",", "n_connected_components", ",", "n_samples", ",", "parent", ",", "distances", "return", "children_", ",", "n_connected_components", ",", "n_samples", ",", "parent" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py3/sklearn/cluster/_agglomerative.py#L82-L130
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/generic.py
python
NDFrame._constructor_sliced
(self)
Used when a manipulation result has one lower dimension(s) as the original, such as DataFrame single columns slicing.
Used when a manipulation result has one lower dimension(s) as the original, such as DataFrame single columns slicing.
[ "Used", "when", "a", "manipulation", "result", "has", "one", "lower", "dimension", "(", "s", ")", "as", "the", "original", "such", "as", "DataFrame", "single", "columns", "slicing", "." ]
def _constructor_sliced(self): """Used when a manipulation result has one lower dimension(s) as the original, such as DataFrame single columns slicing. """ raise AbstractMethodError(self)
[ "def", "_constructor_sliced", "(", "self", ")", ":", "raise", "AbstractMethodError", "(", "self", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/generic.py#L281-L285
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/tkinter/__init__.py
python
Misc.pack_slaves
(self)
return [self._nametowidget(x) for x in self.tk.splitlist( self.tk.call('pack', 'slaves', self._w))]
Return a list of all slaves of this widget in its packing order.
Return a list of all slaves of this widget in its packing order.
[ "Return", "a", "list", "of", "all", "slaves", "of", "this", "widget", "in", "its", "packing", "order", "." ]
def pack_slaves(self): """Return a list of all slaves of this widget in its packing order.""" return [self._nametowidget(x) for x in self.tk.splitlist( self.tk.call('pack', 'slaves', self._w))]
[ "def", "pack_slaves", "(", "self", ")", ":", "return", "[", "self", ".", "_nametowidget", "(", "x", ")", "for", "x", "in", "self", ".", "tk", ".", "splitlist", "(", "self", ".", "tk", ".", "call", "(", "'pack'", ",", "'slaves'", ",", "self", ".", "_w", ")", ")", "]" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/tkinter/__init__.py#L1521-L1526
miyosuda/TensorFlowAndroidDemo
35903e0221aa5f109ea2dbef27f20b52e317f42d
jni-build/jni/include/tensorflow/contrib/layers/python/layers/feature_column.py
python
sparse_column_with_integerized_feature
(column_name, bucket_size, combiner="sum", dtype=dtypes.int64)
return _SparseColumnIntegerized(column_name, bucket_size, combiner=combiner, dtype=dtype)
Creates an integerized _SparseColumn. Use this when your features are already pre-integerized into int64 IDs. output_id = input_feature Args: column_name: A string defining sparse column name. bucket_size: An int that is > 1. The number of buckets. It should be bigger than maximum feature. In other words features in this column should be an int64 in range [0, bucket_size) combiner: A string specifying how to reduce if the sparse column is multivalent. Currently "mean", "sqrtn" and "sum" are supported, with "sum" the default: * "sum": do not normalize features in the column * "mean": do l1 normalization on features in the column * "sqrtn": do l2 normalization on features in the column For more information: `tf.embedding_lookup_sparse`. dtype: Type of features. It should be an integer type. Default value is dtypes.int64. Returns: An integerized _SparseColumn definition. Raises: ValueError: bucket_size is not greater than 1. ValueError: dtype is not integer.
Creates an integerized _SparseColumn.
[ "Creates", "an", "integerized", "_SparseColumn", "." ]
def sparse_column_with_integerized_feature(column_name, bucket_size, combiner="sum", dtype=dtypes.int64): """Creates an integerized _SparseColumn. Use this when your features are already pre-integerized into int64 IDs. output_id = input_feature Args: column_name: A string defining sparse column name. bucket_size: An int that is > 1. The number of buckets. It should be bigger than maximum feature. In other words features in this column should be an int64 in range [0, bucket_size) combiner: A string specifying how to reduce if the sparse column is multivalent. Currently "mean", "sqrtn" and "sum" are supported, with "sum" the default: * "sum": do not normalize features in the column * "mean": do l1 normalization on features in the column * "sqrtn": do l2 normalization on features in the column For more information: `tf.embedding_lookup_sparse`. dtype: Type of features. It should be an integer type. Default value is dtypes.int64. Returns: An integerized _SparseColumn definition. Raises: ValueError: bucket_size is not greater than 1. ValueError: dtype is not integer. """ return _SparseColumnIntegerized(column_name, bucket_size, combiner=combiner, dtype=dtype)
[ "def", "sparse_column_with_integerized_feature", "(", "column_name", ",", "bucket_size", ",", "combiner", "=", "\"sum\"", ",", "dtype", "=", "dtypes", ".", "int64", ")", ":", "return", "_SparseColumnIntegerized", "(", "column_name", ",", "bucket_size", ",", "combiner", "=", "combiner", ",", "dtype", "=", "dtype", ")" ]
https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/contrib/layers/python/layers/feature_column.py#L314-L348
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/keras/engine/training_v2.py
python
_process_inputs
(model, x, y, batch_size=None, epochs=1, sample_weights=None, class_weights=None, shuffle=False, steps=None, distribution_strategy=None, max_queue_size=10, workers=1, use_multiprocessing=False)
return adapter
Process the inputs for fit/eval/predict().
Process the inputs for fit/eval/predict().
[ "Process", "the", "inputs", "for", "fit", "/", "eval", "/", "predict", "()", "." ]
def _process_inputs(model, x, y, batch_size=None, epochs=1, sample_weights=None, class_weights=None, shuffle=False, steps=None, distribution_strategy=None, max_queue_size=10, workers=1, use_multiprocessing=False): """Process the inputs for fit/eval/predict().""" adapter_cls = data_adapter.select_data_adapter(x, y) if adapter_cls in _ADAPTER_FOR_STANDARDIZE_USER_DATA: x, y, sample_weights = model._standardize_user_data( x, y, sample_weight=sample_weights, class_weight=class_weights, batch_size=batch_size, check_steps=False, steps=steps) adapter = adapter_cls( x, y, batch_size=batch_size, epochs=epochs, steps=steps, sample_weights=sample_weights, shuffle=shuffle, distribution_strategy=distribution_strategy, max_queue_size=max_queue_size, workers=workers, use_multiprocessing=use_multiprocessing) # As a fallback for the data type that does not work with # _standardize_user_data, use the _prepare_model_with_inputs. if adapter_cls not in _ADAPTER_FOR_STANDARDIZE_USER_DATA: training_v2_utils._prepare_model_with_inputs(model, adapter.get_dataset()) return adapter
[ "def", "_process_inputs", "(", "model", ",", "x", ",", "y", ",", "batch_size", "=", "None", ",", "epochs", "=", "1", ",", "sample_weights", "=", "None", ",", "class_weights", "=", "None", ",", "shuffle", "=", "False", ",", "steps", "=", "None", ",", "distribution_strategy", "=", "None", ",", "max_queue_size", "=", "10", ",", "workers", "=", "1", ",", "use_multiprocessing", "=", "False", ")", ":", "adapter_cls", "=", "data_adapter", ".", "select_data_adapter", "(", "x", ",", "y", ")", "if", "adapter_cls", "in", "_ADAPTER_FOR_STANDARDIZE_USER_DATA", ":", "x", ",", "y", ",", "sample_weights", "=", "model", ".", "_standardize_user_data", "(", "x", ",", "y", ",", "sample_weight", "=", "sample_weights", ",", "class_weight", "=", "class_weights", ",", "batch_size", "=", "batch_size", ",", "check_steps", "=", "False", ",", "steps", "=", "steps", ")", "adapter", "=", "adapter_cls", "(", "x", ",", "y", ",", "batch_size", "=", "batch_size", ",", "epochs", "=", "epochs", ",", "steps", "=", "steps", ",", "sample_weights", "=", "sample_weights", ",", "shuffle", "=", "shuffle", ",", "distribution_strategy", "=", "distribution_strategy", ",", "max_queue_size", "=", "max_queue_size", ",", "workers", "=", "workers", ",", "use_multiprocessing", "=", "use_multiprocessing", ")", "# As a fallback for the data type that does not work with", "# _standardize_user_data, use the _prepare_model_with_inputs.", "if", "adapter_cls", "not", "in", "_ADAPTER_FOR_STANDARDIZE_USER_DATA", ":", "training_v2_utils", ".", "_prepare_model_with_inputs", "(", "model", ",", "adapter", ".", "get_dataset", "(", ")", ")", "return", "adapter" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/keras/engine/training_v2.py#L585-L625
apiaryio/snowcrash
b5b39faa85f88ee17459edf39fdc6fe4fc70d2e3
tools/gyp/buildbot/buildbot_run.py
python
CallSubProcess
(*args, **kwargs)
Wrapper around subprocess.call which treats errors as build exceptions.
Wrapper around subprocess.call which treats errors as build exceptions.
[ "Wrapper", "around", "subprocess", ".", "call", "which", "treats", "errors", "as", "build", "exceptions", "." ]
def CallSubProcess(*args, **kwargs): """Wrapper around subprocess.call which treats errors as build exceptions.""" with open(os.devnull) as devnull_fd: retcode = subprocess.call(stdin=devnull_fd, *args, **kwargs) if retcode != 0: print '@@@STEP_EXCEPTION@@@' sys.exit(1)
[ "def", "CallSubProcess", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "with", "open", "(", "os", ".", "devnull", ")", "as", "devnull_fd", ":", "retcode", "=", "subprocess", ".", "call", "(", "stdin", "=", "devnull_fd", ",", "*", "args", ",", "*", "*", "kwargs", ")", "if", "retcode", "!=", "0", ":", "print", "'@@@STEP_EXCEPTION@@@'", "sys", ".", "exit", "(", "1", ")" ]
https://github.com/apiaryio/snowcrash/blob/b5b39faa85f88ee17459edf39fdc6fe4fc70d2e3/tools/gyp/buildbot/buildbot_run.py#L22-L28
ApolloAuto/apollo-platform
86d9dc6743b496ead18d597748ebabd34a513289
ros/ros_comm/rosgraph/src/rosgraph/masterapi.py
python
Master.getPid
(self)
return self._succeed(self.handle.getPid(self.caller_id))
Get the PID of this server @return: serverProcessPID @rtype: int @raise rosgraph.masterapi.Error: if Master returns ERROR. @raise rosgraph.masterapi.Failure: if Master returns FAILURE.
Get the PID of this server
[ "Get", "the", "PID", "of", "this", "server" ]
def getPid(self): """ Get the PID of this server @return: serverProcessPID @rtype: int @raise rosgraph.masterapi.Error: if Master returns ERROR. @raise rosgraph.masterapi.Failure: if Master returns FAILURE. """ return self._succeed(self.handle.getPid(self.caller_id))
[ "def", "getPid", "(", "self", ")", ":", "return", "self", ".", "_succeed", "(", "self", ".", "handle", ".", "getPid", "(", "self", ".", "caller_id", ")", ")" ]
https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/ros_comm/rosgraph/src/rosgraph/masterapi.py#L288-L296
johmathe/shotdetect
1ecf93a695c96fd7601a41ab5834f1117b9d7d50
tools/cpplint.py
python
_CppLintState.SetVerboseLevel
(self, level)
return last_verbose_level
Sets the module's verbosity, and returns the previous setting.
Sets the module's verbosity, and returns the previous setting.
[ "Sets", "the", "module", "s", "verbosity", "and", "returns", "the", "previous", "setting", "." ]
def SetVerboseLevel(self, level): """Sets the module's verbosity, and returns the previous setting.""" last_verbose_level = self.verbose_level self.verbose_level = level return last_verbose_level
[ "def", "SetVerboseLevel", "(", "self", ",", "level", ")", ":", "last_verbose_level", "=", "self", ".", "verbose_level", "self", ".", "verbose_level", "=", "level", "return", "last_verbose_level" ]
https://github.com/johmathe/shotdetect/blob/1ecf93a695c96fd7601a41ab5834f1117b9d7d50/tools/cpplint.py#L511-L515
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/stc.py
python
StyledTextCtrl.GetTag
(*args, **kwargs)
return _stc.StyledTextCtrl_GetTag(*args, **kwargs)
GetTag(self, int tagNumber) -> String
GetTag(self, int tagNumber) -> String
[ "GetTag", "(", "self", "int", "tagNumber", ")", "-", ">", "String" ]
def GetTag(*args, **kwargs): """GetTag(self, int tagNumber) -> String""" return _stc.StyledTextCtrl_GetTag(*args, **kwargs)
[ "def", "GetTag", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_stc", ".", "StyledTextCtrl_GetTag", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/stc.py#L4285-L4287
SFTtech/openage
d6a08c53c48dc1e157807471df92197f6ca9e04d
openage/nyan/import_tree.py
python
ImportTree.expand_from_object
(self, nyan_object)
Expands the tree from a nyan object. :param nyan_object: A nyan object. :type nyan_object: .nyan_structs.NyanObject
Expands the tree from a nyan object.
[ "Expands", "the", "tree", "from", "a", "nyan", "object", "." ]
def expand_from_object(self, nyan_object): """ Expands the tree from a nyan object. :param nyan_object: A nyan object. :type nyan_object: .nyan_structs.NyanObject """ # Process the object fqon = nyan_object.get_fqon() if fqon[0] != "engine": current_node = self.root node_type = NodeType.OBJECT for node_str in fqon: if current_node.has_child(node_str): # Choose the already created node current_node = current_node.get_child(node_str) else: # Add a new node new_node = Node(node_str, node_type, current_node) current_node.add_child(new_node) current_node = new_node else: # Workaround for API objects because they are not loaded # from files currently. # TODO: Remove workaround when API is loaded from files. current_node = self.root index = 0 while index < len(fqon): node_str = fqon[index] if current_node.has_child(node_str): # Choose the already created node current_node = current_node.get_child(node_str) else: # Add a new node if node_str[0].islower(): # By convention, directory and file names are lower case # We can check for that to determine the node type. node_type = NodeType.FILESYS else: node_type = NodeType.OBJECT new_node = Node(node_str, node_type, current_node) current_node.add_child(new_node) current_node = new_node index += 1 # Recursively search the nyan objects for nested objects unsearched_objects = [] unsearched_objects.extend(nyan_object.get_nested_objects()) found_nested_objects = [] while len(unsearched_objects) > 0: current_nested_object = unsearched_objects[0] unsearched_objects.extend(current_nested_object.get_nested_objects()) found_nested_objects.append(current_nested_object) unsearched_objects.remove(current_nested_object) # Process fqons of the nested objects for nested_object in found_nested_objects: current_node = self.root node_type = NodeType.NESTED fqon = nested_object.get_fqon() for node_str in fqon: if current_node.has_child(node_str): # Choose the already created node current_node = current_node.get_child(node_str) else: # Add a new node new_node = Node(node_str, node_type, current_node) current_node.add_child(new_node) current_node = new_node
[ "def", "expand_from_object", "(", "self", ",", "nyan_object", ")", ":", "# Process the object", "fqon", "=", "nyan_object", ".", "get_fqon", "(", ")", "if", "fqon", "[", "0", "]", "!=", "\"engine\"", ":", "current_node", "=", "self", ".", "root", "node_type", "=", "NodeType", ".", "OBJECT", "for", "node_str", "in", "fqon", ":", "if", "current_node", ".", "has_child", "(", "node_str", ")", ":", "# Choose the already created node", "current_node", "=", "current_node", ".", "get_child", "(", "node_str", ")", "else", ":", "# Add a new node", "new_node", "=", "Node", "(", "node_str", ",", "node_type", ",", "current_node", ")", "current_node", ".", "add_child", "(", "new_node", ")", "current_node", "=", "new_node", "else", ":", "# Workaround for API objects because they are not loaded", "# from files currently.", "# TODO: Remove workaround when API is loaded from files.", "current_node", "=", "self", ".", "root", "index", "=", "0", "while", "index", "<", "len", "(", "fqon", ")", ":", "node_str", "=", "fqon", "[", "index", "]", "if", "current_node", ".", "has_child", "(", "node_str", ")", ":", "# Choose the already created node", "current_node", "=", "current_node", ".", "get_child", "(", "node_str", ")", "else", ":", "# Add a new node", "if", "node_str", "[", "0", "]", ".", "islower", "(", ")", ":", "# By convention, directory and file names are lower case", "# We can check for that to determine the node type.", "node_type", "=", "NodeType", ".", "FILESYS", "else", ":", "node_type", "=", "NodeType", ".", "OBJECT", "new_node", "=", "Node", "(", "node_str", ",", "node_type", ",", "current_node", ")", "current_node", ".", "add_child", "(", "new_node", ")", "current_node", "=", "new_node", "index", "+=", "1", "# Recursively search the nyan objects for nested objects", "unsearched_objects", "=", "[", "]", "unsearched_objects", ".", "extend", "(", "nyan_object", ".", "get_nested_objects", "(", ")", ")", "found_nested_objects", "=", "[", "]", "while", "len", "(", "unsearched_objects", ")", ">", "0", ":", "current_nested_object", "=", "unsearched_objects", "[", "0", "]", "unsearched_objects", ".", "extend", "(", "current_nested_object", ".", "get_nested_objects", "(", ")", ")", "found_nested_objects", ".", "append", "(", "current_nested_object", ")", "unsearched_objects", ".", "remove", "(", "current_nested_object", ")", "# Process fqons of the nested objects", "for", "nested_object", "in", "found_nested_objects", ":", "current_node", "=", "self", ".", "root", "node_type", "=", "NodeType", ".", "NESTED", "fqon", "=", "nested_object", ".", "get_fqon", "(", ")", "for", "node_str", "in", "fqon", ":", "if", "current_node", ".", "has_child", "(", "node_str", ")", ":", "# Choose the already created node", "current_node", "=", "current_node", ".", "get_child", "(", "node_str", ")", "else", ":", "# Add a new node", "new_node", "=", "Node", "(", "node_str", ",", "node_type", ",", "current_node", ")", "current_node", ".", "add_child", "(", "new_node", ")", "current_node", "=", "new_node" ]
https://github.com/SFTtech/openage/blob/d6a08c53c48dc1e157807471df92197f6ca9e04d/openage/nyan/import_tree.py#L70-L150
ablab/spades
3a754192b88540524ce6fb69eef5ea9273a38465
assembler/ext/src/python_libs/pyyaml2/__init__.py
python
add_representer
(data_type, representer, Dumper=Dumper)
Add a representer for the given type. Representer is a function accepting a Dumper instance and an instance of the given data type and producing the corresponding representation node.
Add a representer for the given type. Representer is a function accepting a Dumper instance and an instance of the given data type and producing the corresponding representation node.
[ "Add", "a", "representer", "for", "the", "given", "type", ".", "Representer", "is", "a", "function", "accepting", "a", "Dumper", "instance", "and", "an", "instance", "of", "the", "given", "data", "type", "and", "producing", "the", "corresponding", "representation", "node", "." ]
def add_representer(data_type, representer, Dumper=Dumper): """ Add a representer for the given type. Representer is a function accepting a Dumper instance and an instance of the given data type and producing the corresponding representation node. """ Dumper.add_representer(data_type, representer)
[ "def", "add_representer", "(", "data_type", ",", "representer", ",", "Dumper", "=", "Dumper", ")", ":", "Dumper", ".", "add_representer", "(", "data_type", ",", "representer", ")" ]
https://github.com/ablab/spades/blob/3a754192b88540524ce6fb69eef5ea9273a38465/assembler/ext/src/python_libs/pyyaml2/__init__.py#L266-L273
apache/incubator-mxnet
f03fb23f1d103fec9541b5ae59ee06b1734a51d9
python/mxnet/ndarray/ndarray.py
python
NDArray.to_dlpack_for_write
(self)
return to_dlpack_for_write(self)
Returns a reference view of NDArray that represents as DLManagedTensor until all previous read/write operations on the current array are finished. Returns ------- PyCapsule (the pointer of DLManagedTensor) a reference view of NDArray that represents as DLManagedTensor. Examples -------- >>> x = mx.nd.ones((2,3)) >>> w = mx.nd.to_dlpack_for_write(x) >>> type(w) <class 'PyCapsule'> >>> u = mx.nd.from_dlpack(w) >>> u += 1 >>> x [[2. 2. 2.] [2. 2. 2.]] <NDArray 2x3 @cpu(0)>
Returns a reference view of NDArray that represents as DLManagedTensor until all previous read/write operations on the current array are finished.
[ "Returns", "a", "reference", "view", "of", "NDArray", "that", "represents", "as", "DLManagedTensor", "until", "all", "previous", "read", "/", "write", "operations", "on", "the", "current", "array", "are", "finished", "." ]
def to_dlpack_for_write(self): """Returns a reference view of NDArray that represents as DLManagedTensor until all previous read/write operations on the current array are finished. Returns ------- PyCapsule (the pointer of DLManagedTensor) a reference view of NDArray that represents as DLManagedTensor. Examples -------- >>> x = mx.nd.ones((2,3)) >>> w = mx.nd.to_dlpack_for_write(x) >>> type(w) <class 'PyCapsule'> >>> u = mx.nd.from_dlpack(w) >>> u += 1 >>> x [[2. 2. 2.] [2. 2. 2.]] <NDArray 2x3 @cpu(0)> """ return to_dlpack_for_write(self)
[ "def", "to_dlpack_for_write", "(", "self", ")", ":", "return", "to_dlpack_for_write", "(", "self", ")" ]
https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/python/mxnet/ndarray/ndarray.py#L2998-L3020
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/array_analysis.py
python
SymbolicEquivSet._insert
(self, objs)
return True
Overload _insert method to handle ind changes between relative objects. Returns True if some change is made, false otherwise.
Overload _insert method to handle ind changes between relative objects. Returns True if some change is made, false otherwise.
[ "Overload", "_insert", "method", "to", "handle", "ind", "changes", "between", "relative", "objects", ".", "Returns", "True", "if", "some", "change", "is", "made", "false", "otherwise", "." ]
def _insert(self, objs): """Overload _insert method to handle ind changes between relative objects. Returns True if some change is made, false otherwise. """ indset = set() uniqs = set() for obj in objs: ind = self._get_ind(obj) if ind == -1: uniqs.add(obj) elif not (ind in indset): uniqs.add(obj) indset.add(ind) if len(uniqs) <= 1: return False uniqs = list(uniqs) super(SymbolicEquivSet, self)._insert(uniqs) objs = self.ind_to_obj[self._get_ind(uniqs[0])] # New equivalence guided by def_by and ref_by offset_dict = {} def get_or_set(d, k): if k in d: v = d[k] else: v = [] d[k] = v return v for obj in objs: if obj in self.def_by: value = self.def_by[obj] if isinstance(value, tuple): (name, offset) = value get_or_set(offset_dict, -offset).append(name) if name in self.ref_by: # relative to name for (v, i) in self.ref_by[name]: get_or_set(offset_dict, -(offset+i)).append(v) if obj in self.ref_by: for (name, offset) in self.ref_by[obj]: get_or_set(offset_dict, offset).append(name) for names in offset_dict.values(): self._insert(names) return True
[ "def", "_insert", "(", "self", ",", "objs", ")", ":", "indset", "=", "set", "(", ")", "uniqs", "=", "set", "(", ")", "for", "obj", "in", "objs", ":", "ind", "=", "self", ".", "_get_ind", "(", "obj", ")", "if", "ind", "==", "-", "1", ":", "uniqs", ".", "add", "(", "obj", ")", "elif", "not", "(", "ind", "in", "indset", ")", ":", "uniqs", ".", "add", "(", "obj", ")", "indset", ".", "add", "(", "ind", ")", "if", "len", "(", "uniqs", ")", "<=", "1", ":", "return", "False", "uniqs", "=", "list", "(", "uniqs", ")", "super", "(", "SymbolicEquivSet", ",", "self", ")", ".", "_insert", "(", "uniqs", ")", "objs", "=", "self", ".", "ind_to_obj", "[", "self", ".", "_get_ind", "(", "uniqs", "[", "0", "]", ")", "]", "# New equivalence guided by def_by and ref_by", "offset_dict", "=", "{", "}", "def", "get_or_set", "(", "d", ",", "k", ")", ":", "if", "k", "in", "d", ":", "v", "=", "d", "[", "k", "]", "else", ":", "v", "=", "[", "]", "d", "[", "k", "]", "=", "v", "return", "v", "for", "obj", "in", "objs", ":", "if", "obj", "in", "self", ".", "def_by", ":", "value", "=", "self", ".", "def_by", "[", "obj", "]", "if", "isinstance", "(", "value", ",", "tuple", ")", ":", "(", "name", ",", "offset", ")", "=", "value", "get_or_set", "(", "offset_dict", ",", "-", "offset", ")", ".", "append", "(", "name", ")", "if", "name", "in", "self", ".", "ref_by", ":", "# relative to name", "for", "(", "v", ",", "i", ")", "in", "self", ".", "ref_by", "[", "name", "]", ":", "get_or_set", "(", "offset_dict", ",", "-", "(", "offset", "+", "i", ")", ")", ".", "append", "(", "v", ")", "if", "obj", "in", "self", ".", "ref_by", ":", "for", "(", "name", ",", "offset", ")", "in", "self", ".", "ref_by", "[", "obj", "]", ":", "get_or_set", "(", "offset_dict", ",", "offset", ")", ".", "append", "(", "name", ")", "for", "names", "in", "offset_dict", ".", "values", "(", ")", ":", "self", ".", "_insert", "(", "names", ")", "return", "True" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/array_analysis.py#L854-L896
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/richtext.py
python
RichTextCtrl.SetDragStartTime
(*args, **kwargs)
return _richtext.RichTextCtrl_SetDragStartTime(*args, **kwargs)
SetDragStartTime(self, DateTime st)
SetDragStartTime(self, DateTime st)
[ "SetDragStartTime", "(", "self", "DateTime", "st", ")" ]
def SetDragStartTime(*args, **kwargs): """SetDragStartTime(self, DateTime st)""" return _richtext.RichTextCtrl_SetDragStartTime(*args, **kwargs)
[ "def", "SetDragStartTime", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_richtext", ".", "RichTextCtrl_SetDragStartTime", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/richtext.py#L3057-L3059
hpi-xnor/BMXNet-v2
af2b1859eafc5c721b1397cef02f946aaf2ce20d
python/mxnet/contrib/onnx/mx2onnx/_op_translations.py
python
convert_broadcast_lesser
(node, **kwargs)
return create_basic_op_node('Less', node, kwargs)
Map MXNet's broadcast_lesser operator attributes to onnx's Less operator and return the created node.
Map MXNet's broadcast_lesser operator attributes to onnx's Less operator and return the created node.
[ "Map", "MXNet", "s", "broadcast_lesser", "operator", "attributes", "to", "onnx", "s", "Less", "operator", "and", "return", "the", "created", "node", "." ]
def convert_broadcast_lesser(node, **kwargs): """Map MXNet's broadcast_lesser operator attributes to onnx's Less operator and return the created node. """ return create_basic_op_node('Less', node, kwargs)
[ "def", "convert_broadcast_lesser", "(", "node", ",", "*", "*", "kwargs", ")", ":", "return", "create_basic_op_node", "(", "'Less'", ",", "node", ",", "kwargs", ")" ]
https://github.com/hpi-xnor/BMXNet-v2/blob/af2b1859eafc5c721b1397cef02f946aaf2ce20d/python/mxnet/contrib/onnx/mx2onnx/_op_translations.py#L1762-L1766
eclipse/sumo
7132a9b8b6eea734bdec38479026b4d8c4336d03
tools/sumolib/output/convert/phem.py
python
net2str
(net, outSTRM)
return sIDm
Writes the network object given as "inpNET" as a .str file readable by PHEM. Returns a map from the SUMO-road id to the generated numerical id used by PHEM. The following may be a matter of changes: - currently, only the positions of the start and the end nodes are written, the geometry of the edge as defined in the SUMO-network is not exported. A map between the edge id and a segment to a numerical id would be necessary
Writes the network object given as "inpNET" as a .str file readable by PHEM. Returns a map from the SUMO-road id to the generated numerical id used by PHEM.
[ "Writes", "the", "network", "object", "given", "as", "inpNET", "as", "a", ".", "str", "file", "readable", "by", "PHEM", ".", "Returns", "a", "map", "from", "the", "SUMO", "-", "road", "id", "to", "the", "generated", "numerical", "id", "used", "by", "PHEM", "." ]
def net2str(net, outSTRM): """ Writes the network object given as "inpNET" as a .str file readable by PHEM. Returns a map from the SUMO-road id to the generated numerical id used by PHEM. The following may be a matter of changes: - currently, only the positions of the start and the end nodes are written, the geometry of the edge as defined in the SUMO-network is not exported. A map between the edge id and a segment to a numerical id would be necessary """ if outSTRM is not None: print("Str-Id,Sp,SegAnX,SegEnX,SegAnY,SegEnY", file=outSTRM) sIDm = sumolib._Running() for e in net._edges: eid = sIDm.g(e._id) if outSTRM is not None: c1 = e._from._coord c2 = e._to._coord print("%s,%s,%s,%s,%s,%s" % (eid, len(e._lanes), c1[0], c2[0], c1[1], c2[1]), file=outSTRM) return sIDm
[ "def", "net2str", "(", "net", ",", "outSTRM", ")", ":", "if", "outSTRM", "is", "not", "None", ":", "print", "(", "\"Str-Id,Sp,SegAnX,SegEnX,SegAnY,SegEnY\"", ",", "file", "=", "outSTRM", ")", "sIDm", "=", "sumolib", ".", "_Running", "(", ")", "for", "e", "in", "net", ".", "_edges", ":", "eid", "=", "sIDm", ".", "g", "(", "e", ".", "_id", ")", "if", "outSTRM", "is", "not", "None", ":", "c1", "=", "e", ".", "_from", ".", "_coord", "c2", "=", "e", ".", "_to", ".", "_coord", "print", "(", "\"%s,%s,%s,%s,%s,%s\"", "%", "(", "eid", ",", "len", "(", "e", ".", "_lanes", ")", ",", "c1", "[", "0", "]", ",", "c2", "[", "0", "]", ",", "c1", "[", "1", "]", ",", "c2", "[", "1", "]", ")", ",", "file", "=", "outSTRM", ")", "return", "sIDm" ]
https://github.com/eclipse/sumo/blob/7132a9b8b6eea734bdec38479026b4d8c4336d03/tools/sumolib/output/convert/phem.py#L62-L82
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/distutils/dep_util.py
python
newer
(source, target)
return mtime1 > mtime2
Return true if 'source' exists and is more recently modified than 'target', or if 'source' exists and 'target' doesn't. Return false if both exist and 'target' is the same age or younger than 'source'. Raise DistutilsFileError if 'source' does not exist.
Return true if 'source' exists and is more recently modified than 'target', or if 'source' exists and 'target' doesn't. Return false if both exist and 'target' is the same age or younger than 'source'. Raise DistutilsFileError if 'source' does not exist.
[ "Return", "true", "if", "source", "exists", "and", "is", "more", "recently", "modified", "than", "target", "or", "if", "source", "exists", "and", "target", "doesn", "t", ".", "Return", "false", "if", "both", "exist", "and", "target", "is", "the", "same", "age", "or", "younger", "than", "source", ".", "Raise", "DistutilsFileError", "if", "source", "does", "not", "exist", "." ]
def newer (source, target): """Return true if 'source' exists and is more recently modified than 'target', or if 'source' exists and 'target' doesn't. Return false if both exist and 'target' is the same age or younger than 'source'. Raise DistutilsFileError if 'source' does not exist. """ if not os.path.exists(source): raise DistutilsFileError("file '%s' does not exist" % os.path.abspath(source)) if not os.path.exists(target): return 1 from stat import ST_MTIME mtime1 = os.stat(source)[ST_MTIME] mtime2 = os.stat(target)[ST_MTIME] return mtime1 > mtime2
[ "def", "newer", "(", "source", ",", "target", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "source", ")", ":", "raise", "DistutilsFileError", "(", "\"file '%s' does not exist\"", "%", "os", ".", "path", ".", "abspath", "(", "source", ")", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "target", ")", ":", "return", "1", "from", "stat", "import", "ST_MTIME", "mtime1", "=", "os", ".", "stat", "(", "source", ")", "[", "ST_MTIME", "]", "mtime2", "=", "os", ".", "stat", "(", "target", ")", "[", "ST_MTIME", "]", "return", "mtime1", ">", "mtime2" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/distutils/dep_util.py#L11-L27
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
third_party/gpus/find_cuda_config.py
python
find_cuda_config
()
return result
Returns a dictionary of CUDA library and header file paths.
Returns a dictionary of CUDA library and header file paths.
[ "Returns", "a", "dictionary", "of", "CUDA", "library", "and", "header", "file", "paths", "." ]
def find_cuda_config(): """Returns a dictionary of CUDA library and header file paths.""" libraries = [argv.lower() for argv in sys.argv[1:]] cuda_version = os.environ.get("TF_CUDA_VERSION", "") base_paths = _list_from_env("TF_CUDA_PATHS", _get_default_cuda_paths(cuda_version)) base_paths = [path for path in base_paths if os.path.exists(path)] result = {} if "cuda" in libraries: cuda_paths = _list_from_env("CUDA_TOOLKIT_PATH", base_paths) result.update(_find_cuda_config(cuda_paths, cuda_version)) cuda_version = result["cuda_version"] cublas_paths = base_paths if tuple(int(v) for v in cuda_version.split(".")) < (10, 1): # Before CUDA 10.1, cuBLAS was in the same directory as the toolkit. cublas_paths = cuda_paths cublas_version = os.environ.get("TF_CUBLAS_VERSION", "") result.update( _find_cublas_config(cublas_paths, cublas_version, cuda_version)) cusolver_paths = base_paths if tuple(int(v) for v in cuda_version.split(".")) < (11, 0): cusolver_paths = cuda_paths cusolver_version = os.environ.get("TF_CUSOLVER_VERSION", "") result.update( _find_cusolver_config(cusolver_paths, cusolver_version, cuda_version)) curand_paths = base_paths if tuple(int(v) for v in cuda_version.split(".")) < (11, 0): curand_paths = cuda_paths curand_version = os.environ.get("TF_CURAND_VERSION", "") result.update( _find_curand_config(curand_paths, curand_version, cuda_version)) cufft_paths = base_paths if tuple(int(v) for v in cuda_version.split(".")) < (11, 0): cufft_paths = cuda_paths cufft_version = os.environ.get("TF_CUFFT_VERSION", "") result.update(_find_cufft_config(cufft_paths, cufft_version, cuda_version)) cusparse_paths = base_paths if tuple(int(v) for v in cuda_version.split(".")) < (11, 0): cusparse_paths = cuda_paths cusparse_version = os.environ.get("TF_CUSPARSE_VERSION", "") result.update( _find_cusparse_config(cusparse_paths, cusparse_version, cuda_version)) if "cudnn" in libraries: cudnn_paths = _get_legacy_path("CUDNN_INSTALL_PATH", base_paths) cudnn_version = os.environ.get("TF_CUDNN_VERSION", "") result.update(_find_cudnn_config(cudnn_paths, cudnn_version)) if "nccl" in libraries: nccl_paths = _get_legacy_path("NCCL_INSTALL_PATH", base_paths) nccl_version = os.environ.get("TF_NCCL_VERSION", "") result.update(_find_nccl_config(nccl_paths, nccl_version)) if "tensorrt" in libraries: tensorrt_paths = _get_legacy_path("TENSORRT_INSTALL_PATH", base_paths) tensorrt_version = os.environ.get("TF_TENSORRT_VERSION", "") result.update(_find_tensorrt_config(tensorrt_paths, tensorrt_version)) for k, v in result.items(): if k.endswith("_dir") or k.endswith("_path"): result[k] = _normalize_path(v) return result
[ "def", "find_cuda_config", "(", ")", ":", "libraries", "=", "[", "argv", ".", "lower", "(", ")", "for", "argv", "in", "sys", ".", "argv", "[", "1", ":", "]", "]", "cuda_version", "=", "os", ".", "environ", ".", "get", "(", "\"TF_CUDA_VERSION\"", ",", "\"\"", ")", "base_paths", "=", "_list_from_env", "(", "\"TF_CUDA_PATHS\"", ",", "_get_default_cuda_paths", "(", "cuda_version", ")", ")", "base_paths", "=", "[", "path", "for", "path", "in", "base_paths", "if", "os", ".", "path", ".", "exists", "(", "path", ")", "]", "result", "=", "{", "}", "if", "\"cuda\"", "in", "libraries", ":", "cuda_paths", "=", "_list_from_env", "(", "\"CUDA_TOOLKIT_PATH\"", ",", "base_paths", ")", "result", ".", "update", "(", "_find_cuda_config", "(", "cuda_paths", ",", "cuda_version", ")", ")", "cuda_version", "=", "result", "[", "\"cuda_version\"", "]", "cublas_paths", "=", "base_paths", "if", "tuple", "(", "int", "(", "v", ")", "for", "v", "in", "cuda_version", ".", "split", "(", "\".\"", ")", ")", "<", "(", "10", ",", "1", ")", ":", "# Before CUDA 10.1, cuBLAS was in the same directory as the toolkit.", "cublas_paths", "=", "cuda_paths", "cublas_version", "=", "os", ".", "environ", ".", "get", "(", "\"TF_CUBLAS_VERSION\"", ",", "\"\"", ")", "result", ".", "update", "(", "_find_cublas_config", "(", "cublas_paths", ",", "cublas_version", ",", "cuda_version", ")", ")", "cusolver_paths", "=", "base_paths", "if", "tuple", "(", "int", "(", "v", ")", "for", "v", "in", "cuda_version", ".", "split", "(", "\".\"", ")", ")", "<", "(", "11", ",", "0", ")", ":", "cusolver_paths", "=", "cuda_paths", "cusolver_version", "=", "os", ".", "environ", ".", "get", "(", "\"TF_CUSOLVER_VERSION\"", ",", "\"\"", ")", "result", ".", "update", "(", "_find_cusolver_config", "(", "cusolver_paths", ",", "cusolver_version", ",", "cuda_version", ")", ")", "curand_paths", "=", "base_paths", "if", "tuple", "(", "int", "(", "v", ")", "for", "v", "in", "cuda_version", ".", "split", "(", "\".\"", ")", ")", "<", "(", "11", ",", "0", ")", ":", "curand_paths", "=", "cuda_paths", "curand_version", "=", "os", ".", "environ", ".", "get", "(", "\"TF_CURAND_VERSION\"", ",", "\"\"", ")", "result", ".", "update", "(", "_find_curand_config", "(", "curand_paths", ",", "curand_version", ",", "cuda_version", ")", ")", "cufft_paths", "=", "base_paths", "if", "tuple", "(", "int", "(", "v", ")", "for", "v", "in", "cuda_version", ".", "split", "(", "\".\"", ")", ")", "<", "(", "11", ",", "0", ")", ":", "cufft_paths", "=", "cuda_paths", "cufft_version", "=", "os", ".", "environ", ".", "get", "(", "\"TF_CUFFT_VERSION\"", ",", "\"\"", ")", "result", ".", "update", "(", "_find_cufft_config", "(", "cufft_paths", ",", "cufft_version", ",", "cuda_version", ")", ")", "cusparse_paths", "=", "base_paths", "if", "tuple", "(", "int", "(", "v", ")", "for", "v", "in", "cuda_version", ".", "split", "(", "\".\"", ")", ")", "<", "(", "11", ",", "0", ")", ":", "cusparse_paths", "=", "cuda_paths", "cusparse_version", "=", "os", ".", "environ", ".", "get", "(", "\"TF_CUSPARSE_VERSION\"", ",", "\"\"", ")", "result", ".", "update", "(", "_find_cusparse_config", "(", "cusparse_paths", ",", "cusparse_version", ",", "cuda_version", ")", ")", "if", "\"cudnn\"", "in", "libraries", ":", "cudnn_paths", "=", "_get_legacy_path", "(", "\"CUDNN_INSTALL_PATH\"", ",", "base_paths", ")", "cudnn_version", "=", "os", ".", "environ", ".", "get", "(", "\"TF_CUDNN_VERSION\"", ",", "\"\"", ")", "result", ".", "update", "(", "_find_cudnn_config", "(", "cudnn_paths", ",", "cudnn_version", ")", ")", "if", "\"nccl\"", "in", "libraries", ":", "nccl_paths", "=", "_get_legacy_path", "(", "\"NCCL_INSTALL_PATH\"", ",", "base_paths", ")", "nccl_version", "=", "os", ".", "environ", ".", "get", "(", "\"TF_NCCL_VERSION\"", ",", "\"\"", ")", "result", ".", "update", "(", "_find_nccl_config", "(", "nccl_paths", ",", "nccl_version", ")", ")", "if", "\"tensorrt\"", "in", "libraries", ":", "tensorrt_paths", "=", "_get_legacy_path", "(", "\"TENSORRT_INSTALL_PATH\"", ",", "base_paths", ")", "tensorrt_version", "=", "os", ".", "environ", ".", "get", "(", "\"TF_TENSORRT_VERSION\"", ",", "\"\"", ")", "result", ".", "update", "(", "_find_tensorrt_config", "(", "tensorrt_paths", ",", "tensorrt_version", ")", ")", "for", "k", ",", "v", "in", "result", ".", "items", "(", ")", ":", "if", "k", ".", "endswith", "(", "\"_dir\"", ")", "or", "k", ".", "endswith", "(", "\"_path\"", ")", ":", "result", "[", "k", "]", "=", "_normalize_path", "(", "v", ")", "return", "result" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/third_party/gpus/find_cuda_config.py#L566-L634
1989Ryan/Semantic_SLAM
0284b3f832ca431c494f9c134fe46c40ec86ee38
Third_Part/PSPNet_Keras_tensorflow/pascal_voc_labels.py
python
generate_color_map
(N=256, normalized=False)
return cmap
from https://gist.github.com/wllhf/a4533e0adebe57e3ed06d4b50c8419ae .
from https://gist.github.com/wllhf/a4533e0adebe57e3ed06d4b50c8419ae .
[ "from", "https", ":", "//", "gist", ".", "github", ".", "com", "/", "wllhf", "/", "a4533e0adebe57e3ed06d4b50c8419ae", "." ]
def generate_color_map(N=256, normalized=False): """from https://gist.github.com/wllhf/a4533e0adebe57e3ed06d4b50c8419ae .""" def bitget(byteval, idx): return ((byteval & (1 << idx)) != 0) dtype = 'float32' if normalized else 'uint8' cmap = np.zeros((N, 3), dtype=dtype) for i in range(N): r = g = b = 0 c = i for j in range(8): r = r | (bitget(c, 0) << 7 - j) g = g | (bitget(c, 1) << 7 - j) b = b | (bitget(c, 2) << 7 - j) c = c >> 3 cmap[i] = np.array([r, g, b]) cmap = cmap / 255 if normalized else cmap return cmap
[ "def", "generate_color_map", "(", "N", "=", "256", ",", "normalized", "=", "False", ")", ":", "def", "bitget", "(", "byteval", ",", "idx", ")", ":", "return", "(", "(", "byteval", "&", "(", "1", "<<", "idx", ")", ")", "!=", "0", ")", "dtype", "=", "'float32'", "if", "normalized", "else", "'uint8'", "cmap", "=", "np", ".", "zeros", "(", "(", "N", ",", "3", ")", ",", "dtype", "=", "dtype", ")", "for", "i", "in", "range", "(", "N", ")", ":", "r", "=", "g", "=", "b", "=", "0", "c", "=", "i", "for", "j", "in", "range", "(", "8", ")", ":", "r", "=", "r", "|", "(", "bitget", "(", "c", ",", "0", ")", "<<", "7", "-", "j", ")", "g", "=", "g", "|", "(", "bitget", "(", "c", ",", "1", ")", "<<", "7", "-", "j", ")", "b", "=", "b", "|", "(", "bitget", "(", "c", ",", "2", ")", "<<", "7", "-", "j", ")", "c", "=", "c", ">>", "3", "cmap", "[", "i", "]", "=", "np", ".", "array", "(", "[", "r", ",", "g", ",", "b", "]", ")", "cmap", "=", "cmap", "/", "255", "if", "normalized", "else", "cmap", "return", "cmap" ]
https://github.com/1989Ryan/Semantic_SLAM/blob/0284b3f832ca431c494f9c134fe46c40ec86ee38/Third_Part/PSPNet_Keras_tensorflow/pascal_voc_labels.py#L42-L61
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numpy/polynomial/legendre.py
python
legder
(c, m=1, scl=1, axis=0)
return c
Differentiate a Legendre series. Returns the Legendre series coefficients `c` differentiated `m` times along `axis`. At each iteration the result is multiplied by `scl` (the scaling factor is for use in a linear change of variable). The argument `c` is an array of coefficients from low to high degree along each axis, e.g., [1,2,3] represents the series ``1*L_0 + 2*L_1 + 3*L_2`` while [[1,2],[1,2]] represents ``1*L_0(x)*L_0(y) + 1*L_1(x)*L_0(y) + 2*L_0(x)*L_1(y) + 2*L_1(x)*L_1(y)`` if axis=0 is ``x`` and axis=1 is ``y``. Parameters ---------- c : array_like Array of Legendre series coefficients. If c is multidimensional the different axis correspond to different variables with the degree in each axis given by the corresponding index. m : int, optional Number of derivatives taken, must be non-negative. (Default: 1) scl : scalar, optional Each differentiation is multiplied by `scl`. The end result is multiplication by ``scl**m``. This is for use in a linear change of variable. (Default: 1) axis : int, optional Axis over which the derivative is taken. (Default: 0). .. versionadded:: 1.7.0 Returns ------- der : ndarray Legendre series of the derivative. See Also -------- legint Notes ----- In general, the result of differentiating a Legendre series does not resemble the same operation on a power series. Thus the result of this function may be "unintuitive," albeit correct; see Examples section below. Examples -------- >>> from numpy.polynomial import legendre as L >>> c = (1,2,3,4) >>> L.legder(c) array([ 6., 9., 20.]) >>> L.legder(c, 3) array([60.]) >>> L.legder(c, scl=-1) array([ -6., -9., -20.]) >>> L.legder(c, 2,-1) array([ 9., 60.])
Differentiate a Legendre series.
[ "Differentiate", "a", "Legendre", "series", "." ]
def legder(c, m=1, scl=1, axis=0): """ Differentiate a Legendre series. Returns the Legendre series coefficients `c` differentiated `m` times along `axis`. At each iteration the result is multiplied by `scl` (the scaling factor is for use in a linear change of variable). The argument `c` is an array of coefficients from low to high degree along each axis, e.g., [1,2,3] represents the series ``1*L_0 + 2*L_1 + 3*L_2`` while [[1,2],[1,2]] represents ``1*L_0(x)*L_0(y) + 1*L_1(x)*L_0(y) + 2*L_0(x)*L_1(y) + 2*L_1(x)*L_1(y)`` if axis=0 is ``x`` and axis=1 is ``y``. Parameters ---------- c : array_like Array of Legendre series coefficients. If c is multidimensional the different axis correspond to different variables with the degree in each axis given by the corresponding index. m : int, optional Number of derivatives taken, must be non-negative. (Default: 1) scl : scalar, optional Each differentiation is multiplied by `scl`. The end result is multiplication by ``scl**m``. This is for use in a linear change of variable. (Default: 1) axis : int, optional Axis over which the derivative is taken. (Default: 0). .. versionadded:: 1.7.0 Returns ------- der : ndarray Legendre series of the derivative. See Also -------- legint Notes ----- In general, the result of differentiating a Legendre series does not resemble the same operation on a power series. Thus the result of this function may be "unintuitive," albeit correct; see Examples section below. Examples -------- >>> from numpy.polynomial import legendre as L >>> c = (1,2,3,4) >>> L.legder(c) array([ 6., 9., 20.]) >>> L.legder(c, 3) array([60.]) >>> L.legder(c, scl=-1) array([ -6., -9., -20.]) >>> L.legder(c, 2,-1) array([ 9., 60.]) """ c = np.array(c, ndmin=1, copy=True) if c.dtype.char in '?bBhHiIlLqQpP': c = c.astype(np.double) cnt = pu._deprecate_as_int(m, "the order of derivation") iaxis = pu._deprecate_as_int(axis, "the axis") if cnt < 0: raise ValueError("The order of derivation must be non-negative") iaxis = normalize_axis_index(iaxis, c.ndim) if cnt == 0: return c c = np.moveaxis(c, iaxis, 0) n = len(c) if cnt >= n: c = c[:1]*0 else: for i in range(cnt): n = n - 1 c *= scl der = np.empty((n,) + c.shape[1:], dtype=c.dtype) for j in range(n, 2, -1): der[j - 1] = (2*j - 1)*c[j] c[j - 2] += c[j] if n > 1: der[1] = 3*c[2] der[0] = c[1] c = der c = np.moveaxis(c, 0, iaxis) return c
[ "def", "legder", "(", "c", ",", "m", "=", "1", ",", "scl", "=", "1", ",", "axis", "=", "0", ")", ":", "c", "=", "np", ".", "array", "(", "c", ",", "ndmin", "=", "1", ",", "copy", "=", "True", ")", "if", "c", ".", "dtype", ".", "char", "in", "'?bBhHiIlLqQpP'", ":", "c", "=", "c", ".", "astype", "(", "np", ".", "double", ")", "cnt", "=", "pu", ".", "_deprecate_as_int", "(", "m", ",", "\"the order of derivation\"", ")", "iaxis", "=", "pu", ".", "_deprecate_as_int", "(", "axis", ",", "\"the axis\"", ")", "if", "cnt", "<", "0", ":", "raise", "ValueError", "(", "\"The order of derivation must be non-negative\"", ")", "iaxis", "=", "normalize_axis_index", "(", "iaxis", ",", "c", ".", "ndim", ")", "if", "cnt", "==", "0", ":", "return", "c", "c", "=", "np", ".", "moveaxis", "(", "c", ",", "iaxis", ",", "0", ")", "n", "=", "len", "(", "c", ")", "if", "cnt", ">=", "n", ":", "c", "=", "c", "[", ":", "1", "]", "*", "0", "else", ":", "for", "i", "in", "range", "(", "cnt", ")", ":", "n", "=", "n", "-", "1", "c", "*=", "scl", "der", "=", "np", ".", "empty", "(", "(", "n", ",", ")", "+", "c", ".", "shape", "[", "1", ":", "]", ",", "dtype", "=", "c", ".", "dtype", ")", "for", "j", "in", "range", "(", "n", ",", "2", ",", "-", "1", ")", ":", "der", "[", "j", "-", "1", "]", "=", "(", "2", "*", "j", "-", "1", ")", "*", "c", "[", "j", "]", "c", "[", "j", "-", "2", "]", "+=", "c", "[", "j", "]", "if", "n", ">", "1", ":", "der", "[", "1", "]", "=", "3", "*", "c", "[", "2", "]", "der", "[", "0", "]", "=", "c", "[", "1", "]", "c", "=", "der", "c", "=", "np", ".", "moveaxis", "(", "c", ",", "0", ",", "iaxis", ")", "return", "c" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numpy/polynomial/legendre.py#L612-L701
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
native_client_sdk/src/tools/decode_dump.py
python
CoreDecoder._DecodeAddressSegment
(self, segments, address)
return ('(null)', address)
Convert an address to a segment relative one, plus filename. Args: segments: a list of phdr segments. address: a process wide code address. Returns: A tuple of filename and segment relative address.
Convert an address to a segment relative one, plus filename.
[ "Convert", "an", "address", "to", "a", "segment", "relative", "one", "plus", "filename", "." ]
def _DecodeAddressSegment(self, segments, address): """Convert an address to a segment relative one, plus filename. Args: segments: a list of phdr segments. address: a process wide code address. Returns: A tuple of filename and segment relative address. """ for segment in segments: for phdr in segment['dlpi_phdr']: start = segment['dlpi_addr'] + phdr['p_vaddr'] end = start + phdr['p_memsz'] if address >= start and address < end: return (segment['dlpi_name'], address - segment['dlpi_addr']) return ('(null)', address)
[ "def", "_DecodeAddressSegment", "(", "self", ",", "segments", ",", "address", ")", ":", "for", "segment", "in", "segments", ":", "for", "phdr", "in", "segment", "[", "'dlpi_phdr'", "]", ":", "start", "=", "segment", "[", "'dlpi_addr'", "]", "+", "phdr", "[", "'p_vaddr'", "]", "end", "=", "start", "+", "phdr", "[", "'p_memsz'", "]", "if", "address", ">=", "start", "and", "address", "<", "end", ":", "return", "(", "segment", "[", "'dlpi_name'", "]", ",", "address", "-", "segment", "[", "'dlpi_addr'", "]", ")", "return", "(", "'(null)'", ",", "address", ")" ]
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/native_client_sdk/src/tools/decode_dump.py#L76-L91
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
tools/git/move_source_file.py
python
MakeDestinationPath
(from_path, to_path)
return to_path
Given the from and to paths, return a correct destination path. The initial destination path may either a full path or a directory. Also does basic sanity checks.
Given the from and to paths, return a correct destination path.
[ "Given", "the", "from", "and", "to", "paths", "return", "a", "correct", "destination", "path", "." ]
def MakeDestinationPath(from_path, to_path): """Given the from and to paths, return a correct destination path. The initial destination path may either a full path or a directory. Also does basic sanity checks. """ if not IsHandledFile(from_path): raise Exception('Only intended to move individual source files ' '(%s does not have a recognized extension).' % from_path) # Remove '.', '..', etc. to_path = os.path.normpath(to_path) if os.path.isdir(to_path): to_path = os.path.join(to_path, os.path.basename(from_path)) else: dest_extension = os.path.splitext(to_path)[1] if dest_extension not in HANDLED_EXTENSIONS: raise Exception('Destination must be either a full path with ' 'a recognized extension or a directory.') return to_path
[ "def", "MakeDestinationPath", "(", "from_path", ",", "to_path", ")", ":", "if", "not", "IsHandledFile", "(", "from_path", ")", ":", "raise", "Exception", "(", "'Only intended to move individual source files '", "'(%s does not have a recognized extension).'", "%", "from_path", ")", "# Remove '.', '..', etc.", "to_path", "=", "os", ".", "path", ".", "normpath", "(", "to_path", ")", "if", "os", ".", "path", ".", "isdir", "(", "to_path", ")", ":", "to_path", "=", "os", ".", "path", ".", "join", "(", "to_path", ",", "os", ".", "path", ".", "basename", "(", "from_path", ")", ")", "else", ":", "dest_extension", "=", "os", ".", "path", ".", "splitext", "(", "to_path", ")", "[", "1", "]", "if", "dest_extension", "not", "in", "HANDLED_EXTENSIONS", ":", "raise", "Exception", "(", "'Destination must be either a full path with '", "'a recognized extension or a directory.'", ")", "return", "to_path" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/git/move_source_file.py#L43-L64
mongodb/mongo
d8ff665343ad29cf286ee2cf4a1960d29371937b
buildscripts/evergreen_task_tags.py
python
list_all_tags
(evg_config)
Print all task tags found in the evergreen configuration. :param evg_config: evergreen configuration.
Print all task tags found in the evergreen configuration.
[ "Print", "all", "task", "tags", "found", "in", "the", "evergreen", "configuration", "." ]
def list_all_tags(evg_config): """ Print all task tags found in the evergreen configuration. :param evg_config: evergreen configuration. """ all_tags = get_all_task_tags(evg_config) for tag in all_tags: print(tag)
[ "def", "list_all_tags", "(", "evg_config", ")", ":", "all_tags", "=", "get_all_task_tags", "(", "evg_config", ")", "for", "tag", "in", "all_tags", ":", "print", "(", "tag", ")" ]
https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/buildscripts/evergreen_task_tags.py#L48-L56
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/contextlib.py
python
_BaseExitStack.callback
(*args, **kwds)
return callback
Registers an arbitrary callback and arguments. Cannot suppress exceptions.
Registers an arbitrary callback and arguments.
[ "Registers", "an", "arbitrary", "callback", "and", "arguments", "." ]
def callback(*args, **kwds): """Registers an arbitrary callback and arguments. Cannot suppress exceptions. """ if len(args) >= 2: self, callback, *args = args elif not args: raise TypeError("descriptor 'callback' of '_BaseExitStack' object " "needs an argument") elif 'callback' in kwds: callback = kwds.pop('callback') self, *args = args else: raise TypeError('callback expected at least 1 positional argument, ' 'got %d' % (len(args)-1)) _exit_wrapper = self._create_cb_wrapper(callback, *args, **kwds) # We changed the signature, so using @wraps is not appropriate, but # setting __wrapped__ may still help with introspection. _exit_wrapper.__wrapped__ = callback self._push_exit_callback(_exit_wrapper) return callback
[ "def", "callback", "(", "*", "args", ",", "*", "*", "kwds", ")", ":", "if", "len", "(", "args", ")", ">=", "2", ":", "self", ",", "callback", ",", "", "*", "args", "=", "args", "elif", "not", "args", ":", "raise", "TypeError", "(", "\"descriptor 'callback' of '_BaseExitStack' object \"", "\"needs an argument\"", ")", "elif", "'callback'", "in", "kwds", ":", "callback", "=", "kwds", ".", "pop", "(", "'callback'", ")", "self", ",", "", "*", "args", "=", "args", "else", ":", "raise", "TypeError", "(", "'callback expected at least 1 positional argument, '", "'got %d'", "%", "(", "len", "(", "args", ")", "-", "1", ")", ")", "_exit_wrapper", "=", "self", ".", "_create_cb_wrapper", "(", "callback", ",", "*", "args", ",", "*", "*", "kwds", ")", "# We changed the signature, so using @wraps is not appropriate, but", "# setting __wrapped__ may still help with introspection.", "_exit_wrapper", ".", "__wrapped__", "=", "callback", "self", ".", "_push_exit_callback", "(", "_exit_wrapper", ")", "return", "callback" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/contextlib.py#L431-L454
eventql/eventql
7ca0dbb2e683b525620ea30dc40540a22d5eb227
deps/3rdparty/spidermonkey/mozjs/python/bitstring/bitstring.py
python
Bits._converttobitstring
(cls, bs, offset=0, cache={})
return cls(bs)
Convert bs to a bitstring and return it. offset gives the suggested bit offset of first significant bit, to optimise append etc.
Convert bs to a bitstring and return it.
[ "Convert", "bs", "to", "a", "bitstring", "and", "return", "it", "." ]
def _converttobitstring(cls, bs, offset=0, cache={}): """Convert bs to a bitstring and return it. offset gives the suggested bit offset of first significant bit, to optimise append etc. """ if isinstance(bs, Bits): return bs try: return cache[(bs, offset)] except KeyError: if isinstance(bs, basestring): b = cls() try: _, tokens = tokenparser(bs) except ValueError as e: raise CreationError(*e.args) if tokens: b._append(Bits._init_with_token(*tokens[0])) b._datastore = offsetcopy(b._datastore, offset) for token in tokens[1:]: b._append(Bits._init_with_token(*token)) assert b._assertsanity() assert b.len == 0 or b._offset == offset if len(cache) < CACHE_SIZE: cache[(bs, offset)] = b return b except TypeError: # Unhashable type pass return cls(bs)
[ "def", "_converttobitstring", "(", "cls", ",", "bs", ",", "offset", "=", "0", ",", "cache", "=", "{", "}", ")", ":", "if", "isinstance", "(", "bs", ",", "Bits", ")", ":", "return", "bs", "try", ":", "return", "cache", "[", "(", "bs", ",", "offset", ")", "]", "except", "KeyError", ":", "if", "isinstance", "(", "bs", ",", "basestring", ")", ":", "b", "=", "cls", "(", ")", "try", ":", "_", ",", "tokens", "=", "tokenparser", "(", "bs", ")", "except", "ValueError", "as", "e", ":", "raise", "CreationError", "(", "*", "e", ".", "args", ")", "if", "tokens", ":", "b", ".", "_append", "(", "Bits", ".", "_init_with_token", "(", "*", "tokens", "[", "0", "]", ")", ")", "b", ".", "_datastore", "=", "offsetcopy", "(", "b", ".", "_datastore", ",", "offset", ")", "for", "token", "in", "tokens", "[", "1", ":", "]", ":", "b", ".", "_append", "(", "Bits", ".", "_init_with_token", "(", "*", "token", ")", ")", "assert", "b", ".", "_assertsanity", "(", ")", "assert", "b", ".", "len", "==", "0", "or", "b", ".", "_offset", "==", "offset", "if", "len", "(", "cache", ")", "<", "CACHE_SIZE", ":", "cache", "[", "(", "bs", ",", "offset", ")", "]", "=", "b", "return", "b", "except", "TypeError", ":", "# Unhashable type", "pass", "return", "cls", "(", "bs", ")" ]
https://github.com/eventql/eventql/blob/7ca0dbb2e683b525620ea30dc40540a22d5eb227/deps/3rdparty/spidermonkey/mozjs/python/bitstring/bitstring.py#L1947-L1978
Smorodov/Multitarget-tracker
bee300e8bfd660c86cbeb6892c65a5b7195c9381
thirdparty/pybind11/tools/clang/cindex.py
python
Type.get_class_type
(self)
return conf.lib.clang_Type_getClassType(self)
Retrieve the class type of the member pointer type.
Retrieve the class type of the member pointer type.
[ "Retrieve", "the", "class", "type", "of", "the", "member", "pointer", "type", "." ]
def get_class_type(self): """ Retrieve the class type of the member pointer type. """ return conf.lib.clang_Type_getClassType(self)
[ "def", "get_class_type", "(", "self", ")", ":", "return", "conf", ".", "lib", ".", "clang_Type_getClassType", "(", "self", ")" ]
https://github.com/Smorodov/Multitarget-tracker/blob/bee300e8bfd660c86cbeb6892c65a5b7195c9381/thirdparty/pybind11/tools/clang/cindex.py#L2072-L2076
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
qt/applications/workbench/workbench/projectrecovery/projectrecoveryloader.py
python
ProjectRecoveryLoader._open_script_in_editor_call
(self, script)
Open script in editor method invokation to guarantee it occurring on the correct thread. :param script: String; Path to the script :return:
Open script in editor method invokation to guarantee it occurring on the correct thread. :param script: String; Path to the script :return:
[ "Open", "script", "in", "editor", "method", "invokation", "to", "guarantee", "it", "occurring", "on", "the", "correct", "thread", ".", ":", "param", "script", ":", "String", ";", "Path", "to", "the", "script", ":", "return", ":" ]
def _open_script_in_editor_call(self, script): """ Open script in editor method invokation to guarantee it occurring on the correct thread. :param script: String; Path to the script :return: """ self.multi_file_interpreter.open_file_in_new_tab(script)
[ "def", "_open_script_in_editor_call", "(", "self", ",", "script", ")", ":", "self", ".", "multi_file_interpreter", ".", "open_file_in_new_tab", "(", "script", ")" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/applications/workbench/workbench/projectrecovery/projectrecoveryloader.py#L126-L132
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemFramework/v1/ResourceManager/lib/Crypto/Util/asn1.py
python
DerSequence.__init__
(self, startSeq=None, implicit=None)
Initialize the DER object as a SEQUENCE. :Parameters: startSeq : Python sequence A sequence whose element are either integers or other DER objects. implicit : integer The IMPLICIT tag to use for the encoded object. It overrides the universal tag for SEQUENCE (16).
Initialize the DER object as a SEQUENCE.
[ "Initialize", "the", "DER", "object", "as", "a", "SEQUENCE", "." ]
def __init__(self, startSeq=None, implicit=None): """Initialize the DER object as a SEQUENCE. :Parameters: startSeq : Python sequence A sequence whose element are either integers or other DER objects. implicit : integer The IMPLICIT tag to use for the encoded object. It overrides the universal tag for SEQUENCE (16). """ DerObject.__init__(self, 0x10, b'', implicit, True) if startSeq is None: self._seq = [] else: self._seq = startSeq
[ "def", "__init__", "(", "self", ",", "startSeq", "=", "None", ",", "implicit", "=", "None", ")", ":", "DerObject", ".", "__init__", "(", "self", ",", "0x10", ",", "b''", ",", "implicit", ",", "True", ")", "if", "startSeq", "is", "None", ":", "self", ".", "_seq", "=", "[", "]", "else", ":", "self", ".", "_seq", "=", "startSeq" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/ResourceManager/lib/Crypto/Util/asn1.py#L387-L404
vicaya/hypertable
e7386f799c238c109ae47973417c2a2c7f750825
src/py/ThriftClient/gen-py/hyperthrift/gen/ClientService.py
python
Iface.open_mutator
(self, name, flags, flush_interval)
Open a table mutator @param name - table name @param flags - mutator flags @param flush_interval - auto-flush interval in milliseconds; 0 disables it. @return mutator id Parameters: - name - flags - flush_interval
Open a table mutator
[ "Open", "a", "table", "mutator" ]
def open_mutator(self, name, flags, flush_interval): """ Open a table mutator @param name - table name @param flags - mutator flags @param flush_interval - auto-flush interval in milliseconds; 0 disables it. @return mutator id Parameters: - name - flags - flush_interval """ pass
[ "def", "open_mutator", "(", "self", ",", "name", ",", "flags", ",", "flush_interval", ")", ":", "pass" ]
https://github.com/vicaya/hypertable/blob/e7386f799c238c109ae47973417c2a2c7f750825/src/py/ThriftClient/gen-py/hyperthrift/gen/ClientService.py#L176-L193
google/shaka-packager
e1b0c7c45431327fd3ce193514a5407d07b39b22
packager/third_party/protobuf/python/google/protobuf/internal/well_known_types.py
python
Duration.FromTimedelta
(self, td)
Convertd timedelta to Duration.
Convertd timedelta to Duration.
[ "Convertd", "timedelta", "to", "Duration", "." ]
def FromTimedelta(self, td): """Convertd timedelta to Duration.""" self._NormalizeDuration(td.seconds + td.days * _SECONDS_PER_DAY, td.microseconds * _NANOS_PER_MICROSECOND)
[ "def", "FromTimedelta", "(", "self", ",", "td", ")", ":", "self", ".", "_NormalizeDuration", "(", "td", ".", "seconds", "+", "td", ".", "days", "*", "_SECONDS_PER_DAY", ",", "td", ".", "microseconds", "*", "_NANOS_PER_MICROSECOND", ")" ]
https://github.com/google/shaka-packager/blob/e1b0c7c45431327fd3ce193514a5407d07b39b22/packager/third_party/protobuf/python/google/protobuf/internal/well_known_types.py#L352-L355
tangzhenyu/Scene-Text-Understanding
0f7ffc7aea5971a50cdc03d33d0a41075285948b
SynthText_Chinese/colorize3_poisson.py
python
Colorize.border
(self, alpha, size, kernel_type='RECT')
return border
alpha : alpha layer of the text size : size of the kernel kernel_type : one of [rect,ellipse,cross] @return : alpha layer of the border (color to be added externally).
alpha : alpha layer of the text size : size of the kernel kernel_type : one of [rect,ellipse,cross]
[ "alpha", ":", "alpha", "layer", "of", "the", "text", "size", ":", "size", "of", "the", "kernel", "kernel_type", ":", "one", "of", "[", "rect", "ellipse", "cross", "]" ]
def border(self, alpha, size, kernel_type='RECT'): """ alpha : alpha layer of the text size : size of the kernel kernel_type : one of [rect,ellipse,cross] @return : alpha layer of the border (color to be added externally). """ kdict = {'RECT':cv.MORPH_RECT, 'ELLIPSE':cv.MORPH_ELLIPSE, 'CROSS':cv.MORPH_CROSS} kernel = cv.getStructuringElement(kdict[kernel_type],(size,size)) border = cv.dilate(alpha,kernel,iterations=1) # - alpha return border
[ "def", "border", "(", "self", ",", "alpha", ",", "size", ",", "kernel_type", "=", "'RECT'", ")", ":", "kdict", "=", "{", "'RECT'", ":", "cv", ".", "MORPH_RECT", ",", "'ELLIPSE'", ":", "cv", ".", "MORPH_ELLIPSE", ",", "'CROSS'", ":", "cv", ".", "MORPH_CROSS", "}", "kernel", "=", "cv", ".", "getStructuringElement", "(", "kdict", "[", "kernel_type", "]", ",", "(", "size", ",", "size", ")", ")", "border", "=", "cv", ".", "dilate", "(", "alpha", ",", "kernel", ",", "iterations", "=", "1", ")", "# - alpha", "return", "border" ]
https://github.com/tangzhenyu/Scene-Text-Understanding/blob/0f7ffc7aea5971a50cdc03d33d0a41075285948b/SynthText_Chinese/colorize3_poisson.py#L175-L187
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/python/debug/lib/debug_data.py
python
DebugDumpDir.set_python_graph
(self, python_graph)
Provide Python `Graph` object to the wrapper. Unlike the partition graphs, which are protobuf `GraphDef` objects, `Graph` is a Python object and carries additional information such as the traceback of the construction of the nodes in the graph. Args: python_graph: (ops.Graph) The Python Graph object.
Provide Python `Graph` object to the wrapper.
[ "Provide", "Python", "Graph", "object", "to", "the", "wrapper", "." ]
def set_python_graph(self, python_graph): """Provide Python `Graph` object to the wrapper. Unlike the partition graphs, which are protobuf `GraphDef` objects, `Graph` is a Python object and carries additional information such as the traceback of the construction of the nodes in the graph. Args: python_graph: (ops.Graph) The Python Graph object. """ self._python_graph = python_graph self._node_traceback = {} if self._python_graph: for op in self._python_graph.get_operations(): self._node_traceback[op.name] = op.traceback
[ "def", "set_python_graph", "(", "self", ",", "python_graph", ")", ":", "self", ".", "_python_graph", "=", "python_graph", "self", ".", "_node_traceback", "=", "{", "}", "if", "self", ".", "_python_graph", ":", "for", "op", "in", "self", ".", "_python_graph", ".", "get_operations", "(", ")", ":", "self", ".", "_node_traceback", "[", "op", ".", "name", "]", "=", "op", ".", "traceback" ]
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/python/debug/lib/debug_data.py#L853-L868
pytorch/pytorch
7176c92687d3cc847cc046bf002269c6949a21c2
torch/_sources.py
python
get_source_lines_and_file
( obj: Any, error_msg: Optional[str] = None, )
return sourcelines, file_lineno, filename
Wrapper around inspect.getsourcelines and inspect.getsourcefile. Returns: (sourcelines, file_lino, filename)
Wrapper around inspect.getsourcelines and inspect.getsourcefile.
[ "Wrapper", "around", "inspect", ".", "getsourcelines", "and", "inspect", ".", "getsourcefile", "." ]
def get_source_lines_and_file( obj: Any, error_msg: Optional[str] = None, ) -> Tuple[List[str], int, Optional[str]]: """ Wrapper around inspect.getsourcelines and inspect.getsourcefile. Returns: (sourcelines, file_lino, filename) """ filename = None # in case getsourcefile throws try: filename = inspect.getsourcefile(obj) sourcelines, file_lineno = inspect.getsourcelines(obj) except OSError as e: msg = (f"Can't get source for {obj}. TorchScript requires source access in " "order to carry out compilation, make sure original .py files are " "available.") if error_msg: msg += '\n' + error_msg raise OSError(msg) from e return sourcelines, file_lineno, filename
[ "def", "get_source_lines_and_file", "(", "obj", ":", "Any", ",", "error_msg", ":", "Optional", "[", "str", "]", "=", "None", ",", ")", "->", "Tuple", "[", "List", "[", "str", "]", ",", "int", ",", "Optional", "[", "str", "]", "]", ":", "filename", "=", "None", "# in case getsourcefile throws", "try", ":", "filename", "=", "inspect", ".", "getsourcefile", "(", "obj", ")", "sourcelines", ",", "file_lineno", "=", "inspect", ".", "getsourcelines", "(", "obj", ")", "except", "OSError", "as", "e", ":", "msg", "=", "(", "f\"Can't get source for {obj}. TorchScript requires source access in \"", "\"order to carry out compilation, make sure original .py files are \"", "\"available.\"", ")", "if", "error_msg", ":", "msg", "+=", "'\\n'", "+", "error_msg", "raise", "OSError", "(", "msg", ")", "from", "e", "return", "sourcelines", ",", "file_lineno", ",", "filename" ]
https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/torch/_sources.py#L9-L30
oracle/graaljs
36a56e8e993d45fc40939a3a4d9c0c24990720f1
graal-nodejs/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/MSVSSettings.py
python
_MovedAndRenamed
( tool, msvs_settings_name, msbuild_tool_name, msbuild_settings_name, setting_type )
Defines a setting that may have moved to a new section. Args: tool: a dictionary that gives the names of the tool for MSVS and MSBuild. msvs_settings_name: the MSVS name of the setting. msbuild_tool_name: the name of the MSBuild tool to place the setting under. msbuild_settings_name: the MSBuild name of the setting. setting_type: the type of this setting.
Defines a setting that may have moved to a new section.
[ "Defines", "a", "setting", "that", "may", "have", "moved", "to", "a", "new", "section", "." ]
def _MovedAndRenamed( tool, msvs_settings_name, msbuild_tool_name, msbuild_settings_name, setting_type ): """Defines a setting that may have moved to a new section. Args: tool: a dictionary that gives the names of the tool for MSVS and MSBuild. msvs_settings_name: the MSVS name of the setting. msbuild_tool_name: the name of the MSBuild tool to place the setting under. msbuild_settings_name: the MSBuild name of the setting. setting_type: the type of this setting. """ def _Translate(value, msbuild_settings): tool_settings = msbuild_settings.setdefault(msbuild_tool_name, {}) tool_settings[msbuild_settings_name] = setting_type.ConvertToMSBuild(value) _msvs_validators[tool.msvs_name][msvs_settings_name] = setting_type.ValidateMSVS validator = setting_type.ValidateMSBuild _msbuild_validators[msbuild_tool_name][msbuild_settings_name] = validator _msvs_to_msbuild_converters[tool.msvs_name][msvs_settings_name] = _Translate
[ "def", "_MovedAndRenamed", "(", "tool", ",", "msvs_settings_name", ",", "msbuild_tool_name", ",", "msbuild_settings_name", ",", "setting_type", ")", ":", "def", "_Translate", "(", "value", ",", "msbuild_settings", ")", ":", "tool_settings", "=", "msbuild_settings", ".", "setdefault", "(", "msbuild_tool_name", ",", "{", "}", ")", "tool_settings", "[", "msbuild_settings_name", "]", "=", "setting_type", ".", "ConvertToMSBuild", "(", "value", ")", "_msvs_validators", "[", "tool", ".", "msvs_name", "]", "[", "msvs_settings_name", "]", "=", "setting_type", ".", "ValidateMSVS", "validator", "=", "setting_type", ".", "ValidateMSBuild", "_msbuild_validators", "[", "msbuild_tool_name", "]", "[", "msbuild_settings_name", "]", "=", "validator", "_msvs_to_msbuild_converters", "[", "tool", ".", "msvs_name", "]", "[", "msvs_settings_name", "]", "=", "_Translate" ]
https://github.com/oracle/graaljs/blob/36a56e8e993d45fc40939a3a4d9c0c24990720f1/graal-nodejs/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/MSVSSettings.py#L270-L290
H-uru/Plasma
c2140ea046e82e9c199e257a7f2e7edb42602871
Scripts/Python/plasma/Plasma.py
python
PtEnableMouseMovement
()
Enable avatar mouse movement input
Enable avatar mouse movement input
[ "Enable", "avatar", "mouse", "movement", "input" ]
def PtEnableMouseMovement(): """Enable avatar mouse movement input""" pass
[ "def", "PtEnableMouseMovement", "(", ")", ":", "pass" ]
https://github.com/H-uru/Plasma/blob/c2140ea046e82e9c199e257a7f2e7edb42602871/Scripts/Python/plasma/Plasma.py#L254-L256
google/earthenterprise
0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9
earth_enterprise/src/server/wsgi/serve/snippets/util/dbroot_writer.py
python
_SetSnippets
(dbroot_proto, almost_snippet_values, log)
Writes the JSON snippet values into the dbroot_proto. We write individual paths instead of the whole tree at once, only because it's easier. Args: dbroot_proto: destination dbroot_proto almost_snippet_values: list of tuples of dbroot path, value. They're 'dense', ie the indexes of all repeated fields all start at 0 and are contiguous. log: logger object.
Writes the JSON snippet values into the dbroot_proto.
[ "Writes", "the", "JSON", "snippet", "values", "into", "the", "dbroot_proto", "." ]
def _SetSnippets(dbroot_proto, almost_snippet_values, log): """Writes the JSON snippet values into the dbroot_proto. We write individual paths instead of the whole tree at once, only because it's easier. Args: dbroot_proto: destination dbroot_proto almost_snippet_values: list of tuples of dbroot path, value. They're 'dense', ie the indexes of all repeated fields all start at 0 and are contiguous. log: logger object. """ log.debug(">_SetSnippets") true_snippet_values = _MassageSpecialCases(almost_snippet_values, log) true_snippet_values.sort() log.debug("aiming to set in dbroot:") for k, v in true_snippet_values: assert isinstance(true_snippet_values, list) assert isinstance(true_snippet_values[0], tuple) log.debug("snippet name:[%s], val:[%s]" % (k, str(v))) log.debug("debugged em all") for path, value in true_snippet_values: log.debug("path: %s value: %s" % (path, value)) log.debug("setting in binary...") proto_reflection.WritePathValsToDbroot( dbroot_proto, true_snippet_values, log) log.debug("...wrote") log.debug("<_SetSnippets")
[ "def", "_SetSnippets", "(", "dbroot_proto", ",", "almost_snippet_values", ",", "log", ")", ":", "log", ".", "debug", "(", "\">_SetSnippets\"", ")", "true_snippet_values", "=", "_MassageSpecialCases", "(", "almost_snippet_values", ",", "log", ")", "true_snippet_values", ".", "sort", "(", ")", "log", ".", "debug", "(", "\"aiming to set in dbroot:\"", ")", "for", "k", ",", "v", "in", "true_snippet_values", ":", "assert", "isinstance", "(", "true_snippet_values", ",", "list", ")", "assert", "isinstance", "(", "true_snippet_values", "[", "0", "]", ",", "tuple", ")", "log", ".", "debug", "(", "\"snippet name:[%s], val:[%s]\"", "%", "(", "k", ",", "str", "(", "v", ")", ")", ")", "log", ".", "debug", "(", "\"debugged em all\"", ")", "for", "path", ",", "value", "in", "true_snippet_values", ":", "log", ".", "debug", "(", "\"path: %s value: %s\"", "%", "(", "path", ",", "value", ")", ")", "log", ".", "debug", "(", "\"setting in binary...\"", ")", "proto_reflection", ".", "WritePathValsToDbroot", "(", "dbroot_proto", ",", "true_snippet_values", ",", "log", ")", "log", ".", "debug", "(", "\"...wrote\"", ")", "log", ".", "debug", "(", "\"<_SetSnippets\"", ")" ]
https://github.com/google/earthenterprise/blob/0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9/earth_enterprise/src/server/wsgi/serve/snippets/util/dbroot_writer.py#L143-L174
facebookresearch/mvfst-rl
778bc4259ae7277e67c2ead593a493845c93db83
train/utils.py
python
delete_dir
(dir_path, max_tries=1, sleep_time=1)
Delete a directory (with potential retry mechanism)
Delete a directory (with potential retry mechanism)
[ "Delete", "a", "directory", "(", "with", "potential", "retry", "mechanism", ")" ]
def delete_dir(dir_path, max_tries=1, sleep_time=1): """Delete a directory (with potential retry mechanism)""" if not os.path.exists(dir_path): return for i in range(max_tries): try: shutil.rmtree(dir_path) except Exception: if i == max_tries - 1: logging.warning("Failed to delete dir (giving up): %s", dir_path) break else: logging.info("Failed to delete dir (will try again): %s", dir_path) time.sleep(sleep_time) else: logging.info("Deleted dir: %s", dir_path) break
[ "def", "delete_dir", "(", "dir_path", ",", "max_tries", "=", "1", ",", "sleep_time", "=", "1", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "dir_path", ")", ":", "return", "for", "i", "in", "range", "(", "max_tries", ")", ":", "try", ":", "shutil", ".", "rmtree", "(", "dir_path", ")", "except", "Exception", ":", "if", "i", "==", "max_tries", "-", "1", ":", "logging", ".", "warning", "(", "\"Failed to delete dir (giving up): %s\"", ",", "dir_path", ")", "break", "else", ":", "logging", ".", "info", "(", "\"Failed to delete dir (will try again): %s\"", ",", "dir_path", ")", "time", ".", "sleep", "(", "sleep_time", ")", "else", ":", "logging", ".", "info", "(", "\"Deleted dir: %s\"", ",", "dir_path", ")", "break" ]
https://github.com/facebookresearch/mvfst-rl/blob/778bc4259ae7277e67c2ead593a493845c93db83/train/utils.py#L239-L256
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/ipython/py3/IPython/core/completerlib.py
python
reset_completer
(self, event)
return '-f -s in out array dhist'.split()
A completer for %reset magic
A completer for %reset magic
[ "A", "completer", "for", "%reset", "magic" ]
def reset_completer(self, event): "A completer for %reset magic" return '-f -s in out array dhist'.split()
[ "def", "reset_completer", "(", "self", ",", "event", ")", ":", "return", "'-f -s in out array dhist'", ".", "split", "(", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/ipython/py3/IPython/core/completerlib.py#L400-L402
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/numpy/py2/numpy/ma/core.py
python
left_shift
(a, n)
Shift the bits of an integer to the left. This is the masked array version of `numpy.left_shift`, for details see that function. See Also -------- numpy.left_shift
Shift the bits of an integer to the left.
[ "Shift", "the", "bits", "of", "an", "integer", "to", "the", "left", "." ]
def left_shift(a, n): """ Shift the bits of an integer to the left. This is the masked array version of `numpy.left_shift`, for details see that function. See Also -------- numpy.left_shift """ m = getmask(a) if m is nomask: d = umath.left_shift(filled(a), n) return masked_array(d) else: d = umath.left_shift(filled(a, 0), n) return masked_array(d, mask=m)
[ "def", "left_shift", "(", "a", ",", "n", ")", ":", "m", "=", "getmask", "(", "a", ")", "if", "m", "is", "nomask", ":", "d", "=", "umath", ".", "left_shift", "(", "filled", "(", "a", ")", ",", "n", ")", "return", "masked_array", "(", "d", ")", "else", ":", "d", "=", "umath", ".", "left_shift", "(", "filled", "(", "a", ",", "0", ")", ",", "n", ")", "return", "masked_array", "(", "d", ",", "mask", "=", "m", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py2/numpy/ma/core.py#L6812-L6830
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/setuptools/command/easy_install.py
python
ScriptWriter.get_header
(cls, script_text="", executable=None)
return cmd.as_header()
Create a #! line, getting options (if any) from script_text
Create a #! line, getting options (if any) from script_text
[ "Create", "a", "#!", "line", "getting", "options", "(", "if", "any", ")", "from", "script_text" ]
def get_header(cls, script_text="", executable=None): """Create a #! line, getting options (if any) from script_text""" cmd = cls.command_spec_class.best().from_param(executable) cmd.install_options(script_text) return cmd.as_header()
[ "def", "get_header", "(", "cls", ",", "script_text", "=", "\"\"", ",", "executable", "=", "None", ")", ":", "cmd", "=", "cls", ".", "command_spec_class", ".", "best", "(", ")", ".", "from_param", "(", "executable", ")", "cmd", ".", "install_options", "(", "script_text", ")", "return", "cmd", ".", "as_header", "(", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/setuptools/command/easy_install.py#L2155-L2159
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/prompt-toolkit/py2/prompt_toolkit/output.py
python
Output.cursor_down
(self, amount)
Move cursor `amount` place down.
Move cursor `amount` place down.
[ "Move", "cursor", "amount", "place", "down", "." ]
def cursor_down(self, amount): " Move cursor `amount` place down. "
[ "def", "cursor_down", "(", "self", ",", "amount", ")", ":" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/prompt-toolkit/py2/prompt_toolkit/output.py#L117-L118
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py3/pandas/tseries/holiday.py
python
AbstractHolidayCalendar.holidays
(self, start=None, end=None, return_name=False)
Returns a curve with holidays between start_date and end_date Parameters ---------- start : starting date, datetime-like, optional end : ending date, datetime-like, optional return_name : bool, optional If True, return a series that has dates and holiday names. False will only return a DatetimeIndex of dates. Returns ------- DatetimeIndex of holidays
Returns a curve with holidays between start_date and end_date
[ "Returns", "a", "curve", "with", "holidays", "between", "start_date", "and", "end_date" ]
def holidays(self, start=None, end=None, return_name=False): """ Returns a curve with holidays between start_date and end_date Parameters ---------- start : starting date, datetime-like, optional end : ending date, datetime-like, optional return_name : bool, optional If True, return a series that has dates and holiday names. False will only return a DatetimeIndex of dates. Returns ------- DatetimeIndex of holidays """ if self.rules is None: raise Exception( f"Holiday Calendar {self.name} does not have any rules specified" ) if start is None: start = AbstractHolidayCalendar.start_date if end is None: end = AbstractHolidayCalendar.end_date start = Timestamp(start) end = Timestamp(end) # If we don't have a cache or the dates are outside the prior cache, we # get them again if self._cache is None or start < self._cache[0] or end > self._cache[1]: pre_holidays = [ rule.dates(start, end, return_name=True) for rule in self.rules ] if pre_holidays: holidays = concat(pre_holidays) else: holidays = Series(index=DatetimeIndex([]), dtype=object) self._cache = (start, end, holidays.sort_index()) holidays = self._cache[2] holidays = holidays[start:end] if return_name: return holidays else: return holidays.index
[ "def", "holidays", "(", "self", ",", "start", "=", "None", ",", "end", "=", "None", ",", "return_name", "=", "False", ")", ":", "if", "self", ".", "rules", "is", "None", ":", "raise", "Exception", "(", "f\"Holiday Calendar {self.name} does not have any rules specified\"", ")", "if", "start", "is", "None", ":", "start", "=", "AbstractHolidayCalendar", ".", "start_date", "if", "end", "is", "None", ":", "end", "=", "AbstractHolidayCalendar", ".", "end_date", "start", "=", "Timestamp", "(", "start", ")", "end", "=", "Timestamp", "(", "end", ")", "# If we don't have a cache or the dates are outside the prior cache, we", "# get them again", "if", "self", ".", "_cache", "is", "None", "or", "start", "<", "self", ".", "_cache", "[", "0", "]", "or", "end", ">", "self", ".", "_cache", "[", "1", "]", ":", "pre_holidays", "=", "[", "rule", ".", "dates", "(", "start", ",", "end", ",", "return_name", "=", "True", ")", "for", "rule", "in", "self", ".", "rules", "]", "if", "pre_holidays", ":", "holidays", "=", "concat", "(", "pre_holidays", ")", "else", ":", "holidays", "=", "Series", "(", "index", "=", "DatetimeIndex", "(", "[", "]", ")", ",", "dtype", "=", "object", ")", "self", ".", "_cache", "=", "(", "start", ",", "end", ",", "holidays", ".", "sort_index", "(", ")", ")", "holidays", "=", "self", ".", "_cache", "[", "2", "]", "holidays", "=", "holidays", "[", "start", ":", "end", "]", "if", "return_name", ":", "return", "holidays", "else", ":", "return", "holidays", ".", "index" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/tseries/holiday.py#L420-L469
dicecco1/fpga_caffe
7a191704efd7873071cfef35772d7e7bf3e3cfd6
python/caffe/pycaffe.py
python
_Net_params
(self)
return self._params_dict
An OrderedDict (bottom to top, i.e., input to output) of network parameters indexed by name; each is a list of multiple blobs (e.g., weights and biases)
An OrderedDict (bottom to top, i.e., input to output) of network parameters indexed by name; each is a list of multiple blobs (e.g., weights and biases)
[ "An", "OrderedDict", "(", "bottom", "to", "top", "i", ".", "e", ".", "input", "to", "output", ")", "of", "network", "parameters", "indexed", "by", "name", ";", "each", "is", "a", "list", "of", "multiple", "blobs", "(", "e", ".", "g", ".", "weights", "and", "biases", ")" ]
def _Net_params(self): """ An OrderedDict (bottom to top, i.e., input to output) of network parameters indexed by name; each is a list of multiple blobs (e.g., weights and biases) """ if not hasattr(self, '_params_dict'): self._params_dict = OrderedDict([(name, lr.blobs) for name, lr in zip( self._layer_names, self.layers) if len(lr.blobs) > 0]) return self._params_dict
[ "def", "_Net_params", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'_params_dict'", ")", ":", "self", ".", "_params_dict", "=", "OrderedDict", "(", "[", "(", "name", ",", "lr", ".", "blobs", ")", "for", "name", ",", "lr", "in", "zip", "(", "self", ".", "_layer_names", ",", "self", ".", "layers", ")", "if", "len", "(", "lr", ".", "blobs", ")", ">", "0", "]", ")", "return", "self", ".", "_params_dict" ]
https://github.com/dicecco1/fpga_caffe/blob/7a191704efd7873071cfef35772d7e7bf3e3cfd6/python/caffe/pycaffe.py#L58-L69
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/idlelib/config_key.py
python
GetKeysDialog.keys_ok
(self, keys)
return False
Validity check on user's 'basic' keybinding selection. Doesn't check the string produced by the advanced dialog because 'modifiers' isn't set.
Validity check on user's 'basic' keybinding selection.
[ "Validity", "check", "on", "user", "s", "basic", "keybinding", "selection", "." ]
def keys_ok(self, keys): """Validity check on user's 'basic' keybinding selection. Doesn't check the string produced by the advanced dialog because 'modifiers' isn't set. """ final_key = self.list_keys_final.get('anchor') modifiers = self.get_modifiers() title = self.keyerror_title key_sequences = [key for keylist in self.current_key_sequences for key in keylist] if not keys.endswith('>'): self.showerror(title, parent=self, message='Missing the final Key') elif (not modifiers and final_key not in FUNCTION_KEYS + MOVE_KEYS): self.showerror(title=title, parent=self, message='No modifier key(s) specified.') elif (modifiers == ['Shift']) \ and (final_key not in FUNCTION_KEYS + MOVE_KEYS + ('Tab', 'Space')): msg = 'The shift modifier by itself may not be used with'\ ' this key symbol.' self.showerror(title=title, parent=self, message=msg) elif keys in key_sequences: msg = 'This key combination is already in use.' self.showerror(title=title, parent=self, message=msg) else: return True return False
[ "def", "keys_ok", "(", "self", ",", "keys", ")", ":", "final_key", "=", "self", ".", "list_keys_final", ".", "get", "(", "'anchor'", ")", "modifiers", "=", "self", ".", "get_modifiers", "(", ")", "title", "=", "self", ".", "keyerror_title", "key_sequences", "=", "[", "key", "for", "keylist", "in", "self", ".", "current_key_sequences", "for", "key", "in", "keylist", "]", "if", "not", "keys", ".", "endswith", "(", "'>'", ")", ":", "self", ".", "showerror", "(", "title", ",", "parent", "=", "self", ",", "message", "=", "'Missing the final Key'", ")", "elif", "(", "not", "modifiers", "and", "final_key", "not", "in", "FUNCTION_KEYS", "+", "MOVE_KEYS", ")", ":", "self", ".", "showerror", "(", "title", "=", "title", ",", "parent", "=", "self", ",", "message", "=", "'No modifier key(s) specified.'", ")", "elif", "(", "modifiers", "==", "[", "'Shift'", "]", ")", "and", "(", "final_key", "not", "in", "FUNCTION_KEYS", "+", "MOVE_KEYS", "+", "(", "'Tab'", ",", "'Space'", ")", ")", ":", "msg", "=", "'The shift modifier by itself may not be used with'", "' this key symbol.'", "self", ".", "showerror", "(", "title", "=", "title", ",", "parent", "=", "self", ",", "message", "=", "msg", ")", "elif", "keys", "in", "key_sequences", ":", "msg", "=", "'This key combination is already in use.'", "self", ".", "showerror", "(", "title", "=", "title", ",", "parent", "=", "self", ",", "message", "=", "msg", ")", "else", ":", "return", "True", "return", "False" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/idlelib/config_key.py#L274-L303
Z3Prover/z3
d745d03afdfdf638d66093e2bfbacaf87187f35b
src/api/python/z3/z3num.py
python
Numeral.power
(self, k)
return Numeral(Z3_algebraic_power(self.ctx_ref(), self.ast, k), self.ctx)
Return the numeral `self^k`. >>> sqrt3 = Numeral(3).root(2) >>> sqrt3 1.7320508075? >>> sqrt3.power(2) 3
Return the numeral `self^k`.
[ "Return", "the", "numeral", "self^k", "." ]
def power(self, k): """ Return the numeral `self^k`. >>> sqrt3 = Numeral(3).root(2) >>> sqrt3 1.7320508075? >>> sqrt3.power(2) 3 """ return Numeral(Z3_algebraic_power(self.ctx_ref(), self.ast, k), self.ctx)
[ "def", "power", "(", "self", ",", "k", ")", ":", "return", "Numeral", "(", "Z3_algebraic_power", "(", "self", ".", "ctx_ref", "(", ")", ",", "self", ".", "ast", ",", "k", ")", ",", "self", ".", "ctx", ")" ]
https://github.com/Z3Prover/z3/blob/d745d03afdfdf638d66093e2bfbacaf87187f35b/src/api/python/z3/z3num.py#L383-L392
opengauss-mirror/openGauss-server
e383f1b77720a00ddbe4c0655bc85914d9b02a2b
src/gausskernel/dbmind/tools/ai_manager/module/anomaly_detection/install.py
python
Installer.try_to_kill_process_exist
(self)
Try to kill process, if already exist
Try to kill process, if already exist
[ "Try", "to", "kill", "process", "if", "already", "exist" ]
def try_to_kill_process_exist(self): """ Try to kill process, if already exist """ script_path = os.path.realpath( os.path.join(self.install_path, Constant.ANORMALY_MAIN_SCRIPT)) process_list = [(cmd % (Constant.CMD_PREFIX, os.path.dirname(script_path), script_path) ).split(self.version)[-1] for cmd in self.service_list] for process in process_list: process_num = CommonTools.check_process(process) if process_num: CommonTools.grep_process_and_kill(process) g.logger.info('Killed process of [%s]' % process)
[ "def", "try_to_kill_process_exist", "(", "self", ")", ":", "script_path", "=", "os", ".", "path", ".", "realpath", "(", "os", ".", "path", ".", "join", "(", "self", ".", "install_path", ",", "Constant", ".", "ANORMALY_MAIN_SCRIPT", ")", ")", "process_list", "=", "[", "(", "cmd", "%", "(", "Constant", ".", "CMD_PREFIX", ",", "os", ".", "path", ".", "dirname", "(", "script_path", ")", ",", "script_path", ")", ")", ".", "split", "(", "self", ".", "version", ")", "[", "-", "1", "]", "for", "cmd", "in", "self", ".", "service_list", "]", "for", "process", "in", "process_list", ":", "process_num", "=", "CommonTools", ".", "check_process", "(", "process", ")", "if", "process_num", ":", "CommonTools", ".", "grep_process_and_kill", "(", "process", ")", "g", ".", "logger", ".", "info", "(", "'Killed process of [%s]'", "%", "process", ")" ]
https://github.com/opengauss-mirror/openGauss-server/blob/e383f1b77720a00ddbe4c0655bc85914d9b02a2b/src/gausskernel/dbmind/tools/ai_manager/module/anomaly_detection/install.py#L159-L171
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/docview.py
python
Document.GetWriteable
(self)
Returns true if the document can be written to its accociated file path. This method has been added to wxPython and is not in wxWindows.
Returns true if the document can be written to its accociated file path. This method has been added to wxPython and is not in wxWindows.
[ "Returns", "true", "if", "the", "document", "can", "be", "written", "to", "its", "accociated", "file", "path", ".", "This", "method", "has", "been", "added", "to", "wxPython", "and", "is", "not", "in", "wxWindows", "." ]
def GetWriteable(self): """ Returns true if the document can be written to its accociated file path. This method has been added to wxPython and is not in wxWindows. """ if not self._writeable: return False if not self._documentFile: # Doesn't exist, do a save as return True else: return os.access(self._documentFile, os.W_OK)
[ "def", "GetWriteable", "(", "self", ")", ":", "if", "not", "self", ".", "_writeable", ":", "return", "False", "if", "not", "self", ".", "_documentFile", ":", "# Doesn't exist, do a save as", "return", "True", "else", ":", "return", "os", ".", "access", "(", "self", ".", "_documentFile", ",", "os", ".", "W_OK", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/docview.py#L747-L757
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_controls.py
python
TextAttr.HasFontSize
(*args, **kwargs)
return _controls_.TextAttr_HasFontSize(*args, **kwargs)
HasFontSize(self) -> bool
HasFontSize(self) -> bool
[ "HasFontSize", "(", "self", ")", "-", ">", "bool" ]
def HasFontSize(*args, **kwargs): """HasFontSize(self) -> bool""" return _controls_.TextAttr_HasFontSize(*args, **kwargs)
[ "def", "HasFontSize", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_controls_", ".", "TextAttr_HasFontSize", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_controls.py#L1796-L1798
google/skia
82d65d0487bd72f5f7332d002429ec2dc61d2463
infra/bots/assets/chromebook_x86_64_gles/create.py
python
create_asset
(target_dir, gl_path)
Create the asset.
Create the asset.
[ "Create", "the", "asset", "." ]
def create_asset(target_dir, gl_path): """Create the asset.""" cmd = [ 'sudo','apt-get','install', 'libgles2-mesa-dev', 'libegl1-mesa-dev' ] subprocess.check_call(cmd) lib_dir = os.path.join(target_dir, 'lib') os.mkdir(lib_dir) to_copy = glob.glob(os.path.join(gl_path,'libGL*')) to_copy.extend(glob.glob(os.path.join(gl_path,'libEGL*'))) to_copy.extend(glob.glob(os.path.join(gl_path,'libdrm*'))) for f in to_copy: shutil.copy(f, lib_dir) include_dir = os.path.join(target_dir, 'include') os.mkdir(include_dir) shutil.copytree('/usr/include/EGL', os.path.join(include_dir, 'EGL')) shutil.copytree('/usr/include/KHR', os.path.join(include_dir, 'KHR')) shutil.copytree('/usr/include/GLES2', os.path.join(include_dir, 'GLES2')) shutil.copytree('/usr/include/GLES3', os.path.join(include_dir, 'GLES3'))
[ "def", "create_asset", "(", "target_dir", ",", "gl_path", ")", ":", "cmd", "=", "[", "'sudo'", ",", "'apt-get'", ",", "'install'", ",", "'libgles2-mesa-dev'", ",", "'libegl1-mesa-dev'", "]", "subprocess", ".", "check_call", "(", "cmd", ")", "lib_dir", "=", "os", ".", "path", ".", "join", "(", "target_dir", ",", "'lib'", ")", "os", ".", "mkdir", "(", "lib_dir", ")", "to_copy", "=", "glob", ".", "glob", "(", "os", ".", "path", ".", "join", "(", "gl_path", ",", "'libGL*'", ")", ")", "to_copy", ".", "extend", "(", "glob", ".", "glob", "(", "os", ".", "path", ".", "join", "(", "gl_path", ",", "'libEGL*'", ")", ")", ")", "to_copy", ".", "extend", "(", "glob", ".", "glob", "(", "os", ".", "path", ".", "join", "(", "gl_path", ",", "'libdrm*'", ")", ")", ")", "for", "f", "in", "to_copy", ":", "shutil", ".", "copy", "(", "f", ",", "lib_dir", ")", "include_dir", "=", "os", ".", "path", ".", "join", "(", "target_dir", ",", "'include'", ")", "os", ".", "mkdir", "(", "include_dir", ")", "shutil", ".", "copytree", "(", "'/usr/include/EGL'", ",", "os", ".", "path", ".", "join", "(", "include_dir", ",", "'EGL'", ")", ")", "shutil", ".", "copytree", "(", "'/usr/include/KHR'", ",", "os", ".", "path", ".", "join", "(", "include_dir", ",", "'KHR'", ")", ")", "shutil", ".", "copytree", "(", "'/usr/include/GLES2'", ",", "os", ".", "path", ".", "join", "(", "include_dir", ",", "'GLES2'", ")", ")", "shutil", ".", "copytree", "(", "'/usr/include/GLES3'", ",", "os", ".", "path", ".", "join", "(", "include_dir", ",", "'GLES3'", ")", ")" ]
https://github.com/google/skia/blob/82d65d0487bd72f5f7332d002429ec2dc61d2463/infra/bots/assets/chromebook_x86_64_gles/create.py#L33-L58
deeplearningais/CUV
4e920ad1304af9de3e5f755cc2e9c5c96e06c324
examples/rbm/base.py
python
RBMStack.run
(self, iterstart, itermax, mbatch_provider)
Trains all levels of the RBM stack for itermax epochs. Lowest-level data comes from mbatch_provider.
Trains all levels of the RBM stack for itermax epochs. Lowest-level data comes from mbatch_provider.
[ "Trains", "all", "levels", "of", "the", "RBM", "stack", "for", "itermax", "epochs", ".", "Lowest", "-", "level", "data", "comes", "from", "mbatch_provider", "." ]
def run(self, iterstart, itermax, mbatch_provider): """ Trains all levels of the RBM stack for itermax epochs. Lowest-level data comes from mbatch_provider. """ self.mbp = mbatch_provider self.err = [] for layer in xrange( self.cfg.num_layers-1 ): if layer >= self.cfg.continue_learning-1: try: self.trainLayer(mbatch_provider, iterstart, itermax, layer) print "Finished Layer ", layer except KeyboardInterrupt: mbatch_provider.forgetOriginalData() print "Stopping training of layer %d" % layer finally: self.saveLayer(layer, self.cfg.workdir, "-pretrain") if layer < self.cfg.num_layers-2: mbatch_provider = self.getHiddenRep(layer, mbatch_provider) print "Got ", len(mbatch_provider.dataset), "batches"
[ "def", "run", "(", "self", ",", "iterstart", ",", "itermax", ",", "mbatch_provider", ")", ":", "self", ".", "mbp", "=", "mbatch_provider", "self", ".", "err", "=", "[", "]", "for", "layer", "in", "xrange", "(", "self", ".", "cfg", ".", "num_layers", "-", "1", ")", ":", "if", "layer", ">=", "self", ".", "cfg", ".", "continue_learning", "-", "1", ":", "try", ":", "self", ".", "trainLayer", "(", "mbatch_provider", ",", "iterstart", ",", "itermax", ",", "layer", ")", "print", "\"Finished Layer \"", ",", "layer", "except", "KeyboardInterrupt", ":", "mbatch_provider", ".", "forgetOriginalData", "(", ")", "print", "\"Stopping training of layer %d\"", "%", "layer", "finally", ":", "self", ".", "saveLayer", "(", "layer", ",", "self", ".", "cfg", ".", "workdir", ",", "\"-pretrain\"", ")", "if", "layer", "<", "self", ".", "cfg", ".", "num_layers", "-", "2", ":", "mbatch_provider", "=", "self", ".", "getHiddenRep", "(", "layer", ",", "mbatch_provider", ")", "print", "\"Got \"", ",", "len", "(", "mbatch_provider", ".", "dataset", ")", ",", "\"batches\"" ]
https://github.com/deeplearningais/CUV/blob/4e920ad1304af9de3e5f755cc2e9c5c96e06c324/examples/rbm/base.py#L317-L333
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemFramework/v1/AWS/common-code/lib/requests/models.py
python
Response.iter_lines
(self, chunk_size=ITER_CHUNK_SIZE, decode_unicode=False, delimiter=None)
Iterates over the response data, one line at a time. When stream=True is set on the request, this avoids reading the content at once into memory for large responses. .. note:: This method is not reentrant safe.
Iterates over the response data, one line at a time. When stream=True is set on the request, this avoids reading the content at once into memory for large responses.
[ "Iterates", "over", "the", "response", "data", "one", "line", "at", "a", "time", ".", "When", "stream", "=", "True", "is", "set", "on", "the", "request", "this", "avoids", "reading", "the", "content", "at", "once", "into", "memory", "for", "large", "responses", "." ]
def iter_lines(self, chunk_size=ITER_CHUNK_SIZE, decode_unicode=False, delimiter=None): """Iterates over the response data, one line at a time. When stream=True is set on the request, this avoids reading the content at once into memory for large responses. .. note:: This method is not reentrant safe. """ pending = None for chunk in self.iter_content(chunk_size=chunk_size, decode_unicode=decode_unicode): if pending is not None: chunk = pending + chunk if delimiter: lines = chunk.split(delimiter) else: lines = chunk.splitlines() if lines and lines[-1] and chunk and lines[-1][-1] == chunk[-1]: pending = lines.pop() else: pending = None for line in lines: yield line if pending is not None: yield pending
[ "def", "iter_lines", "(", "self", ",", "chunk_size", "=", "ITER_CHUNK_SIZE", ",", "decode_unicode", "=", "False", ",", "delimiter", "=", "None", ")", ":", "pending", "=", "None", "for", "chunk", "in", "self", ".", "iter_content", "(", "chunk_size", "=", "chunk_size", ",", "decode_unicode", "=", "decode_unicode", ")", ":", "if", "pending", "is", "not", "None", ":", "chunk", "=", "pending", "+", "chunk", "if", "delimiter", ":", "lines", "=", "chunk", ".", "split", "(", "delimiter", ")", "else", ":", "lines", "=", "chunk", ".", "splitlines", "(", ")", "if", "lines", "and", "lines", "[", "-", "1", "]", "and", "chunk", "and", "lines", "[", "-", "1", "]", "[", "-", "1", "]", "==", "chunk", "[", "-", "1", "]", ":", "pending", "=", "lines", ".", "pop", "(", ")", "else", ":", "pending", "=", "None", "for", "line", "in", "lines", ":", "yield", "line", "if", "pending", "is", "not", "None", ":", "yield", "pending" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/AWS/common-code/lib/requests/models.py#L785-L814
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pyparsing/py2/pyparsing.py
python
ParserElement.enablePackrat
(cache_size_limit=128)
Enables "packrat" parsing, which adds memoizing to the parsing logic. Repeated parse attempts at the same string location (which happens often in many complex grammars) can immediately return a cached value, instead of re-executing parsing/validating code. Memoizing is done of both valid results and parsing exceptions. Parameters: - cache_size_limit - (default= ``128``) - if an integer value is provided will limit the size of the packrat cache; if None is passed, then the cache size will be unbounded; if 0 is passed, the cache will be effectively disabled. This speedup may break existing programs that use parse actions that have side-effects. For this reason, packrat parsing is disabled when you first import pyparsing. To activate the packrat feature, your program must call the class method :class:`ParserElement.enablePackrat`. For best results, call ``enablePackrat()`` immediately after importing pyparsing. Example:: import pyparsing pyparsing.ParserElement.enablePackrat()
Enables "packrat" parsing, which adds memoizing to the parsing logic. Repeated parse attempts at the same string location (which happens often in many complex grammars) can immediately return a cached value, instead of re-executing parsing/validating code. Memoizing is done of both valid results and parsing exceptions.
[ "Enables", "packrat", "parsing", "which", "adds", "memoizing", "to", "the", "parsing", "logic", ".", "Repeated", "parse", "attempts", "at", "the", "same", "string", "location", "(", "which", "happens", "often", "in", "many", "complex", "grammars", ")", "can", "immediately", "return", "a", "cached", "value", "instead", "of", "re", "-", "executing", "parsing", "/", "validating", "code", ".", "Memoizing", "is", "done", "of", "both", "valid", "results", "and", "parsing", "exceptions", "." ]
def enablePackrat(cache_size_limit=128): """Enables "packrat" parsing, which adds memoizing to the parsing logic. Repeated parse attempts at the same string location (which happens often in many complex grammars) can immediately return a cached value, instead of re-executing parsing/validating code. Memoizing is done of both valid results and parsing exceptions. Parameters: - cache_size_limit - (default= ``128``) - if an integer value is provided will limit the size of the packrat cache; if None is passed, then the cache size will be unbounded; if 0 is passed, the cache will be effectively disabled. This speedup may break existing programs that use parse actions that have side-effects. For this reason, packrat parsing is disabled when you first import pyparsing. To activate the packrat feature, your program must call the class method :class:`ParserElement.enablePackrat`. For best results, call ``enablePackrat()`` immediately after importing pyparsing. Example:: import pyparsing pyparsing.ParserElement.enablePackrat() """ if not ParserElement._packratEnabled: ParserElement._packratEnabled = True if cache_size_limit is None: ParserElement.packrat_cache = ParserElement._UnboundedCache() else: ParserElement.packrat_cache = ParserElement._FifoCache(cache_size_limit) ParserElement._parse = ParserElement._parseCache
[ "def", "enablePackrat", "(", "cache_size_limit", "=", "128", ")", ":", "if", "not", "ParserElement", ".", "_packratEnabled", ":", "ParserElement", ".", "_packratEnabled", "=", "True", "if", "cache_size_limit", "is", "None", ":", "ParserElement", ".", "packrat_cache", "=", "ParserElement", ".", "_UnboundedCache", "(", ")", "else", ":", "ParserElement", ".", "packrat_cache", "=", "ParserElement", ".", "_FifoCache", "(", "cache_size_limit", ")", "ParserElement", ".", "_parse", "=", "ParserElement", ".", "_parseCache" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pyparsing/py2/pyparsing.py#L1867-L1899
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/AWSPythonSDK/1.5.8/docutils/parsers/rst/tableparser.py
python
SimpleTableParser.parse_table
(self)
First determine the column boundaries from the top border, then process rows. Each row may consist of multiple lines; accumulate lines until a row is complete. Call `self.parse_row` to finish the job.
First determine the column boundaries from the top border, then process rows. Each row may consist of multiple lines; accumulate lines until a row is complete. Call `self.parse_row` to finish the job.
[ "First", "determine", "the", "column", "boundaries", "from", "the", "top", "border", "then", "process", "rows", ".", "Each", "row", "may", "consist", "of", "multiple", "lines", ";", "accumulate", "lines", "until", "a", "row", "is", "complete", ".", "Call", "self", ".", "parse_row", "to", "finish", "the", "job", "." ]
def parse_table(self): """ First determine the column boundaries from the top border, then process rows. Each row may consist of multiple lines; accumulate lines until a row is complete. Call `self.parse_row` to finish the job. """ # Top border must fully describe all table columns. self.columns = self.parse_columns(self.block[0], 0) self.border_end = self.columns[-1][1] firststart, firstend = self.columns[0] offset = 1 # skip top border start = 1 text_found = None while offset < len(self.block): line = self.block[offset] if self.span_pat.match(line): # Column span underline or border; row is complete. self.parse_row(self.block[start:offset], start, (line.rstrip(), offset)) start = offset + 1 text_found = None elif line[firststart:firstend].strip(): # First column not blank, therefore it's a new row. if text_found and offset != start: self.parse_row(self.block[start:offset], start) start = offset text_found = 1 elif not text_found: start = offset + 1 offset += 1
[ "def", "parse_table", "(", "self", ")", ":", "# Top border must fully describe all table columns.", "self", ".", "columns", "=", "self", ".", "parse_columns", "(", "self", ".", "block", "[", "0", "]", ",", "0", ")", "self", ".", "border_end", "=", "self", ".", "columns", "[", "-", "1", "]", "[", "1", "]", "firststart", ",", "firstend", "=", "self", ".", "columns", "[", "0", "]", "offset", "=", "1", "# skip top border", "start", "=", "1", "text_found", "=", "None", "while", "offset", "<", "len", "(", "self", ".", "block", ")", ":", "line", "=", "self", ".", "block", "[", "offset", "]", "if", "self", ".", "span_pat", ".", "match", "(", "line", ")", ":", "# Column span underline or border; row is complete.", "self", ".", "parse_row", "(", "self", ".", "block", "[", "start", ":", "offset", "]", ",", "start", ",", "(", "line", ".", "rstrip", "(", ")", ",", "offset", ")", ")", "start", "=", "offset", "+", "1", "text_found", "=", "None", "elif", "line", "[", "firststart", ":", "firstend", "]", ".", "strip", "(", ")", ":", "# First column not blank, therefore it's a new row.", "if", "text_found", "and", "offset", "!=", "start", ":", "self", ".", "parse_row", "(", "self", ".", "block", "[", "start", ":", "offset", "]", ",", "start", ")", "start", "=", "offset", "text_found", "=", "1", "elif", "not", "text_found", ":", "start", "=", "offset", "+", "1", "offset", "+=", "1" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/AWSPythonSDK/1.5.8/docutils/parsers/rst/tableparser.py#L392-L422
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/ReflectometryISISLoadAndProcess.py
python
ReflectometryISISLoadAndProcess.validateInputs
(self)
return issues
Return a dictionary containing issues found in properties.
Return a dictionary containing issues found in properties.
[ "Return", "a", "dictionary", "containing", "issues", "found", "in", "properties", "." ]
def validateInputs(self): """Return a dictionary containing issues found in properties.""" issues = dict() if len(self.getProperty(Prop.RUNS).value) > 1 and self.getProperty(Prop.SLICE).value: issues[Prop.SLICE] = "Cannot perform slicing when summing multiple input runs" return issues
[ "def", "validateInputs", "(", "self", ")", ":", "issues", "=", "dict", "(", ")", "if", "len", "(", "self", ".", "getProperty", "(", "Prop", ".", "RUNS", ")", ".", "value", ")", ">", "1", "and", "self", ".", "getProperty", "(", "Prop", ".", "SLICE", ")", ".", "value", ":", "issues", "[", "Prop", ".", "SLICE", "]", "=", "\"Cannot perform slicing when summing multiple input runs\"", "return", "issues" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/ReflectometryISISLoadAndProcess.py#L111-L116
apache/mesos
97d9a4063332aae3825d78de71611657e05cf5e2
support/cpplint.py
python
_CppLintState.SetVerboseLevel
(self, level)
return last_verbose_level
Sets the module's verbosity, and returns the previous setting.
Sets the module's verbosity, and returns the previous setting.
[ "Sets", "the", "module", "s", "verbosity", "and", "returns", "the", "previous", "setting", "." ]
def SetVerboseLevel(self, level): """Sets the module's verbosity, and returns the previous setting.""" last_verbose_level = self.verbose_level self.verbose_level = level return last_verbose_level
[ "def", "SetVerboseLevel", "(", "self", ",", "level", ")", ":", "last_verbose_level", "=", "self", ".", "verbose_level", "self", ".", "verbose_level", "=", "level", "return", "last_verbose_level" ]
https://github.com/apache/mesos/blob/97d9a4063332aae3825d78de71611657e05cf5e2/support/cpplint.py#L896-L900
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/cuda/kernels/reduction.py
python
Reduce.__init__
(self, functor)
Create a reduction object that reduces values using a given binary function. The binary function is compiled once and cached inside this object. Keeping this object alive will prevent re-compilation. :param binop: A function to be compiled as a CUDA device function that will be used as the binary operation for reduction on a CUDA device. Internally, it is compiled using ``cuda.jit(device=True)``.
Create a reduction object that reduces values using a given binary function. The binary function is compiled once and cached inside this object. Keeping this object alive will prevent re-compilation.
[ "Create", "a", "reduction", "object", "that", "reduces", "values", "using", "a", "given", "binary", "function", ".", "The", "binary", "function", "is", "compiled", "once", "and", "cached", "inside", "this", "object", ".", "Keeping", "this", "object", "alive", "will", "prevent", "re", "-", "compilation", "." ]
def __init__(self, functor): """Create a reduction object that reduces values using a given binary function. The binary function is compiled once and cached inside this object. Keeping this object alive will prevent re-compilation. :param binop: A function to be compiled as a CUDA device function that will be used as the binary operation for reduction on a CUDA device. Internally, it is compiled using ``cuda.jit(device=True)``. """ self._functor = functor
[ "def", "__init__", "(", "self", ",", "functor", ")", ":", "self", ".", "_functor", "=", "functor" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/cuda/kernels/reduction.py#L166-L176
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/richtext.py
python
TextAttrBorder.HasWidth
(*args, **kwargs)
return _richtext.TextAttrBorder_HasWidth(*args, **kwargs)
HasWidth(self) -> bool
HasWidth(self) -> bool
[ "HasWidth", "(", "self", ")", "-", ">", "bool" ]
def HasWidth(*args, **kwargs): """HasWidth(self) -> bool""" return _richtext.TextAttrBorder_HasWidth(*args, **kwargs)
[ "def", "HasWidth", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_richtext", ".", "TextAttrBorder_HasWidth", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/richtext.py#L394-L396
PaddlePaddle/PaddleOCR
b756bf5f8c90142e0d89d3db0163965c686b6ffe
ppocr/utils/e2e_utils/visual.py
python
expand_poly_along_width
(poly, shrink_ratio_of_width=0.3)
return poly
expand poly along width.
expand poly along width.
[ "expand", "poly", "along", "width", "." ]
def expand_poly_along_width(poly, shrink_ratio_of_width=0.3): """ expand poly along width. """ point_num = poly.shape[0] left_quad = np.array( [poly[0], poly[1], poly[-2], poly[-1]], dtype=np.float32) left_ratio = -shrink_ratio_of_width * np.linalg.norm(left_quad[0] - left_quad[3]) / \ (np.linalg.norm(left_quad[0] - left_quad[1]) + 1e-6) left_quad_expand = shrink_quad_along_width(left_quad, left_ratio, 1.0) right_quad = np.array( [ poly[point_num // 2 - 2], poly[point_num // 2 - 1], poly[point_num // 2], poly[point_num // 2 + 1] ], dtype=np.float32) right_ratio = 1.0 + \ shrink_ratio_of_width * np.linalg.norm(right_quad[0] - right_quad[3]) / \ (np.linalg.norm(right_quad[0] - right_quad[1]) + 1e-6) right_quad_expand = shrink_quad_along_width(right_quad, 0.0, right_ratio) poly[0] = left_quad_expand[0] poly[-1] = left_quad_expand[-1] poly[point_num // 2 - 1] = right_quad_expand[1] poly[point_num // 2] = right_quad_expand[2] return poly
[ "def", "expand_poly_along_width", "(", "poly", ",", "shrink_ratio_of_width", "=", "0.3", ")", ":", "point_num", "=", "poly", ".", "shape", "[", "0", "]", "left_quad", "=", "np", ".", "array", "(", "[", "poly", "[", "0", "]", ",", "poly", "[", "1", "]", ",", "poly", "[", "-", "2", "]", ",", "poly", "[", "-", "1", "]", "]", ",", "dtype", "=", "np", ".", "float32", ")", "left_ratio", "=", "-", "shrink_ratio_of_width", "*", "np", ".", "linalg", ".", "norm", "(", "left_quad", "[", "0", "]", "-", "left_quad", "[", "3", "]", ")", "/", "(", "np", ".", "linalg", ".", "norm", "(", "left_quad", "[", "0", "]", "-", "left_quad", "[", "1", "]", ")", "+", "1e-6", ")", "left_quad_expand", "=", "shrink_quad_along_width", "(", "left_quad", ",", "left_ratio", ",", "1.0", ")", "right_quad", "=", "np", ".", "array", "(", "[", "poly", "[", "point_num", "//", "2", "-", "2", "]", ",", "poly", "[", "point_num", "//", "2", "-", "1", "]", ",", "poly", "[", "point_num", "//", "2", "]", ",", "poly", "[", "point_num", "//", "2", "+", "1", "]", "]", ",", "dtype", "=", "np", ".", "float32", ")", "right_ratio", "=", "1.0", "+", "shrink_ratio_of_width", "*", "np", ".", "linalg", ".", "norm", "(", "right_quad", "[", "0", "]", "-", "right_quad", "[", "3", "]", ")", "/", "(", "np", ".", "linalg", ".", "norm", "(", "right_quad", "[", "0", "]", "-", "right_quad", "[", "1", "]", ")", "+", "1e-6", ")", "right_quad_expand", "=", "shrink_quad_along_width", "(", "right_quad", ",", "0.0", ",", "right_ratio", ")", "poly", "[", "0", "]", "=", "left_quad_expand", "[", "0", "]", "poly", "[", "-", "1", "]", "=", "left_quad_expand", "[", "-", "1", "]", "poly", "[", "point_num", "//", "2", "-", "1", "]", "=", "right_quad_expand", "[", "1", "]", "poly", "[", "point_num", "//", "2", "]", "=", "right_quad_expand", "[", "2", "]", "return", "poly" ]
https://github.com/PaddlePaddle/PaddleOCR/blob/b756bf5f8c90142e0d89d3db0163965c686b6ffe/ppocr/utils/e2e_utils/visual.py#L128-L152
sphinxsearch/sphinx
409f2c2b5b2ff70b04e38f92b6b1a890326bad65
api/sphinxapi.py
python
SphinxClient.Status
( self, session=False )
return res
Get the status
Get the status
[ "Get", "the", "status" ]
def Status ( self, session=False ): """ Get the status """ # connect, send query, get response sock = self._Connect() if not sock: return None sess = 1 if session: sess = 0 req = pack ( '>2HLL', SEARCHD_COMMAND_STATUS, VER_COMMAND_STATUS, 4, sess ) self._Send ( sock, req ) response = self._GetResponse ( sock, VER_COMMAND_STATUS ) if not response: return None # parse response res = [] p = 8 max_ = len(response) while p<max_: length = unpack ( '>L', response[p:p+4] )[0] k = response[p+4:p+length+4] p += 4+length length = unpack ( '>L', response[p:p+4] )[0] v = response[p+4:p+length+4] p += 4+length res += [[bytes_str(k), bytes_str(v)]] return res
[ "def", "Status", "(", "self", ",", "session", "=", "False", ")", ":", "# connect, send query, get response", "sock", "=", "self", ".", "_Connect", "(", ")", "if", "not", "sock", ":", "return", "None", "sess", "=", "1", "if", "session", ":", "sess", "=", "0", "req", "=", "pack", "(", "'>2HLL'", ",", "SEARCHD_COMMAND_STATUS", ",", "VER_COMMAND_STATUS", ",", "4", ",", "sess", ")", "self", ".", "_Send", "(", "sock", ",", "req", ")", "response", "=", "self", ".", "_GetResponse", "(", "sock", ",", "VER_COMMAND_STATUS", ")", "if", "not", "response", ":", "return", "None", "# parse response", "res", "=", "[", "]", "p", "=", "8", "max_", "=", "len", "(", "response", ")", "while", "p", "<", "max_", ":", "length", "=", "unpack", "(", "'>L'", ",", "response", "[", "p", ":", "p", "+", "4", "]", ")", "[", "0", "]", "k", "=", "response", "[", "p", "+", "4", ":", "p", "+", "length", "+", "4", "]", "p", "+=", "4", "+", "length", "length", "=", "unpack", "(", "'>L'", ",", "response", "[", "p", ":", "p", "+", "4", "]", ")", "[", "0", "]", "v", "=", "response", "[", "p", "+", "4", ":", "p", "+", "length", "+", "4", "]", "p", "+=", "4", "+", "length", "res", "+=", "[", "[", "bytes_str", "(", "k", ")", ",", "bytes_str", "(", "v", ")", "]", "]", "return", "res" ]
https://github.com/sphinxsearch/sphinx/blob/409f2c2b5b2ff70b04e38f92b6b1a890326bad65/api/sphinxapi.py#L1199-L1235
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/lmbr_aws/cleanup_utils/cleanup_s3_utils.py
python
_clean_s3_bucket
(cleaner, bucket_name)
Deletes all object dependencies in a bucket. The delete function is unique in that it deletes objects in batches. :param cleaner: A Cleaner object from the main cleanup.py script :param bucket_name: The name of the s3 bucket to clean. :return:
Deletes all object dependencies in a bucket. The delete function is unique in that it deletes objects in batches. :param cleaner: A Cleaner object from the main cleanup.py script :param bucket_name: The name of the s3 bucket to clean. :return:
[ "Deletes", "all", "object", "dependencies", "in", "a", "bucket", ".", "The", "delete", "function", "is", "unique", "in", "that", "it", "deletes", "objects", "in", "batches", ".", ":", "param", "cleaner", ":", "A", "Cleaner", "object", "from", "the", "main", "cleanup", ".", "py", "script", ":", "param", "bucket_name", ":", "The", "name", "of", "the", "s3", "bucket", "to", "clean", ".", ":", "return", ":" ]
def _clean_s3_bucket(cleaner, bucket_name): """ Deletes all object dependencies in a bucket. The delete function is unique in that it deletes objects in batches. :param cleaner: A Cleaner object from the main cleanup.py script :param bucket_name: The name of the s3 bucket to clean. :return: """ print(' cleaning bucket {}'.format(bucket_name)) # Get the first batch try: response = cleaner.s3.list_object_versions(Bucket=bucket_name, MaxKeys=1000) except ClientError as e: print(' ERROR: Unexpected error while trying to gather s3 object versions. {}'.format(e)) code = e.response['Error']['Code'] if code != "NoSuchBucket": cleaner.add_to_failed_resources('s3', bucket_name) return # Deleting objects in batches is capped at 1000 objects, therefore we can't construct the entire list beforehand delete_verification_list = [] while True: delete_list = [] for version in response.get('Versions', []): delete_list.append({'Key': version['Key'], 'VersionId': version['VersionId']}) for marker in response.get('DeleteMarkers', []): delete_list.append({'Key': marker['Key'], 'VersionId': marker['VersionId']}) delete_verification_list.extend(delete_list) try: cleaner.s3.delete_objects(Bucket=bucket_name, Delete={'Objects': delete_list, 'Quiet': True}) except ClientError as e: print(' ERROR: Failed to delete objects {0} from bucket {1}. {2}' .format(delete_list, bucket_name, exception_utils.message(e))) code = e.response['Error']['Code'] if code != "NoSuchBucket": cleaner.add_to_failed_resources('s3', delete_list) next_key = response.get('NextKeyMarker', None) if next_key: response = cleaner.s3.list_object_versions(Bucket=bucket_name, MaxKeys=1000, KeyMarker=next_key) else: break # Wait for all objects to be deleted waiter = cleaner.s3.get_waiter('object_not_exists') for deleting_object in delete_verification_list: try: waiter.wait(Bucket=bucket_name, Key=deleting_object['Key'], VersionId=deleting_object['VersionId'], WaiterConfig={'Delay': cleaner.wait_interval, 'MaxAttempts': cleaner.wait_attempts}) print(' Finished deleting s3 object with key {}'.format(deleting_object['Key'])) except botocore.exceptions.WaiterError as e: if cleanup_utils.WAITER_ERROR_MESSAGE in exception_utils.message(e): print("ERROR: Timed out waiting for s3 object with key {} to delete".format(deleting_object['Key'])) else: print("ERROR: Unexpected error occurred waiting for s3 object with key {0} to delete due to {1}" .format(deleting_object['Key'], exception_utils.message(e))) cleaner.add_to_failed_resources('s3', deleting_object['Key'])
[ "def", "_clean_s3_bucket", "(", "cleaner", ",", "bucket_name", ")", ":", "print", "(", "' cleaning bucket {}'", ".", "format", "(", "bucket_name", ")", ")", "# Get the first batch", "try", ":", "response", "=", "cleaner", ".", "s3", ".", "list_object_versions", "(", "Bucket", "=", "bucket_name", ",", "MaxKeys", "=", "1000", ")", "except", "ClientError", "as", "e", ":", "print", "(", "' ERROR: Unexpected error while trying to gather s3 object versions. {}'", ".", "format", "(", "e", ")", ")", "code", "=", "e", ".", "response", "[", "'Error'", "]", "[", "'Code'", "]", "if", "code", "!=", "\"NoSuchBucket\"", ":", "cleaner", ".", "add_to_failed_resources", "(", "'s3'", ",", "bucket_name", ")", "return", "# Deleting objects in batches is capped at 1000 objects, therefore we can't construct the entire list beforehand", "delete_verification_list", "=", "[", "]", "while", "True", ":", "delete_list", "=", "[", "]", "for", "version", "in", "response", ".", "get", "(", "'Versions'", ",", "[", "]", ")", ":", "delete_list", ".", "append", "(", "{", "'Key'", ":", "version", "[", "'Key'", "]", ",", "'VersionId'", ":", "version", "[", "'VersionId'", "]", "}", ")", "for", "marker", "in", "response", ".", "get", "(", "'DeleteMarkers'", ",", "[", "]", ")", ":", "delete_list", ".", "append", "(", "{", "'Key'", ":", "marker", "[", "'Key'", "]", ",", "'VersionId'", ":", "marker", "[", "'VersionId'", "]", "}", ")", "delete_verification_list", ".", "extend", "(", "delete_list", ")", "try", ":", "cleaner", ".", "s3", ".", "delete_objects", "(", "Bucket", "=", "bucket_name", ",", "Delete", "=", "{", "'Objects'", ":", "delete_list", ",", "'Quiet'", ":", "True", "}", ")", "except", "ClientError", "as", "e", ":", "print", "(", "' ERROR: Failed to delete objects {0} from bucket {1}. {2}'", ".", "format", "(", "delete_list", ",", "bucket_name", ",", "exception_utils", ".", "message", "(", "e", ")", ")", ")", "code", "=", "e", ".", "response", "[", "'Error'", "]", "[", "'Code'", "]", "if", "code", "!=", "\"NoSuchBucket\"", ":", "cleaner", ".", "add_to_failed_resources", "(", "'s3'", ",", "delete_list", ")", "next_key", "=", "response", ".", "get", "(", "'NextKeyMarker'", ",", "None", ")", "if", "next_key", ":", "response", "=", "cleaner", ".", "s3", ".", "list_object_versions", "(", "Bucket", "=", "bucket_name", ",", "MaxKeys", "=", "1000", ",", "KeyMarker", "=", "next_key", ")", "else", ":", "break", "# Wait for all objects to be deleted", "waiter", "=", "cleaner", ".", "s3", ".", "get_waiter", "(", "'object_not_exists'", ")", "for", "deleting_object", "in", "delete_verification_list", ":", "try", ":", "waiter", ".", "wait", "(", "Bucket", "=", "bucket_name", ",", "Key", "=", "deleting_object", "[", "'Key'", "]", ",", "VersionId", "=", "deleting_object", "[", "'VersionId'", "]", ",", "WaiterConfig", "=", "{", "'Delay'", ":", "cleaner", ".", "wait_interval", ",", "'MaxAttempts'", ":", "cleaner", ".", "wait_attempts", "}", ")", "print", "(", "' Finished deleting s3 object with key {}'", ".", "format", "(", "deleting_object", "[", "'Key'", "]", ")", ")", "except", "botocore", ".", "exceptions", ".", "WaiterError", "as", "e", ":", "if", "cleanup_utils", ".", "WAITER_ERROR_MESSAGE", "in", "exception_utils", ".", "message", "(", "e", ")", ":", "print", "(", "\"ERROR: Timed out waiting for s3 object with key {} to delete\"", ".", "format", "(", "deleting_object", "[", "'Key'", "]", ")", ")", "else", ":", "print", "(", "\"ERROR: Unexpected error occurred waiting for s3 object with key {0} to delete due to {1}\"", ".", "format", "(", "deleting_object", "[", "'Key'", "]", ",", "exception_utils", ".", "message", "(", "e", ")", ")", ")", "cleaner", ".", "add_to_failed_resources", "(", "'s3'", ",", "deleting_object", "[", "'Key'", "]", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/lmbr_aws/cleanup_utils/cleanup_s3_utils.py#L88-L143
RamadhanAmizudin/malware
2c6c53c8b0d556f5d8078d6ca0fc4448f4697cf1
GMBot/gmbot/apps/smsg_r/smsapp/remote_api.py
python
listen_status_change
(rec, data)
Signals that the phone has changed its listen status in reply to #listen_sms_start & #listen_sms_stop data."listening status" contains either "started" or "stopped" @param rec: Phone data record @type rec: models.PhoneData @param data: Phone data @type data: dict @rtype: None
Signals that the phone has changed its listen status in reply to #listen_sms_start & #listen_sms_stop data."listening status" contains either "started" or "stopped"
[ "Signals", "that", "the", "phone", "has", "changed", "its", "listen", "status", "in", "reply", "to", "#listen_sms_start", "&", "#listen_sms_stop", "data", ".", "listening", "status", "contains", "either", "started", "or", "stopped" ]
def listen_status_change(rec, data): """ Signals that the phone has changed its listen status in reply to #listen_sms_start & #listen_sms_stop data."listening status" contains either "started" or "stopped" @param rec: Phone data record @type rec: models.PhoneData @param data: Phone data @type data: dict @rtype: None """ new_status = data.get('listening status') owner = rec.owner if new_status == "started": rec.sms_status = models.PhoneData.SMS_LISTEN rec.save() elif new_status == "stopped": rec.owner = None rec.sms_status = models.PhoneData.SMS_INITIAL rec.save() msg = { 'info': "Phone {0} SMS listening {1}".format(rec, new_status), 'imei': rec.imei } sys_messages.add_message(rec.uniq_id, msg)
[ "def", "listen_status_change", "(", "rec", ",", "data", ")", ":", "new_status", "=", "data", ".", "get", "(", "'listening status'", ")", "owner", "=", "rec", ".", "owner", "if", "new_status", "==", "\"started\"", ":", "rec", ".", "sms_status", "=", "models", ".", "PhoneData", ".", "SMS_LISTEN", "rec", ".", "save", "(", ")", "elif", "new_status", "==", "\"stopped\"", ":", "rec", ".", "owner", "=", "None", "rec", ".", "sms_status", "=", "models", ".", "PhoneData", ".", "SMS_INITIAL", "rec", ".", "save", "(", ")", "msg", "=", "{", "'info'", ":", "\"Phone {0} SMS listening {1}\"", ".", "format", "(", "rec", ",", "new_status", ")", ",", "'imei'", ":", "rec", ".", "imei", "}", "sys_messages", ".", "add_message", "(", "rec", ".", "uniq_id", ",", "msg", ")" ]
https://github.com/RamadhanAmizudin/malware/blob/2c6c53c8b0d556f5d8078d6ca0fc4448f4697cf1/GMBot/gmbot/apps/smsg_r/smsapp/remote_api.py#L288-L311
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/python/ops/control_flow_ops.py
python
switch
(data, pred, dtype=None, name=None)
Forwards `data` to an output determined by `pred`. If `pred` is false, the `data` input is forwarded to the first output. Otherwise, the data goes to the second output. This op handles `Tensor`s and `IndexedSlices`. Args: data: The tensor to be forwarded to the appropriate output. pred: A scalar that specifies which output port will receive data. dtype: Optional element type for the returned tensor. If missing, the type is inferred from the type of `value`. name: A name for this operation (optional). Returns: `(output_false, output_true)`: If `pred` is true, data will be forwarded to `output_true`, otherwise it goes to `output_false`.
Forwards `data` to an output determined by `pred`.
[ "Forwards", "data", "to", "an", "output", "determined", "by", "pred", "." ]
def switch(data, pred, dtype=None, name=None): """Forwards `data` to an output determined by `pred`. If `pred` is false, the `data` input is forwarded to the first output. Otherwise, the data goes to the second output. This op handles `Tensor`s and `IndexedSlices`. Args: data: The tensor to be forwarded to the appropriate output. pred: A scalar that specifies which output port will receive data. dtype: Optional element type for the returned tensor. If missing, the type is inferred from the type of `value`. name: A name for this operation (optional). Returns: `(output_false, output_true)`: If `pred` is true, data will be forwarded to `output_true`, otherwise it goes to `output_false`. """ with ops.name_scope(name, "Switch", [data, pred]) as name: data = ops.internal_convert_to_tensor_or_indexed_slices( data, dtype=dtype, name="data", as_ref=True) pred = ops.convert_to_tensor(pred, name="pred") if isinstance(data, ops.Tensor): return gen_control_flow_ops._switch(data, pred, name=name) else: if not isinstance(data, (ops.IndexedSlices, sparse_tensor.SparseTensor)): raise TypeError("Type %s not supported" % type(data)) val, ind = data.values, data.indices val_f, val_t = gen_control_flow_ops._switch(val, pred, name=name) ind_f, ind_t = gen_control_flow_ops._switch(ind, pred, name="indices") if isinstance(data, ops.IndexedSlices): dense_shape = data.dense_shape if dense_shape is not None: dense_shape_f, dense_shape_t = gen_control_flow_ops._switch( dense_shape, pred, name="dense_shape") else: dense_shape_f, dense_shape_t = None, None return (ops.IndexedSlices(val_f, ind_f, dense_shape_f), ops.IndexedSlices(val_t, ind_t, dense_shape_t)) else: dense_shape = data.dense_shape dense_shape_f, dense_shape_t = gen_control_flow_ops._switch( data.dense_shape, pred, name="dense_shape") return (sparse_tensor.SparseTensor(ind_f, val_f, dense_shape_f), sparse_tensor.SparseTensor(ind_t, val_t, dense_shape_t))
[ "def", "switch", "(", "data", ",", "pred", ",", "dtype", "=", "None", ",", "name", "=", "None", ")", ":", "with", "ops", ".", "name_scope", "(", "name", ",", "\"Switch\"", ",", "[", "data", ",", "pred", "]", ")", "as", "name", ":", "data", "=", "ops", ".", "internal_convert_to_tensor_or_indexed_slices", "(", "data", ",", "dtype", "=", "dtype", ",", "name", "=", "\"data\"", ",", "as_ref", "=", "True", ")", "pred", "=", "ops", ".", "convert_to_tensor", "(", "pred", ",", "name", "=", "\"pred\"", ")", "if", "isinstance", "(", "data", ",", "ops", ".", "Tensor", ")", ":", "return", "gen_control_flow_ops", ".", "_switch", "(", "data", ",", "pred", ",", "name", "=", "name", ")", "else", ":", "if", "not", "isinstance", "(", "data", ",", "(", "ops", ".", "IndexedSlices", ",", "sparse_tensor", ".", "SparseTensor", ")", ")", ":", "raise", "TypeError", "(", "\"Type %s not supported\"", "%", "type", "(", "data", ")", ")", "val", ",", "ind", "=", "data", ".", "values", ",", "data", ".", "indices", "val_f", ",", "val_t", "=", "gen_control_flow_ops", ".", "_switch", "(", "val", ",", "pred", ",", "name", "=", "name", ")", "ind_f", ",", "ind_t", "=", "gen_control_flow_ops", ".", "_switch", "(", "ind", ",", "pred", ",", "name", "=", "\"indices\"", ")", "if", "isinstance", "(", "data", ",", "ops", ".", "IndexedSlices", ")", ":", "dense_shape", "=", "data", ".", "dense_shape", "if", "dense_shape", "is", "not", "None", ":", "dense_shape_f", ",", "dense_shape_t", "=", "gen_control_flow_ops", ".", "_switch", "(", "dense_shape", ",", "pred", ",", "name", "=", "\"dense_shape\"", ")", "else", ":", "dense_shape_f", ",", "dense_shape_t", "=", "None", ",", "None", "return", "(", "ops", ".", "IndexedSlices", "(", "val_f", ",", "ind_f", ",", "dense_shape_f", ")", ",", "ops", ".", "IndexedSlices", "(", "val_t", ",", "ind_t", ",", "dense_shape_t", ")", ")", "else", ":", "dense_shape", "=", "data", ".", "dense_shape", "dense_shape_f", ",", "dense_shape_t", "=", "gen_control_flow_ops", ".", "_switch", "(", "data", ".", "dense_shape", ",", "pred", ",", "name", "=", "\"dense_shape\"", ")", "return", "(", "sparse_tensor", ".", "SparseTensor", "(", "ind_f", ",", "val_f", ",", "dense_shape_f", ")", ",", "sparse_tensor", ".", "SparseTensor", "(", "ind_t", ",", "val_t", ",", "dense_shape_t", ")", ")" ]
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/ops/control_flow_ops.py#L284-L329
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_vendor/pkg_resources/__init__.py
python
WorkingSet.run_script
(self, requires, script_name)
Locate distribution for `requires` and run `script_name` script
Locate distribution for `requires` and run `script_name` script
[ "Locate", "distribution", "for", "requires", "and", "run", "script_name", "script" ]
def run_script(self, requires, script_name): """Locate distribution for `requires` and run `script_name` script""" ns = sys._getframe(1).f_globals name = ns['__name__'] ns.clear() ns['__name__'] = name self.require(requires)[0].run_script(script_name, ns)
[ "def", "run_script", "(", "self", ",", "requires", ",", "script_name", ")", ":", "ns", "=", "sys", ".", "_getframe", "(", "1", ")", ".", "f_globals", "name", "=", "ns", "[", "'__name__'", "]", "ns", ".", "clear", "(", ")", "ns", "[", "'__name__'", "]", "=", "name", "self", ".", "require", "(", "requires", ")", "[", "0", "]", ".", "run_script", "(", "script_name", ",", "ns", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_vendor/pkg_resources/__init__.py#L660-L666
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/python/keras/_impl/keras/callbacks.py
python
CallbackList.on_batch_begin
(self, batch, logs=None)
Called right before processing a batch. Arguments: batch: integer, index of batch within the current epoch. logs: dictionary of logs.
Called right before processing a batch.
[ "Called", "right", "before", "processing", "a", "batch", "." ]
def on_batch_begin(self, batch, logs=None): """Called right before processing a batch. Arguments: batch: integer, index of batch within the current epoch. logs: dictionary of logs. """ logs = logs or {} t_before_callbacks = time.time() for callback in self.callbacks: callback.on_batch_begin(batch, logs) self._delta_ts_batch_begin.append(time.time() - t_before_callbacks) delta_t_median = np.median(self._delta_ts_batch_begin) if (self._delta_t_batch > 0. and delta_t_median > 0.95 * self._delta_t_batch and delta_t_median > 0.1): logging.warning( 'Method on_batch_begin() is slow compared ' 'to the batch update (%f). Check your callbacks.' % delta_t_median) self._t_enter_batch = time.time()
[ "def", "on_batch_begin", "(", "self", ",", "batch", ",", "logs", "=", "None", ")", ":", "logs", "=", "logs", "or", "{", "}", "t_before_callbacks", "=", "time", ".", "time", "(", ")", "for", "callback", "in", "self", ".", "callbacks", ":", "callback", ".", "on_batch_begin", "(", "batch", ",", "logs", ")", "self", ".", "_delta_ts_batch_begin", ".", "append", "(", "time", ".", "time", "(", ")", "-", "t_before_callbacks", ")", "delta_t_median", "=", "np", ".", "median", "(", "self", ".", "_delta_ts_batch_begin", ")", "if", "(", "self", ".", "_delta_t_batch", ">", "0.", "and", "delta_t_median", ">", "0.95", "*", "self", ".", "_delta_t_batch", "and", "delta_t_median", ">", "0.1", ")", ":", "logging", ".", "warning", "(", "'Method on_batch_begin() is slow compared '", "'to the batch update (%f). Check your callbacks.'", "%", "delta_t_median", ")", "self", ".", "_t_enter_batch", "=", "time", ".", "time", "(", ")" ]
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/keras/_impl/keras/callbacks.py#L97-L115
mapnik/mapnik
f3da900c355e1d15059c4a91b00203dcc9d9f0ef
scons/scons-local-4.1.0/SCons/Platform/virtualenv.py
python
ImportVirtualenv
(env)
Copies virtualenv-related environment variables from OS environment to ``env['ENV']`` and prepends virtualenv's PATH to ``env['ENV']['PATH']``.
Copies virtualenv-related environment variables from OS environment to ``env['ENV']`` and prepends virtualenv's PATH to ``env['ENV']['PATH']``.
[ "Copies", "virtualenv", "-", "related", "environment", "variables", "from", "OS", "environment", "to", "env", "[", "ENV", "]", "and", "prepends", "virtualenv", "s", "PATH", "to", "env", "[", "ENV", "]", "[", "PATH", "]", "." ]
def ImportVirtualenv(env): """Copies virtualenv-related environment variables from OS environment to ``env['ENV']`` and prepends virtualenv's PATH to ``env['ENV']['PATH']``. """ _inject_venv_variables(env) _inject_venv_path(env)
[ "def", "ImportVirtualenv", "(", "env", ")", ":", "_inject_venv_variables", "(", "env", ")", "_inject_venv_path", "(", "env", ")" ]
https://github.com/mapnik/mapnik/blob/f3da900c355e1d15059c4a91b00203dcc9d9f0ef/scons/scons-local-4.1.0/SCons/Platform/virtualenv.py#L89-L94
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/profiler/parser/memory_usage_parser.py
python
GraphMemoryParser._calc_node_memory
(self, tensor_ids)
return node_mem
Calculate the allocated memory for the node.
Calculate the allocated memory for the node.
[ "Calculate", "the", "allocated", "memory", "for", "the", "node", "." ]
def _calc_node_memory(self, tensor_ids): """Calculate the allocated memory for the node.""" node_mem = 0 for t_id in tensor_ids: tensor = self.tensors[t_id] size = tensor.size node_mem += size return node_mem
[ "def", "_calc_node_memory", "(", "self", ",", "tensor_ids", ")", ":", "node_mem", "=", "0", "for", "t_id", "in", "tensor_ids", ":", "tensor", "=", "self", ".", "tensors", "[", "t_id", "]", "size", "=", "tensor", ".", "size", "node_mem", "+=", "size", "return", "node_mem" ]
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/profiler/parser/memory_usage_parser.py#L294-L302
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
qt/python/mantidqt/mantidqt/widgets/plotconfigdialog/legendtabwidget/presenter.py
python
LegendTabWidgetPresenter.hide_box_ticked
(self, enable)
Disables or enables all options related to the legend box when hide box is ticked or unticked.
Disables or enables all options related to the legend box when hide box is ticked or unticked.
[ "Disables", "or", "enables", "all", "options", "related", "to", "the", "legend", "box", "when", "hide", "box", "is", "ticked", "or", "unticked", "." ]
def hide_box_ticked(self, enable): """Disables or enables all options related to the legend box when hide box is ticked or unticked.""" self.view.background_color_selector_widget.setEnabled(enable) self.view.edge_color_selector_widget.setEnabled(enable) self.view.transparency_slider.setEnabled(enable) self.view.transparency_spin_box.setEnabled(enable) self.view.advanced_options.shadow_check_box.setEnabled(enable) self.view.advanced_options.round_edges_check_box.setEnabled(enable)
[ "def", "hide_box_ticked", "(", "self", ",", "enable", ")", ":", "self", ".", "view", ".", "background_color_selector_widget", ".", "setEnabled", "(", "enable", ")", "self", ".", "view", ".", "edge_color_selector_widget", ".", "setEnabled", "(", "enable", ")", "self", ".", "view", ".", "transparency_slider", ".", "setEnabled", "(", "enable", ")", "self", ".", "view", ".", "transparency_spin_box", ".", "setEnabled", "(", "enable", ")", "self", ".", "view", ".", "advanced_options", ".", "shadow_check_box", ".", "setEnabled", "(", "enable", ")", "self", ".", "view", ".", "advanced_options", ".", "round_edges_check_box", ".", "setEnabled", "(", "enable", ")" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqt/mantidqt/widgets/plotconfigdialog/legendtabwidget/presenter.py#L149-L156
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/py2/scipy/spatial/kdtree.py
python
Rectangle.max_distance_rectangle
(self, other, p=2.)
return minkowski_distance(0, np.maximum(self.maxes-other.mins,other.maxes-self.mins),p)
Compute the maximum distance between points in the two hyperrectangles. Parameters ---------- other : hyperrectangle Input. p : float, optional Input.
Compute the maximum distance between points in the two hyperrectangles.
[ "Compute", "the", "maximum", "distance", "between", "points", "in", "the", "two", "hyperrectangles", "." ]
def max_distance_rectangle(self, other, p=2.): """ Compute the maximum distance between points in the two hyperrectangles. Parameters ---------- other : hyperrectangle Input. p : float, optional Input. """ return minkowski_distance(0, np.maximum(self.maxes-other.mins,other.maxes-self.mins),p)
[ "def", "max_distance_rectangle", "(", "self", ",", "other", ",", "p", "=", "2.", ")", ":", "return", "minkowski_distance", "(", "0", ",", "np", ".", "maximum", "(", "self", ".", "maxes", "-", "other", ".", "mins", ",", "other", ".", "maxes", "-", "self", ".", "mins", ")", ",", "p", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py2/scipy/spatial/kdtree.py#L161-L173
SFTtech/openage
d6a08c53c48dc1e157807471df92197f6ca9e04d
openage/convert/entity_object/conversion/converter_object.py
python
ConverterObjectGroup.create_nyan_objects
(self)
Creates nyan objects from the existing raw API objects.
Creates nyan objects from the existing raw API objects.
[ "Creates", "nyan", "objects", "from", "the", "existing", "raw", "API", "objects", "." ]
def create_nyan_objects(self): """ Creates nyan objects from the existing raw API objects. """ patch_objects = [] for raw_api_object in self.raw_api_objects.values(): raw_api_object.create_nyan_object() if raw_api_object.is_patch(): patch_objects.append(raw_api_object) for patch_object in patch_objects: patch_object.link_patch_target()
[ "def", "create_nyan_objects", "(", "self", ")", ":", "patch_objects", "=", "[", "]", "for", "raw_api_object", "in", "self", ".", "raw_api_objects", ".", "values", "(", ")", ":", "raw_api_object", ".", "create_nyan_object", "(", ")", "if", "raw_api_object", ".", "is_patch", "(", ")", ":", "patch_objects", ".", "append", "(", "raw_api_object", ")", "for", "patch_object", "in", "patch_objects", ":", "patch_object", ".", "link_patch_target", "(", ")" ]
https://github.com/SFTtech/openage/blob/d6a08c53c48dc1e157807471df92197f6ca9e04d/openage/convert/entity_object/conversion/converter_object.py#L191-L203
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/gsutil/third_party/protorpc/protorpc/generate_python.py
python
_write_services
(service_descriptors, out)
Write Service types. Args: service_descriptors: List of ServiceDescriptor instances from which to generate services. out: Indent writer used for generating text.
Write Service types.
[ "Write", "Service", "types", "." ]
def _write_services(service_descriptors, out): """Write Service types. Args: service_descriptors: List of ServiceDescriptor instances from which to generate services. out: Indent writer used for generating text. """ for service in service_descriptors or []: out << '' out << '' out << 'class %s(remote.Service):' % service.name with out.indent(): if service.methods: _write_methods(service.methods, out) else: out << '' out << 'pass'
[ "def", "_write_services", "(", "service_descriptors", ",", "out", ")", ":", "for", "service", "in", "service_descriptors", "or", "[", "]", ":", "out", "<<", "''", "out", "<<", "''", "out", "<<", "'class %s(remote.Service):'", "%", "service", ".", "name", "with", "out", ".", "indent", "(", ")", ":", "if", "service", ".", "methods", ":", "_write_methods", "(", "service", ".", "methods", ",", "out", ")", "else", ":", "out", "<<", "''", "out", "<<", "'pass'" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/protorpc/protorpc/generate_python.py#L164-L182
nsnam/ns-3-dev-git
efdb2e21f45c0a87a60b47c547b68fa140a7b686
bindings/python/rad_util.py
python
uniquify
(seq, preserve_order=False)
Return sequence with duplicate items in sequence seq removed. The code is based on usenet post by Tim Peters. This code is O(N) if the sequence items are hashable, O(N**2) if not. Peter Bengtsson has a blog post with an empirical comparison of other approaches: http://www.peterbe.com/plog/uniqifiers-benchmark If order is not important and the sequence items are hashable then list(set(seq)) is readable and efficient. If order is important and the sequence items are hashable generator expressions can be used (in py >= 2.4) (useful for large sequences): seen = set() do_something(x for x in seq if x not in seen or seen.add(x)) Arguments: seq -- sequence preserve_order -- if not set the order will be arbitrary Using this option will incur a speed penalty. (default: False) Example showing order preservation: >>> uniquify(['a', 'aa', 'b', 'b', 'ccc', 'ccc', 'd'], preserve_order=True) ['a', 'aa', 'b', 'ccc', 'd'] Example using a sequence of un-hashable items: >>> uniquify([['z'], ['x'], ['y'], ['z']], preserve_order=True) [['z'], ['x'], ['y']] The sorted output or the non-order-preserving approach should equal that of the sorted order-preserving approach output: >>> unordered = uniquify([3, 3, 1, 2], preserve_order=False) >>> unordered.sort() >>> ordered = uniquify([3, 3, 1, 2], preserve_order=True) >>> ordered.sort() >>> ordered [1, 2, 3] >>> int(ordered == unordered) 1
Return sequence with duplicate items in sequence seq removed.
[ "Return", "sequence", "with", "duplicate", "items", "in", "sequence", "seq", "removed", "." ]
def uniquify(seq, preserve_order=False): """Return sequence with duplicate items in sequence seq removed. The code is based on usenet post by Tim Peters. This code is O(N) if the sequence items are hashable, O(N**2) if not. Peter Bengtsson has a blog post with an empirical comparison of other approaches: http://www.peterbe.com/plog/uniqifiers-benchmark If order is not important and the sequence items are hashable then list(set(seq)) is readable and efficient. If order is important and the sequence items are hashable generator expressions can be used (in py >= 2.4) (useful for large sequences): seen = set() do_something(x for x in seq if x not in seen or seen.add(x)) Arguments: seq -- sequence preserve_order -- if not set the order will be arbitrary Using this option will incur a speed penalty. (default: False) Example showing order preservation: >>> uniquify(['a', 'aa', 'b', 'b', 'ccc', 'ccc', 'd'], preserve_order=True) ['a', 'aa', 'b', 'ccc', 'd'] Example using a sequence of un-hashable items: >>> uniquify([['z'], ['x'], ['y'], ['z']], preserve_order=True) [['z'], ['x'], ['y']] The sorted output or the non-order-preserving approach should equal that of the sorted order-preserving approach output: >>> unordered = uniquify([3, 3, 1, 2], preserve_order=False) >>> unordered.sort() >>> ordered = uniquify([3, 3, 1, 2], preserve_order=True) >>> ordered.sort() >>> ordered [1, 2, 3] >>> int(ordered == unordered) 1 """ try: # Attempt fast algorithm. d = {} if preserve_order: # This is based on Dave Kirby's method (f8) noted in the post: # http://www.peterbe.com/plog/uniqifiers-benchmark return [x for x in seq if (x not in d) and not d.__setitem__(x, 0)] else: for x in seq: d[x] = 0 return d.keys() except TypeError: # Have an unhashable object, so use slow algorithm. result = [] app = result.append for x in seq: if x not in result: app(x) return result
[ "def", "uniquify", "(", "seq", ",", "preserve_order", "=", "False", ")", ":", "try", ":", "# Attempt fast algorithm.", "d", "=", "{", "}", "if", "preserve_order", ":", "# This is based on Dave Kirby's method (f8) noted in the post:", "# http://www.peterbe.com/plog/uniqifiers-benchmark", "return", "[", "x", "for", "x", "in", "seq", "if", "(", "x", "not", "in", "d", ")", "and", "not", "d", ".", "__setitem__", "(", "x", ",", "0", ")", "]", "else", ":", "for", "x", "in", "seq", ":", "d", "[", "x", "]", "=", "0", "return", "d", ".", "keys", "(", ")", "except", "TypeError", ":", "# Have an unhashable object, so use slow algorithm.", "result", "=", "[", "]", "app", "=", "result", ".", "append", "for", "x", "in", "seq", ":", "if", "x", "not", "in", "result", ":", "app", "(", "x", ")", "return", "result" ]
https://github.com/nsnam/ns-3-dev-git/blob/efdb2e21f45c0a87a60b47c547b68fa140a7b686/bindings/python/rad_util.py#L512-L578
feelpp/feelpp
2d547ed701cc5adb01639185b4a8eb47940367c7
toolboxes/pyfeelpp-toolboxes/feelpp/toolboxes/multifluid/__init__.py
python
thermoelectric
( dim=2, orderPotential=1, buildMesh=True, worldComm=core.Environment.worldCommPtr() )
return _thermoelectrics[key]( "thermoelectric", buildMesh, worldComm )
create a thermoelectric toolbox solver Keyword arguments: dim -- the dimension (default: 2) orderPotential -- the polynomial order for the potential (default: 1) worldComm -- the parallel communicator for the mesh (default: core.Environment::worldCommPtr())
create a thermoelectric toolbox solver Keyword arguments: dim -- the dimension (default: 2) orderPotential -- the polynomial order for the potential (default: 1) worldComm -- the parallel communicator for the mesh (default: core.Environment::worldCommPtr())
[ "create", "a", "thermoelectric", "toolbox", "solver", "Keyword", "arguments", ":", "dim", "--", "the", "dimension", "(", "default", ":", "2", ")", "orderPotential", "--", "the", "polynomial", "order", "for", "the", "potential", "(", "default", ":", "1", ")", "worldComm", "--", "the", "parallel", "communicator", "for", "the", "mesh", "(", "default", ":", "core", ".", "Environment", "::", "worldCommPtr", "()", ")" ]
def thermoelectric( dim=2, orderPotential=1, buildMesh=True, worldComm=core.Environment.worldCommPtr() ): """create a thermoelectric toolbox solver Keyword arguments: dim -- the dimension (default: 2) orderPotential -- the polynomial order for the potential (default: 1) worldComm -- the parallel communicator for the mesh (default: core.Environment::worldCommPtr()) """ key='thermoelectric('+str(dim)+','+str(orderPotential)+')' if worldComm.isMasterRank(): print(key) if key not in _thermoelectrics: raise RuntimeError('Thermoelectric solver '+key+' not existing') return _thermoelectrics[key]( "thermoelectric", buildMesh, worldComm )
[ "def", "thermoelectric", "(", "dim", "=", "2", ",", "orderPotential", "=", "1", ",", "buildMesh", "=", "True", ",", "worldComm", "=", "core", ".", "Environment", ".", "worldCommPtr", "(", ")", ")", ":", "key", "=", "'thermoelectric('", "+", "str", "(", "dim", ")", "+", "','", "+", "str", "(", "orderPotential", ")", "+", "')'", "if", "worldComm", ".", "isMasterRank", "(", ")", ":", "print", "(", "key", ")", "if", "key", "not", "in", "_thermoelectrics", ":", "raise", "RuntimeError", "(", "'Thermoelectric solver '", "+", "key", "+", "' not existing'", ")", "return", "_thermoelectrics", "[", "key", "]", "(", "\"thermoelectric\"", ",", "buildMesh", ",", "worldComm", ")" ]
https://github.com/feelpp/feelpp/blob/2d547ed701cc5adb01639185b4a8eb47940367c7/toolboxes/pyfeelpp-toolboxes/feelpp/toolboxes/multifluid/__init__.py#L12-L24
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/gsutil/gslib/gcs_json_media.py
python
DownloadCallbackConnectionClassFactory.GetConnectionClass
(self)
return DownloadCallbackConnection
Returns a connection class that overrides getresponse.
Returns a connection class that overrides getresponse.
[ "Returns", "a", "connection", "class", "that", "overrides", "getresponse", "." ]
def GetConnectionClass(self): """Returns a connection class that overrides getresponse.""" class DownloadCallbackConnection(httplib2.HTTPSConnectionWithTimeout): """Connection class override for downloads.""" outer_total_size = self.total_size outer_digesters = self.digesters outer_progress_callback = self.progress_callback outer_bytes_downloaded_container = self.bytes_downloaded_container processed_initial_bytes = False callback_processor = None def __init__(self, *args, **kwargs): kwargs['timeout'] = SSL_TIMEOUT httplib2.HTTPSConnectionWithTimeout.__init__(self, *args, **kwargs) def getresponse(self, buffering=False): """Wraps an HTTPResponse to perform callbacks and hashing. In this function, self is a DownloadCallbackConnection. Args: buffering: Unused. This function uses a local buffer. Returns: HTTPResponse object with wrapped read function. """ orig_response = httplib.HTTPConnection.getresponse(self) if orig_response.status not in (httplib.OK, httplib.PARTIAL_CONTENT): return orig_response orig_read_func = orig_response.read def read(amt=None): # pylint: disable=invalid-name """Overrides HTTPConnection.getresponse.read. This function only supports reads of TRANSFER_BUFFER_SIZE or smaller. Args: amt: Integer n where 0 < n <= TRANSFER_BUFFER_SIZE. This is a keyword argument to match the read function it overrides, but it is required. Returns: Data read from HTTPConnection. """ if not amt or amt > TRANSFER_BUFFER_SIZE: raise BadRequestException( 'Invalid HTTP read size %s during download, expected %s.' % (amt, TRANSFER_BUFFER_SIZE)) else: amt = amt or TRANSFER_BUFFER_SIZE if not self.processed_initial_bytes: self.processed_initial_bytes = True if self.outer_progress_callback: self.callback_processor = ProgressCallbackWithBackoff( self.outer_total_size, self.outer_progress_callback) self.callback_processor.Progress( self.outer_bytes_downloaded_container.bytes_transferred) data = orig_read_func(amt) read_length = len(data) if self.callback_processor: self.callback_processor.Progress(read_length) if self.outer_digesters: for alg in self.outer_digesters: self.outer_digesters[alg].update(data) return data orig_response.read = read return orig_response return DownloadCallbackConnection
[ "def", "GetConnectionClass", "(", "self", ")", ":", "class", "DownloadCallbackConnection", "(", "httplib2", ".", "HTTPSConnectionWithTimeout", ")", ":", "\"\"\"Connection class override for downloads.\"\"\"", "outer_total_size", "=", "self", ".", "total_size", "outer_digesters", "=", "self", ".", "digesters", "outer_progress_callback", "=", "self", ".", "progress_callback", "outer_bytes_downloaded_container", "=", "self", ".", "bytes_downloaded_container", "processed_initial_bytes", "=", "False", "callback_processor", "=", "None", "def", "__init__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'timeout'", "]", "=", "SSL_TIMEOUT", "httplib2", ".", "HTTPSConnectionWithTimeout", ".", "__init__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", "def", "getresponse", "(", "self", ",", "buffering", "=", "False", ")", ":", "\"\"\"Wraps an HTTPResponse to perform callbacks and hashing.\n\n In this function, self is a DownloadCallbackConnection.\n\n Args:\n buffering: Unused. This function uses a local buffer.\n\n Returns:\n HTTPResponse object with wrapped read function.\n \"\"\"", "orig_response", "=", "httplib", ".", "HTTPConnection", ".", "getresponse", "(", "self", ")", "if", "orig_response", ".", "status", "not", "in", "(", "httplib", ".", "OK", ",", "httplib", ".", "PARTIAL_CONTENT", ")", ":", "return", "orig_response", "orig_read_func", "=", "orig_response", ".", "read", "def", "read", "(", "amt", "=", "None", ")", ":", "# pylint: disable=invalid-name", "\"\"\"Overrides HTTPConnection.getresponse.read.\n\n This function only supports reads of TRANSFER_BUFFER_SIZE or smaller.\n\n Args:\n amt: Integer n where 0 < n <= TRANSFER_BUFFER_SIZE. This is a\n keyword argument to match the read function it overrides,\n but it is required.\n\n Returns:\n Data read from HTTPConnection.\n \"\"\"", "if", "not", "amt", "or", "amt", ">", "TRANSFER_BUFFER_SIZE", ":", "raise", "BadRequestException", "(", "'Invalid HTTP read size %s during download, expected %s.'", "%", "(", "amt", ",", "TRANSFER_BUFFER_SIZE", ")", ")", "else", ":", "amt", "=", "amt", "or", "TRANSFER_BUFFER_SIZE", "if", "not", "self", ".", "processed_initial_bytes", ":", "self", ".", "processed_initial_bytes", "=", "True", "if", "self", ".", "outer_progress_callback", ":", "self", ".", "callback_processor", "=", "ProgressCallbackWithBackoff", "(", "self", ".", "outer_total_size", ",", "self", ".", "outer_progress_callback", ")", "self", ".", "callback_processor", ".", "Progress", "(", "self", ".", "outer_bytes_downloaded_container", ".", "bytes_transferred", ")", "data", "=", "orig_read_func", "(", "amt", ")", "read_length", "=", "len", "(", "data", ")", "if", "self", ".", "callback_processor", ":", "self", ".", "callback_processor", ".", "Progress", "(", "read_length", ")", "if", "self", ".", "outer_digesters", ":", "for", "alg", "in", "self", ".", "outer_digesters", ":", "self", ".", "outer_digesters", "[", "alg", "]", ".", "update", "(", "data", ")", "return", "data", "orig_response", ".", "read", "=", "read", "return", "orig_response", "return", "DownloadCallbackConnection" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/gslib/gcs_json_media.py#L179-L250
microsoft/TSS.MSR
0f2516fca2cd9929c31d5450e39301c9bde43688
TSS.Py/src/TpmTypes.py
python
TPMT_TK_AUTH.__init__
(self, tag = 0, hierarchy = TPM_HANDLE(), digest = None)
This ticket is produced by TPM2_PolicySigned() and TPM2_PolicySecret() when the authorization has an expiration time. If nonceTPM was provided in the policy command, the ticket is computed by Attributes: tag (TPM_ST): Ticket structure tag hierarchy (TPM_HANDLE): The hierarchy of the object used to produce the ticket digest (bytes): This shall be the HMAC produced using a proof value of hierarchy.
This ticket is produced by TPM2_PolicySigned() and TPM2_PolicySecret() when the authorization has an expiration time. If nonceTPM was provided in the policy command, the ticket is computed by
[ "This", "ticket", "is", "produced", "by", "TPM2_PolicySigned", "()", "and", "TPM2_PolicySecret", "()", "when", "the", "authorization", "has", "an", "expiration", "time", ".", "If", "nonceTPM", "was", "provided", "in", "the", "policy", "command", "the", "ticket", "is", "computed", "by" ]
def __init__(self, tag = 0, hierarchy = TPM_HANDLE(), digest = None): """ This ticket is produced by TPM2_PolicySigned() and TPM2_PolicySecret() when the authorization has an expiration time. If nonceTPM was provided in the policy command, the ticket is computed by Attributes: tag (TPM_ST): Ticket structure tag hierarchy (TPM_HANDLE): The hierarchy of the object used to produce the ticket digest (bytes): This shall be the HMAC produced using a proof value of hierarchy. """ self.tag = tag self.hierarchy = hierarchy self.digest = digest
[ "def", "__init__", "(", "self", ",", "tag", "=", "0", ",", "hierarchy", "=", "TPM_HANDLE", "(", ")", ",", "digest", "=", "None", ")", ":", "self", ".", "tag", "=", "tag", "self", ".", "hierarchy", "=", "hierarchy", "self", ".", "digest", "=", "digest" ]
https://github.com/microsoft/TSS.MSR/blob/0f2516fca2cd9929c31d5450e39301c9bde43688/TSS.Py/src/TpmTypes.py#L4171-L4185
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/lib/arraysetops.py
python
isin
(element, test_elements, assume_unique=False, invert=False)
return in1d(element, test_elements, assume_unique=assume_unique, invert=invert).reshape(element.shape)
Calculates `element in test_elements`, broadcasting over `element` only. Returns a boolean array of the same shape as `element` that is True where an element of `element` is in `test_elements` and False otherwise. Parameters ---------- element : array_like Input array. test_elements : array_like The values against which to test each value of `element`. This argument is flattened if it is an array or array_like. See notes for behavior with non-array-like parameters. assume_unique : bool, optional If True, the input arrays are both assumed to be unique, which can speed up the calculation. Default is False. invert : bool, optional If True, the values in the returned array are inverted, as if calculating `element not in test_elements`. Default is False. ``np.isin(a, b, invert=True)`` is equivalent to (but faster than) ``np.invert(np.isin(a, b))``. Returns ------- isin : ndarray, bool Has the same shape as `element`. The values `element[isin]` are in `test_elements`. See Also -------- in1d : Flattened version of this function. numpy.lib.arraysetops : Module with a number of other functions for performing set operations on arrays. Notes ----- `isin` is an element-wise function version of the python keyword `in`. ``isin(a, b)`` is roughly equivalent to ``np.array([item in b for item in a])`` if `a` and `b` are 1-D sequences. `element` and `test_elements` are converted to arrays if they are not already. If `test_elements` is a set (or other non-sequence collection) it will be converted to an object array with one element, rather than an array of the values contained in `test_elements`. This is a consequence of the `array` constructor's way of handling non-sequence collections. Converting the set to a list usually gives the desired behavior. .. versionadded:: 1.13.0 Examples -------- >>> element = 2*np.arange(4).reshape((2, 2)) >>> element array([[0, 2], [4, 6]]) >>> test_elements = [1, 2, 4, 8] >>> mask = np.isin(element, test_elements) >>> mask array([[False, True], [ True, False]]) >>> element[mask] array([2, 4]) The indices of the matched values can be obtained with `nonzero`: >>> np.nonzero(mask) (array([0, 1]), array([1, 0])) The test can also be inverted: >>> mask = np.isin(element, test_elements, invert=True) >>> mask array([[ True, False], [False, True]]) >>> element[mask] array([0, 6]) Because of how `array` handles sets, the following does not work as expected: >>> test_set = {1, 2, 4, 8} >>> np.isin(element, test_set) array([[False, False], [False, False]]) Casting the set to a list gives the expected result: >>> np.isin(element, list(test_set)) array([[False, True], [ True, False]])
Calculates `element in test_elements`, broadcasting over `element` only. Returns a boolean array of the same shape as `element` that is True where an element of `element` is in `test_elements` and False otherwise.
[ "Calculates", "element", "in", "test_elements", "broadcasting", "over", "element", "only", ".", "Returns", "a", "boolean", "array", "of", "the", "same", "shape", "as", "element", "that", "is", "True", "where", "an", "element", "of", "element", "is", "in", "test_elements", "and", "False", "otherwise", "." ]
def isin(element, test_elements, assume_unique=False, invert=False): """ Calculates `element in test_elements`, broadcasting over `element` only. Returns a boolean array of the same shape as `element` that is True where an element of `element` is in `test_elements` and False otherwise. Parameters ---------- element : array_like Input array. test_elements : array_like The values against which to test each value of `element`. This argument is flattened if it is an array or array_like. See notes for behavior with non-array-like parameters. assume_unique : bool, optional If True, the input arrays are both assumed to be unique, which can speed up the calculation. Default is False. invert : bool, optional If True, the values in the returned array are inverted, as if calculating `element not in test_elements`. Default is False. ``np.isin(a, b, invert=True)`` is equivalent to (but faster than) ``np.invert(np.isin(a, b))``. Returns ------- isin : ndarray, bool Has the same shape as `element`. The values `element[isin]` are in `test_elements`. See Also -------- in1d : Flattened version of this function. numpy.lib.arraysetops : Module with a number of other functions for performing set operations on arrays. Notes ----- `isin` is an element-wise function version of the python keyword `in`. ``isin(a, b)`` is roughly equivalent to ``np.array([item in b for item in a])`` if `a` and `b` are 1-D sequences. `element` and `test_elements` are converted to arrays if they are not already. If `test_elements` is a set (or other non-sequence collection) it will be converted to an object array with one element, rather than an array of the values contained in `test_elements`. This is a consequence of the `array` constructor's way of handling non-sequence collections. Converting the set to a list usually gives the desired behavior. .. versionadded:: 1.13.0 Examples -------- >>> element = 2*np.arange(4).reshape((2, 2)) >>> element array([[0, 2], [4, 6]]) >>> test_elements = [1, 2, 4, 8] >>> mask = np.isin(element, test_elements) >>> mask array([[False, True], [ True, False]]) >>> element[mask] array([2, 4]) The indices of the matched values can be obtained with `nonzero`: >>> np.nonzero(mask) (array([0, 1]), array([1, 0])) The test can also be inverted: >>> mask = np.isin(element, test_elements, invert=True) >>> mask array([[ True, False], [False, True]]) >>> element[mask] array([0, 6]) Because of how `array` handles sets, the following does not work as expected: >>> test_set = {1, 2, 4, 8} >>> np.isin(element, test_set) array([[False, False], [False, False]]) Casting the set to a list gives the expected result: >>> np.isin(element, list(test_set)) array([[False, True], [ True, False]]) """ element = np.asarray(element) return in1d(element, test_elements, assume_unique=assume_unique, invert=invert).reshape(element.shape)
[ "def", "isin", "(", "element", ",", "test_elements", ",", "assume_unique", "=", "False", ",", "invert", "=", "False", ")", ":", "element", "=", "np", ".", "asarray", "(", "element", ")", "return", "in1d", "(", "element", ",", "test_elements", ",", "assume_unique", "=", "assume_unique", ",", "invert", "=", "invert", ")", ".", "reshape", "(", "element", ".", "shape", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/lib/arraysetops.py#L602-L697
thalium/icebox
99d147d5b9269222225443ce171b4fd46d8985d4
third_party/benchmark/tools/gbench/report.py
python
intersect
(list1, list2)
return [x for x in list1 if x in list2]
Given two lists, get a new list consisting of the elements only contained in *both of the input lists*, while preserving the ordering.
Given two lists, get a new list consisting of the elements only contained in *both of the input lists*, while preserving the ordering.
[ "Given", "two", "lists", "get", "a", "new", "list", "consisting", "of", "the", "elements", "only", "contained", "in", "*", "both", "of", "the", "input", "lists", "*", "while", "preserving", "the", "ordering", "." ]
def intersect(list1, list2): """ Given two lists, get a new list consisting of the elements only contained in *both of the input lists*, while preserving the ordering. """ return [x for x in list1 if x in list2]
[ "def", "intersect", "(", "list1", ",", "list2", ")", ":", "return", "[", "x", "for", "x", "in", "list1", "if", "x", "in", "list2", "]" ]
https://github.com/thalium/icebox/blob/99d147d5b9269222225443ce171b4fd46d8985d4/third_party/benchmark/tools/gbench/report.py#L109-L114
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
tools/json_schema_compiler/model.py
python
_GetModelHierarchy
(entity)
return hierarchy
Returns the hierarchy of the given model entity.
Returns the hierarchy of the given model entity.
[ "Returns", "the", "hierarchy", "of", "the", "given", "model", "entity", "." ]
def _GetModelHierarchy(entity): """Returns the hierarchy of the given model entity.""" hierarchy = [] while entity is not None: hierarchy.append(getattr(entity, 'name', repr(entity))) if isinstance(entity, Namespace): hierarchy.insert(0, ' in %s' % entity.source_file) entity = getattr(entity, 'parent', None) hierarchy.reverse() return hierarchy
[ "def", "_GetModelHierarchy", "(", "entity", ")", ":", "hierarchy", "=", "[", "]", "while", "entity", "is", "not", "None", ":", "hierarchy", ".", "append", "(", "getattr", "(", "entity", ",", "'name'", ",", "repr", "(", "entity", ")", ")", ")", "if", "isinstance", "(", "entity", ",", "Namespace", ")", ":", "hierarchy", ".", "insert", "(", "0", ",", "' in %s'", "%", "entity", ".", "source_file", ")", "entity", "=", "getattr", "(", "entity", ",", "'parent'", ",", "None", ")", "hierarchy", ".", "reverse", "(", ")", "return", "hierarchy" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/json_schema_compiler/model.py#L531-L540
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/ops/distributions/bijector_impl.py
python
Bijector.forward_min_event_ndims
(self)
return self._forward_min_event_ndims
Returns the minimal number of dimensions bijector.forward operates on.
Returns the minimal number of dimensions bijector.forward operates on.
[ "Returns", "the", "minimal", "number", "of", "dimensions", "bijector", ".", "forward", "operates", "on", "." ]
def forward_min_event_ndims(self): """Returns the minimal number of dimensions bijector.forward operates on.""" return self._forward_min_event_ndims
[ "def", "forward_min_event_ndims", "(", "self", ")", ":", "return", "self", ".", "_forward_min_event_ndims" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/distributions/bijector_impl.py#L590-L592
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_windows.py
python
TaskBarIcon.__init__
(self, *args, **kwargs)
__init__(self, int iconType=TBI_DEFAULT_TYPE) -> TaskBarIcon
__init__(self, int iconType=TBI_DEFAULT_TYPE) -> TaskBarIcon
[ "__init__", "(", "self", "int", "iconType", "=", "TBI_DEFAULT_TYPE", ")", "-", ">", "TaskBarIcon" ]
def __init__(self, *args, **kwargs): """__init__(self, int iconType=TBI_DEFAULT_TYPE) -> TaskBarIcon""" _windows_.TaskBarIcon_swiginit(self,_windows_.new_TaskBarIcon(*args, **kwargs)) self._setOORInfo(self);TaskBarIcon._setCallbackInfo(self, self, TaskBarIcon)
[ "def", "__init__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "_windows_", ".", "TaskBarIcon_swiginit", "(", "self", ",", "_windows_", ".", "new_TaskBarIcon", "(", "*", "args", ",", "*", "*", "kwargs", ")", ")", "self", ".", "_setOORInfo", "(", "self", ")", "TaskBarIcon", ".", "_setCallbackInfo", "(", "self", ",", "self", ",", "TaskBarIcon", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_windows.py#L2810-L2813
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/prompt-toolkit/py2/prompt_toolkit/document.py
python
Document.get_end_of_line_position
(self)
return len(self.current_line_after_cursor)
Relative position for the end of this line.
Relative position for the end of this line.
[ "Relative", "position", "for", "the", "end", "of", "this", "line", "." ]
def get_end_of_line_position(self): """ Relative position for the end of this line. """ return len(self.current_line_after_cursor)
[ "def", "get_end_of_line_position", "(", "self", ")", ":", "return", "len", "(", "self", ".", "current_line_after_cursor", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/prompt-toolkit/py2/prompt_toolkit/document.py#L741-L743
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/share/doc/python3.7/examples/Tools/iobench/iobench.py
python
read_seek_blockwise
(f)
alternate read & seek 1000 units
alternate read & seek 1000 units
[ "alternate", "read", "&", "seek", "1000", "units" ]
def read_seek_blockwise(f): """ alternate read & seek 1000 units """ f.seek(0) while f.read(1000): f.seek(1000, 1)
[ "def", "read_seek_blockwise", "(", "f", ")", ":", "f", ".", "seek", "(", "0", ")", "while", "f", ".", "read", "(", "1000", ")", ":", "f", ".", "seek", "(", "1000", ",", "1", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/share/doc/python3.7/examples/Tools/iobench/iobench.py#L129-L133