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
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_misc.py
python
StandardPaths.GetUserLocalDataDir
(*args, **kwargs)
return _misc_.StandardPaths_GetUserLocalDataDir(*args, **kwargs)
GetUserLocalDataDir(self) -> String Return the directory for user data files which shouldn't be shared with the other machines Same as `GetUserDataDir` for all platforms except Windows where it is the 'Local Settings/Application Data/appname' directory.
GetUserLocalDataDir(self) -> String
[ "GetUserLocalDataDir", "(", "self", ")", "-", ">", "String" ]
def GetUserLocalDataDir(*args, **kwargs): """ GetUserLocalDataDir(self) -> String Return the directory for user data files which shouldn't be shared with the other machines Same as `GetUserDataDir` for all platforms except Windows where it is the 'Local Settings/Application Data/appname' directory. """ return _misc_.StandardPaths_GetUserLocalDataDir(*args, **kwargs)
[ "def", "GetUserLocalDataDir", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_misc_", ".", "StandardPaths_GetUserLocalDataDir", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_misc.py#L6364-L6374
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/aui.py
python
AuiToolBarArt.SetFlags
(*args, **kwargs)
return _aui.AuiToolBarArt_SetFlags(*args, **kwargs)
SetFlags(self, int flags)
SetFlags(self, int flags)
[ "SetFlags", "(", "self", "int", "flags", ")" ]
def SetFlags(*args, **kwargs): """SetFlags(self, int flags)""" return _aui.AuiToolBarArt_SetFlags(*args, **kwargs)
[ "def", "SetFlags", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_aui", ".", "AuiToolBarArt_SetFlags", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/aui.py#L1894-L1896
CNevd/Difacto_DMLC
f16862e35062707b1cf7e37d04d9b6ae34bbfd28
dmlc-core/tracker/tracker.py
python
RabitTracker.find_share_ring
(self, tree_map, parent_map, r)
return rlst
get a ring structure that tends to share nodes with the tree return a list starting from r
get a ring structure that tends to share nodes with the tree return a list starting from r
[ "get", "a", "ring", "structure", "that", "tends", "to", "share", "nodes", "with", "the", "tree", "return", "a", "list", "starting", "from", "r" ]
def find_share_ring(self, tree_map, parent_map, r): """ get a ring structure that tends to share nodes with the tree return a list starting from r """ nset = set(tree_map[r]) cset = nset - set([parent_map[r]]) if len(cset) == 0: return [r] rlst = [r] cnt = 0 for v in cset: vlst = self.find_share_ring(tree_map, parent_map, v) cnt += 1 if cnt == len(cset): vlst.reverse() rlst += vlst return rlst
[ "def", "find_share_ring", "(", "self", ",", "tree_map", ",", "parent_map", ",", "r", ")", ":", "nset", "=", "set", "(", "tree_map", "[", "r", "]", ")", "cset", "=", "nset", "-", "set", "(", "[", "parent_map", "[", "r", "]", "]", ")", "if", "len",...
https://github.com/CNevd/Difacto_DMLC/blob/f16862e35062707b1cf7e37d04d9b6ae34bbfd28/dmlc-core/tracker/tracker.py#L174-L191
Kitware/ParaView
f760af9124ff4634b23ebbeab95a4f56e0261955
Wrapping/Python/paraview/catalyst/__init__.py
python
get_args
()
return v2_internals._get_active_arguments()
For the active pipeline script, returns "args", if any, specified when the script initialized in the Catalyst adaptor. This is currently only supported for adaptors that use Catalyst 2.0 Adaptor API. For legacy adaptors, this will simply return an empty list. Return value is a list of strings.
For the active pipeline script, returns "args", if any, specified when the script initialized in the Catalyst adaptor.
[ "For", "the", "active", "pipeline", "script", "returns", "args", "if", "any", "specified", "when", "the", "script", "initialized", "in", "the", "Catalyst", "adaptor", "." ]
def get_args(): """For the active pipeline script, returns "args", if any, specified when the script initialized in the Catalyst adaptor. This is currently only supported for adaptors that use Catalyst 2.0 Adaptor API. For legacy adaptors, this will simply return an empty list. Return value is a list of strings. """ from . import v2_internals return v2_internals._get_active_arguments()
[ "def", "get_args", "(", ")", ":", "from", ".", "import", "v2_internals", "return", "v2_internals", ".", "_get_active_arguments", "(", ")" ]
https://github.com/Kitware/ParaView/blob/f760af9124ff4634b23ebbeab95a4f56e0261955/Wrapping/Python/paraview/catalyst/__init__.py#L25-L35
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scikit-learn/py3/sklearn/utils/stats.py
python
_weighted_percentile
(array, sample_weight, percentile=50)
return array[sorted_idx[percentile_idx]]
Compute the weighted ``percentile`` of ``array`` with ``sample_weight``.
Compute the weighted ``percentile`` of ``array`` with ``sample_weight``.
[ "Compute", "the", "weighted", "percentile", "of", "array", "with", "sample_weight", "." ]
def _weighted_percentile(array, sample_weight, percentile=50): """ Compute the weighted ``percentile`` of ``array`` with ``sample_weight``. """ sorted_idx = np.argsort(array) # Find index of median prediction for each sample weight_cdf = stable_cumsum(sample_weight[sorted_idx]) percentile_idx = np.searchsorted( weight_cdf, (percentile / 100.) * weight_cdf[-1]) # in rare cases, percentile_idx equals to len(sorted_idx) percentile_idx = np.clip(percentile_idx, 0, len(sorted_idx)-1) return array[sorted_idx[percentile_idx]]
[ "def", "_weighted_percentile", "(", "array", ",", "sample_weight", ",", "percentile", "=", "50", ")", ":", "sorted_idx", "=", "np", ".", "argsort", "(", "array", ")", "# Find index of median prediction for each sample", "weight_cdf", "=", "stable_cumsum", "(", "samp...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py3/sklearn/utils/stats.py#L6-L18
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/compiler/tensorrt/trt_convert.py
python
TrtGraphConverterV2._run_conversion
(self, meta_graph_def)
return tf_optimizer.OptimizeGraph( grappler_session_config, meta_graph_def, graph_id=b"tf_graph")
Run Grappler's OptimizeGraph() tool to convert the graph. Args: meta_graph_def: the MetaGraphDef instance to run the optimizations on. Returns: The optimized GraphDef.
Run Grappler's OptimizeGraph() tool to convert the graph.
[ "Run", "Grappler", "s", "OptimizeGraph", "()", "tool", "to", "convert", "the", "graph", "." ]
def _run_conversion(self, meta_graph_def): """Run Grappler's OptimizeGraph() tool to convert the graph. Args: meta_graph_def: the MetaGraphDef instance to run the optimizations on. Returns: The optimized GraphDef. """ rewriter_config = get_tensorrt_rewriter_config( conversion_params=self._conversion_params, is_v2=True) grappler_session_config = config_pb2.ConfigProto() grappler_session_config.graph_options.rewrite_options.CopyFrom( rewriter_config) return tf_optimizer.OptimizeGraph( grappler_session_config, meta_graph_def, graph_id=b"tf_graph")
[ "def", "_run_conversion", "(", "self", ",", "meta_graph_def", ")", ":", "rewriter_config", "=", "get_tensorrt_rewriter_config", "(", "conversion_params", "=", "self", ".", "_conversion_params", ",", "is_v2", "=", "True", ")", "grappler_session_config", "=", "config_pb...
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/compiler/tensorrt/trt_convert.py#L908-L923
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/rnn/python/ops/rnn_cell.py
python
AttentionCellWrapper.call
(self, inputs, state)
return output, new_state
Long short-term memory cell with attention (LSTMA).
Long short-term memory cell with attention (LSTMA).
[ "Long", "short", "-", "term", "memory", "cell", "with", "attention", "(", "LSTMA", ")", "." ]
def call(self, inputs, state): """Long short-term memory cell with attention (LSTMA).""" if self._state_is_tuple: state, attns, attn_states = state else: states = state state = array_ops.slice(states, [0, 0], [-1, self._cell.state_size]) attns = array_ops.slice(states, [0, self._cell.state_size], [-1, self._attn_size]) attn_states = array_ops.slice( states, [0, self._cell.state_size + self._attn_size], [-1, self._attn_size * self._attn_length]) attn_states = array_ops.reshape(attn_states, [-1, self._attn_length, self._attn_size]) input_size = self._input_size if input_size is None: input_size = inputs.get_shape().as_list()[1] if self._linear1 is None: self._linear1 = _Linear([inputs, attns], input_size, True) inputs = self._linear1([inputs, attns]) cell_output, new_state = self._cell(inputs, state) if self._state_is_tuple: new_state_cat = array_ops.concat(nest.flatten(new_state), 1) else: new_state_cat = new_state new_attns, new_attn_states = self._attention(new_state_cat, attn_states) with vs.variable_scope("attn_output_projection"): if self._linear2 is None: self._linear2 = _Linear([cell_output, new_attns], self._attn_size, True) output = self._linear2([cell_output, new_attns]) new_attn_states = array_ops.concat( [new_attn_states, array_ops.expand_dims(output, 1)], 1) new_attn_states = array_ops.reshape( new_attn_states, [-1, self._attn_length * self._attn_size]) new_state = (new_state, new_attns, new_attn_states) if not self._state_is_tuple: new_state = array_ops.concat(list(new_state), 1) return output, new_state
[ "def", "call", "(", "self", ",", "inputs", ",", "state", ")", ":", "if", "self", ".", "_state_is_tuple", ":", "state", ",", "attns", ",", "attn_states", "=", "state", "else", ":", "states", "=", "state", "state", "=", "array_ops", ".", "slice", "(", ...
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/rnn/python/ops/rnn_cell.py#L1194-L1231
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/propgrid.py
python
PropertyGridManager.SetSplitterLeft
(*args, **kwargs)
return _propgrid.PropertyGridManager_SetSplitterLeft(*args, **kwargs)
SetSplitterLeft(self, bool subProps=False, bool allPages=True)
SetSplitterLeft(self, bool subProps=False, bool allPages=True)
[ "SetSplitterLeft", "(", "self", "bool", "subProps", "=", "False", "bool", "allPages", "=", "True", ")" ]
def SetSplitterLeft(*args, **kwargs): """SetSplitterLeft(self, bool subProps=False, bool allPages=True)""" return _propgrid.PropertyGridManager_SetSplitterLeft(*args, **kwargs)
[ "def", "SetSplitterLeft", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_propgrid", ".", "PropertyGridManager_SetSplitterLeft", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/propgrid.py#L3582-L3584
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/ops/_op_impl/tbe/floor_div_ds.py
python
_floor_div_ds_tbe
()
return
FloorDiv TBE register
FloorDiv TBE register
[ "FloorDiv", "TBE", "register" ]
def _floor_div_ds_tbe(): """FloorDiv TBE register""" return
[ "def", "_floor_div_ds_tbe", "(", ")", ":", "return" ]
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/ops/_op_impl/tbe/floor_div_ds.py#L40-L42
weolar/miniblink49
1c4678db0594a4abde23d3ebbcc7cd13c3170777
third_party/jinja2/filters.py
python
do_wordcount
(s)
return len(_word_re.findall(s))
Count the words in that string.
Count the words in that string.
[ "Count", "the", "words", "in", "that", "string", "." ]
def do_wordcount(s): """Count the words in that string.""" return len(_word_re.findall(s))
[ "def", "do_wordcount", "(", "s", ")", ":", "return", "len", "(", "_word_re", ".", "findall", "(", "s", ")", ")" ]
https://github.com/weolar/miniblink49/blob/1c4678db0594a4abde23d3ebbcc7cd13c3170777/third_party/jinja2/filters.py#L501-L503
panda3d/panda3d
833ad89ebad58395d0af0b7ec08538e5e4308265
direct/src/stdpy/glob.py
python
glob
(pathname)
return list(iglob(pathname))
Return a list of paths matching a pathname pattern. The pattern may contain simple shell-style wildcards a la fnmatch.
Return a list of paths matching a pathname pattern.
[ "Return", "a", "list", "of", "paths", "matching", "a", "pathname", "pattern", "." ]
def glob(pathname): """Return a list of paths matching a pathname pattern. The pattern may contain simple shell-style wildcards a la fnmatch. """ return list(iglob(pathname))
[ "def", "glob", "(", "pathname", ")", ":", "return", "list", "(", "iglob", "(", "pathname", ")", ")" ]
https://github.com/panda3d/panda3d/blob/833ad89ebad58395d0af0b7ec08538e5e4308265/direct/src/stdpy/glob.py#L12-L18
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/_windows.py
python
Frame.SetMenuBar
(*args, **kwargs)
return _windows_.Frame_SetMenuBar(*args, **kwargs)
SetMenuBar(self, MenuBar menubar)
SetMenuBar(self, MenuBar menubar)
[ "SetMenuBar", "(", "self", "MenuBar", "menubar", ")" ]
def SetMenuBar(*args, **kwargs): """SetMenuBar(self, MenuBar menubar)""" return _windows_.Frame_SetMenuBar(*args, **kwargs)
[ "def", "SetMenuBar", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_windows_", ".", "Frame_SetMenuBar", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_windows.py#L591-L593
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/binhex.py
python
_Hqxdecoderengine.read
(self, totalwtd)
return decdata
Read at least wtd bytes (or until EOF)
Read at least wtd bytes (or until EOF)
[ "Read", "at", "least", "wtd", "bytes", "(", "or", "until", "EOF", ")" ]
def read(self, totalwtd): """Read at least wtd bytes (or until EOF)""" decdata = b'' wtd = totalwtd # # The loop here is convoluted, since we don't really now how # much to decode: there may be newlines in the incoming data. while wtd > 0: if self.eof: return decdata wtd = ((wtd + 2) // 3) * 4 data = self.ifp.read(wtd) # # Next problem: there may not be a complete number of # bytes in what we pass to a2b. Solve by yet another # loop. # while True: try: decdatacur, self.eof = binascii.a2b_hqx(data) break except binascii.Incomplete: pass newdata = self.ifp.read(1) if not newdata: raise Error('Premature EOF on binhex file') data = data + newdata decdata = decdata + decdatacur wtd = totalwtd - len(decdata) if not decdata and not self.eof: raise Error('Premature EOF on binhex file') return decdata
[ "def", "read", "(", "self", ",", "totalwtd", ")", ":", "decdata", "=", "b''", "wtd", "=", "totalwtd", "#", "# The loop here is convoluted, since we don't really now how", "# much to decode: there may be newlines in the incoming data.", "while", "wtd", ">", "0", ":", "if",...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/binhex.py#L261-L291
projectchrono/chrono
92015a8a6f84ef63ac8206a74e54a676251dcc89
src/demos/python/chrono-tensorflow/PPO/run_episode.py
python
run_episode
(env, policy, scaler, time_state)
return (np.concatenate(observes), np.concatenate(actions), np.array(rewards, dtype=np.float64), np.concatenate(unscaled_obs))
Run single episode Args: env: environment (object) policy: policy object with sample() method scaler: scaler object, scales/offsets each observation Returns: 4-tuple of NumPy arrays observes: shape = (episode len, obs_dim) actions: shape = (episode len, act_dim) rewards: shape = (episode len,) unscaled_obs: dataset for training scaler, shape = (episode len, obs_dim)
Run single episode
[ "Run", "single", "episode" ]
def run_episode(env, policy, scaler, time_state): """ Run single episode Args: env: environment (object) policy: policy object with sample() method scaler: scaler object, scales/offsets each observation Returns: 4-tuple of NumPy arrays observes: shape = (episode len, obs_dim) actions: shape = (episode len, act_dim) rewards: shape = (episode len,) unscaled_obs: dataset for training scaler, shape = (episode len, obs_dim) """ obs = env.reset() #resets whenever an episode begins observes, actions, rewards, unscaled_obs = [], [], [], [] done = False step = 0.0 scale, offset = scaler.get() if time_state: scale[-1] = 1.0 # don't scale time step feature offset[-1] = 0.0 # don't offset time step feature while not done: obs = obs.astype(np.float64).reshape((1, -1)) if time_state: obs = np.append(obs, [[step]], axis=1) # add time step feature TODO: check if this extra state is useful unscaled_obs.append(obs) obs = (obs - offset) * scale # center and scale observations TODO: check ifscaler is useful (it should be according to literature) observes.append(obs) action = policy.sample(obs).reshape((1, -1)).astype(np.float64) actions.append(action) obs, reward, done, _ = env.step(action) #state, reward, done, info = env.step(action) if not isinstance(reward, float): reward = np.asscalar(reward) rewards.append(reward) step += 1e-3 # increments time step feature return (np.concatenate(observes), np.concatenate(actions), np.array(rewards, dtype=np.float64), np.concatenate(unscaled_obs))
[ "def", "run_episode", "(", "env", ",", "policy", ",", "scaler", ",", "time_state", ")", ":", "obs", "=", "env", ".", "reset", "(", ")", "#resets whenever an episode begins", "observes", ",", "actions", ",", "rewards", ",", "unscaled_obs", "=", "[", "]", ",...
https://github.com/projectchrono/chrono/blob/92015a8a6f84ef63ac8206a74e54a676251dcc89/src/demos/python/chrono-tensorflow/PPO/run_episode.py#L34-L74
OpenChemistry/tomviz
0a903679318f191cb7dd3eb5ff5bc3a7d3320d9a
tomviz/python/AddPoissonNoise.py
python
AddPoissonNoiseOperator.transform
(self, dataset, N=25)
Add Poisson noise to tilt images
Add Poisson noise to tilt images
[ "Add", "Poisson", "noise", "to", "tilt", "images" ]
def transform(self, dataset, N=25): """Add Poisson noise to tilt images""" self.progress.maximum = 1 tiltSeries = dataset.active_scalars.astype(float) if tiltSeries is None: raise RuntimeError("No scalars found!") Ndata = tiltSeries.shape[0] * tiltSeries.shape[1] self.progress.maximum = tiltSeries.shape[2] step = 0 for i in range(tiltSeries.shape[2]): if self.canceled: return tiltImage = tiltSeries[:, :, i].copy() tiltImage = tiltImage / np.sum(tiltSeries[:, :, i]) * (Ndata * N) tiltImage = np.random.poisson(tiltImage) tiltImage = tiltImage * np.sum(tiltSeries[:, :, i]) / (Ndata * N) tiltSeries[:, :, i] = tiltImage.copy() step += 1 self.progress.value = step dataset.active_scalars = tiltSeries
[ "def", "transform", "(", "self", ",", "dataset", ",", "N", "=", "25", ")", ":", "self", ".", "progress", ".", "maximum", "=", "1", "tiltSeries", "=", "dataset", ".", "active_scalars", ".", "astype", "(", "float", ")", "if", "tiltSeries", "is", "None", ...
https://github.com/OpenChemistry/tomviz/blob/0a903679318f191cb7dd3eb5ff5bc3a7d3320d9a/tomviz/python/AddPoissonNoise.py#L7-L32
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/targets/arrayobj.py
python
make_array_ndindex
(context, builder, sig, args)
return impl_ret_borrowed(context, builder, sig.return_type, res)
ndindex(*shape)
ndindex(*shape)
[ "ndindex", "(", "*", "shape", ")" ]
def make_array_ndindex(context, builder, sig, args): """ndindex(*shape)""" shape = [context.cast(builder, arg, argty, types.intp) for argty, arg in zip(sig.args, args)] nditercls = make_ndindex_cls(types.NumpyNdIndexType(len(shape))) nditer = nditercls(context, builder) nditer.init_specific(context, builder, shape) res = nditer._getvalue() return impl_ret_borrowed(context, builder, sig.return_type, res)
[ "def", "make_array_ndindex", "(", "context", ",", "builder", ",", "sig", ",", "args", ")", ":", "shape", "=", "[", "context", ".", "cast", "(", "builder", ",", "arg", ",", "argty", ",", "types", ".", "intp", ")", "for", "argty", ",", "arg", "in", "...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/targets/arrayobj.py#L3254-L3264
naver/sling
5671cd445a2caae0b4dd0332299e4cfede05062c
webkit/Tools/Scripts/webkitpy/thirdparty/mod_pywebsocket/standalone.py
python
WebSocketRequestHandler.is_cgi
(self)
return False
Test whether self.path corresponds to a CGI script. Add extra check that self.path doesn't contains .. Also check if the file is a executable file or not. If the file is not executable, it is handled as static file or dir rather than a CGI script.
Test whether self.path corresponds to a CGI script.
[ "Test", "whether", "self", ".", "path", "corresponds", "to", "a", "CGI", "script", "." ]
def is_cgi(self): """Test whether self.path corresponds to a CGI script. Add extra check that self.path doesn't contains .. Also check if the file is a executable file or not. If the file is not executable, it is handled as static file or dir rather than a CGI script. """ if CGIHTTPServer.CGIHTTPRequestHandler.is_cgi(self): if '..' in self.path: return False # strip query parameter from request path resource_name = self.path.split('?', 2)[0] # convert resource_name into real path name in filesystem. scriptfile = self.translate_path(resource_name) if not os.path.isfile(scriptfile): return False if not self.is_executable(scriptfile): return False return True return False
[ "def", "is_cgi", "(", "self", ")", ":", "if", "CGIHTTPServer", ".", "CGIHTTPRequestHandler", ".", "is_cgi", "(", "self", ")", ":", "if", "'..'", "in", "self", ".", "path", ":", "return", "False", "# strip query parameter from request path", "resource_name", "=",...
https://github.com/naver/sling/blob/5671cd445a2caae0b4dd0332299e4cfede05062c/webkit/Tools/Scripts/webkitpy/thirdparty/mod_pywebsocket/standalone.py#L779-L800
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_core.py
python
MouseEvent.Aux2Up
(*args, **kwargs)
return _core_.MouseEvent_Aux2Up(*args, **kwargs)
Aux2Up(self) -> bool Returns true if the AUX2 mouse button state changed to up.
Aux2Up(self) -> bool
[ "Aux2Up", "(", "self", ")", "-", ">", "bool" ]
def Aux2Up(*args, **kwargs): """ Aux2Up(self) -> bool Returns true if the AUX2 mouse button state changed to up. """ return _core_.MouseEvent_Aux2Up(*args, **kwargs)
[ "def", "Aux2Up", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "MouseEvent_Aux2Up", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_core.py#L5697-L5703
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/idlelib/tooltip.py
python
TooltipBase.position_window
(self)
(re)-set the tooltip's screen position
(re)-set the tooltip's screen position
[ "(", "re", ")", "-", "set", "the", "tooltip", "s", "screen", "position" ]
def position_window(self): """(re)-set the tooltip's screen position""" x, y = self.get_position() root_x = self.anchor_widget.winfo_rootx() + x root_y = self.anchor_widget.winfo_rooty() + y self.tipwindow.wm_geometry("+%d+%d" % (root_x, root_y))
[ "def", "position_window", "(", "self", ")", ":", "x", ",", "y", "=", "self", ".", "get_position", "(", ")", "root_x", "=", "self", ".", "anchor_widget", ".", "winfo_rootx", "(", ")", "+", "x", "root_y", "=", "self", ".", "anchor_widget", ".", "winfo_ro...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/idlelib/tooltip.py#L47-L52
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/scipy/optimize/_differentialevolution.py
python
DifferentialEvolutionSolver._select_samples
(self, candidate, number_samples)
return idxs
obtain random integers from range(self.num_population_members), without replacement. You can't have the original candidate either.
obtain random integers from range(self.num_population_members), without replacement. You can't have the original candidate either.
[ "obtain", "random", "integers", "from", "range", "(", "self", ".", "num_population_members", ")", "without", "replacement", ".", "You", "can", "t", "have", "the", "original", "candidate", "either", "." ]
def _select_samples(self, candidate, number_samples): """ obtain random integers from range(self.num_population_members), without replacement. You can't have the original candidate either. """ idxs = list(range(self.num_population_members)) idxs.remove(candidate) self.random_number_generator.shuffle(idxs) idxs = idxs[:number_samples] return idxs
[ "def", "_select_samples", "(", "self", ",", "candidate", ",", "number_samples", ")", ":", "idxs", "=", "list", "(", "range", "(", "self", ".", "num_population_members", ")", ")", "idxs", ".", "remove", "(", "candidate", ")", "self", ".", "random_number_gener...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/scipy/optimize/_differentialevolution.py#L778-L787
miyosuda/TensorFlowAndroidMNIST
7b5a4603d2780a8a2834575706e9001977524007
jni-build/jni/include/tensorflow/contrib/metrics/python/ops/metric_ops.py
python
streaming_sparse_precision_at_k
(predictions, labels, k, class_id=None, ignore_mask=None, metrics_collections=None, updates_collections=None, name=None)
Computes precision@k of the predictions with respect to sparse labels. If `class_id` is specified, we calculate precision by considering only the entries in the batch for which `class_id` is in the top-k highest `predictions`, and computing the fraction of them for which `class_id` is indeed a correct label. If `class_id` is not specified, we'll calculate precision as how often on average a class among the top-k classes with the highest predicted values of a batch entry is correct and can be found in the label for that entry. `streaming_sparse_precision_at_k` creates two local variables, `true_positive_at_<k>` and `false_positive_at_<k>`, that are used to compute the precision@k frequency. This frequency is ultimately returned as `precision_at_<k>`: an idempotent operation that simply divides `true_positive_at_<k>` by total (`true_positive_at_<k>` + `false_positive_at_<k>`). To facilitate the estimation of precision@k over a stream of data, the function utilizes three steps. * A `top_k` operation computes a tensor whose elements indicate the top `k` predictions of the `predictions` `Tensor`. * Set operations are applied to `top_k` and `labels` to calculate true positives and false positives. * An `update_op` operation increments `true_positive_at_<k>` and `false_positive_at_<k>`. It also returns the precision value. Args: predictions: Float `Tensor` with shape [D1, ... DN, num_classes] where N >= 1. Commonly, N=1 and predictions has shape [batch size, num_classes]. The final dimension contains the logit values for each class. [D1, ... DN] must match `labels`. labels: `int64` `Tensor` or `SparseTensor` with shape [D1, ... DN, num_labels], where N >= 1 and num_labels is the number of target classes for the associated prediction. Commonly, N=1 and `labels` has shape [batch_size, num_labels]. [D1, ... DN] must match `predictions_idx`. Values should be in range [0, num_classes], where num_classes is the last dimension of `predictions`. k: Integer, k for @k metric. class_id: Integer class ID for which we want binary metrics. This should be in range [0, num_classes], where num_classes is the last dimension of `predictions`. ignore_mask: An optional, binary tensor whose shape is broadcastable to the the first [D1, ... DN] dimensions of `predictions_idx` and `labels`. metrics_collections: An optional list of collections that values should be added to. updates_collections: An optional list of collections that updates should be added to. name: Name of new update operation, and namespace for other dependant ops. Returns: precision: Scalar `float64` `Tensor` with the value of `true_positives` divided by the sum of `true_positives` and `false_positives`. update_op: `Operation` that increments `true_positives` and `false_positives` variables appropriately, and whose value matches `precision`.
Computes precision@k of the predictions with respect to sparse labels.
[ "Computes", "precision@k", "of", "the", "predictions", "with", "respect", "to", "sparse", "labels", "." ]
def streaming_sparse_precision_at_k(predictions, labels, k, class_id=None, ignore_mask=None, metrics_collections=None, updates_collections=None, name=None): """Computes precision@k of the predictions with respect to sparse labels. If `class_id` is specified, we calculate precision by considering only the entries in the batch for which `class_id` is in the top-k highest `predictions`, and computing the fraction of them for which `class_id` is indeed a correct label. If `class_id` is not specified, we'll calculate precision as how often on average a class among the top-k classes with the highest predicted values of a batch entry is correct and can be found in the label for that entry. `streaming_sparse_precision_at_k` creates two local variables, `true_positive_at_<k>` and `false_positive_at_<k>`, that are used to compute the precision@k frequency. This frequency is ultimately returned as `precision_at_<k>`: an idempotent operation that simply divides `true_positive_at_<k>` by total (`true_positive_at_<k>` + `false_positive_at_<k>`). To facilitate the estimation of precision@k over a stream of data, the function utilizes three steps. * A `top_k` operation computes a tensor whose elements indicate the top `k` predictions of the `predictions` `Tensor`. * Set operations are applied to `top_k` and `labels` to calculate true positives and false positives. * An `update_op` operation increments `true_positive_at_<k>` and `false_positive_at_<k>`. It also returns the precision value. Args: predictions: Float `Tensor` with shape [D1, ... DN, num_classes] where N >= 1. Commonly, N=1 and predictions has shape [batch size, num_classes]. The final dimension contains the logit values for each class. [D1, ... DN] must match `labels`. labels: `int64` `Tensor` or `SparseTensor` with shape [D1, ... DN, num_labels], where N >= 1 and num_labels is the number of target classes for the associated prediction. Commonly, N=1 and `labels` has shape [batch_size, num_labels]. [D1, ... DN] must match `predictions_idx`. Values should be in range [0, num_classes], where num_classes is the last dimension of `predictions`. k: Integer, k for @k metric. class_id: Integer class ID for which we want binary metrics. This should be in range [0, num_classes], where num_classes is the last dimension of `predictions`. ignore_mask: An optional, binary tensor whose shape is broadcastable to the the first [D1, ... DN] dimensions of `predictions_idx` and `labels`. metrics_collections: An optional list of collections that values should be added to. updates_collections: An optional list of collections that updates should be added to. name: Name of new update operation, and namespace for other dependant ops. Returns: precision: Scalar `float64` `Tensor` with the value of `true_positives` divided by the sum of `true_positives` and `false_positives`. update_op: `Operation` that increments `true_positives` and `false_positives` variables appropriately, and whose value matches `precision`. """ default_name = 'precision_at_%d' % k if class_id is not None: default_name = '%s_class%d' % (default_name, class_id) with ops.op_scope([predictions, labels], name, default_name) as scope: _, top_k_idx = nn.top_k(predictions, k) top_k_idx = math_ops.to_int64(top_k_idx) tp, tp_update = _streaming_sparse_true_positive_at_k( predictions_idx=top_k_idx, labels=labels, k=k, class_id=class_id, ignore_mask=ignore_mask) fp, fp_update = _streaming_sparse_false_positive_at_k( predictions_idx=top_k_idx, labels=labels, k=k, class_id=class_id, ignore_mask=ignore_mask) metric = math_ops.div(tp, math_ops.add(tp, fp), name=scope) update = math_ops.div( tp_update, math_ops.add(tp_update, fp_update), name='update') if metrics_collections: ops.add_to_collections(metrics_collections, metric) if updates_collections: ops.add_to_collections(updates_collections, update) return metric, update
[ "def", "streaming_sparse_precision_at_k", "(", "predictions", ",", "labels", ",", "k", ",", "class_id", "=", "None", ",", "ignore_mask", "=", "None", ",", "metrics_collections", "=", "None", ",", "updates_collections", "=", "None", ",", "name", "=", "None", ")...
https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/contrib/metrics/python/ops/metric_ops.py#L1114-L1197
cornell-zhang/heterocl
6d9e4b4acc2ee2707b2d25b27298c0335bccedfd
python/heterocl/tvm/contrib/nnpack.py
python
fully_connected_output
(lhs, rhs, nthreads=1)
return _api.extern( (n, m), [lhs, rhs], lambda ins, outs: _intrin.call_packed( "tvm.contrib.nnpack.fully_connected_output", ins[0], ins[1], outs[0], nthreads), name="C")
Create an extern op that compute fully connected of 2D tensor lhs and 2D tensor rhs with nnpack. Parameters ---------- lhs : Tensor lhs 2D matrix input[batch_size][input_channels] of FP32 elements rhs : Tensor lhs 2D matrix kernel[output_channels][input_channels] of FP32 elements Returns ------- C : Tensor lhs 2D array out[batch_size][output_channels] of FP32 elements.
Create an extern op that compute fully connected of 2D tensor lhs and 2D tensor rhs with nnpack.
[ "Create", "an", "extern", "op", "that", "compute", "fully", "connected", "of", "2D", "tensor", "lhs", "and", "2D", "tensor", "rhs", "with", "nnpack", "." ]
def fully_connected_output(lhs, rhs, nthreads=1): """Create an extern op that compute fully connected of 2D tensor lhs and 2D tensor rhs with nnpack. Parameters ---------- lhs : Tensor lhs 2D matrix input[batch_size][input_channels] of FP32 elements rhs : Tensor lhs 2D matrix kernel[output_channels][input_channels] of FP32 elements Returns ------- C : Tensor lhs 2D array out[batch_size][output_channels] of FP32 elements. """ n = lhs.shape[0] m = rhs.shape[0] return _api.extern( (n, m), [lhs, rhs], lambda ins, outs: _intrin.call_packed( "tvm.contrib.nnpack.fully_connected_output", ins[0], ins[1], outs[0], nthreads), name="C")
[ "def", "fully_connected_output", "(", "lhs", ",", "rhs", ",", "nthreads", "=", "1", ")", ":", "n", "=", "lhs", ".", "shape", "[", "0", "]", "m", "=", "rhs", ".", "shape", "[", "0", "]", "return", "_api", ".", "extern", "(", "(", "n", ",", "m", ...
https://github.com/cornell-zhang/heterocl/blob/6d9e4b4acc2ee2707b2d25b27298c0335bccedfd/python/heterocl/tvm/contrib/nnpack.py#L42-L64
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_core.py
python
Position.SetColumn
(*args, **kwargs)
return _core_.Position_SetColumn(*args, **kwargs)
SetColumn(self, int column)
SetColumn(self, int column)
[ "SetColumn", "(", "self", "int", "column", ")" ]
def SetColumn(*args, **kwargs): """SetColumn(self, int column)""" return _core_.Position_SetColumn(*args, **kwargs)
[ "def", "SetColumn", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "Position_SetColumn", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_core.py#L2102-L2104
cmu-db/peloton
484d76df9344cb5c153a2c361c5d5018912d4cf4
third_party/iwyu/iwyu_tool.py
python
_bootstrap
()
Parse arguments and dispatch to main().
Parse arguments and dispatch to main().
[ "Parse", "arguments", "and", "dispatch", "to", "main", "()", "." ]
def _bootstrap(): """ Parse arguments and dispatch to main(). """ # This hackery is necessary to add the forwarded IWYU args to the # usage and help strings. def customize_usage(parser): """ Rewrite the parser's format_usage. """ original_format_usage = parser.format_usage parser.format_usage = lambda: original_format_usage().rstrip() + \ ' -- [<IWYU args>]' + os.linesep def customize_help(parser): """ Rewrite the parser's format_help. """ original_format_help = parser.format_help def custom_help(): """ Customized help string, calls the adjusted format_usage. """ helpmsg = original_format_help() helplines = helpmsg.splitlines() helplines[0] = parser.format_usage().rstrip() return os.linesep.join(helplines) + os.linesep parser.format_help = custom_help # Parse arguments parser = argparse.ArgumentParser( description='Include-what-you-use compilation database driver.', epilog='Assumes include-what-you-use is available on the PATH.') customize_usage(parser) customize_help(parser) parser.add_argument('-v', '--verbose', action='store_true', help='Print IWYU commands') parser.add_argument('-p', metavar='<build-path>', required=True, help='Compilation database path', dest='dbpath') parser.add_argument('source', nargs='*', help='Zero or more source files to run IWYU on. ' 'Defaults to all in compilation database.') def partition_args(argv): """ Split around '--' into driver args and IWYU args. """ try: dd = argv.index('--') return argv[:dd], argv[dd+1:] except ValueError: return argv, [] argv, iwyu_args = partition_args(sys.argv[1:]) args = parser.parse_args(argv) sys.exit(main(args.dbpath, args.source, args.verbose, iwyu_args))
[ "def", "_bootstrap", "(", ")", ":", "# This hackery is necessary to add the forwarded IWYU args to the", "# usage and help strings.", "def", "customize_usage", "(", "parser", ")", ":", "\"\"\" Rewrite the parser's format_usage. \"\"\"", "original_format_usage", "=", "parser", ".", ...
https://github.com/cmu-db/peloton/blob/484d76df9344cb5c153a2c361c5d5018912d4cf4/third_party/iwyu/iwyu_tool.py#L94-L142
kungfu-origin/kungfu
90c84b2b590855654cb9a6395ed050e0f7763512
core/deps/SQLiteCpp-2.3.0/cpplint.py
python
_SetCountingStyle
(level)
Sets the module's counting options.
Sets the module's counting options.
[ "Sets", "the", "module", "s", "counting", "options", "." ]
def _SetCountingStyle(level): """Sets the module's counting options.""" _cpplint_state.SetCountingStyle(level)
[ "def", "_SetCountingStyle", "(", "level", ")", ":", "_cpplint_state", ".", "SetCountingStyle", "(", "level", ")" ]
https://github.com/kungfu-origin/kungfu/blob/90c84b2b590855654cb9a6395ed050e0f7763512/core/deps/SQLiteCpp-2.3.0/cpplint.py#L778-L780
msracver/Deep-Image-Analogy
632b9287b42552e32dad64922967c8c9ec7fc4d3
scripts/download_model_binary.py
python
reporthook
(count, block_size, total_size)
From http://blog.moleculea.com/2012/10/04/urlretrieve-progres-indicator/
From http://blog.moleculea.com/2012/10/04/urlretrieve-progres-indicator/
[ "From", "http", ":", "//", "blog", ".", "moleculea", ".", "com", "/", "2012", "/", "10", "/", "04", "/", "urlretrieve", "-", "progres", "-", "indicator", "/" ]
def reporthook(count, block_size, total_size): """ From http://blog.moleculea.com/2012/10/04/urlretrieve-progres-indicator/ """ global start_time if count == 0: start_time = time.time() return duration = (time.time() - start_time) or 0.01 progress_size = int(count * block_size) speed = int(progress_size / (1024 * duration)) percent = int(count * block_size * 100 / total_size) sys.stdout.write("\r...%d%%, %d MB, %d KB/s, %d seconds passed" % (percent, progress_size / (1024 * 1024), speed, duration)) sys.stdout.flush()
[ "def", "reporthook", "(", "count", ",", "block_size", ",", "total_size", ")", ":", "global", "start_time", "if", "count", "==", "0", ":", "start_time", "=", "time", ".", "time", "(", ")", "return", "duration", "=", "(", "time", ".", "time", "(", ")", ...
https://github.com/msracver/Deep-Image-Analogy/blob/632b9287b42552e32dad64922967c8c9ec7fc4d3/scripts/download_model_binary.py#L13-L27
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/cachecontrol/adapter.py
python
CacheControlAdapter.build_response
( self, request, response, from_cache=False, cacheable_methods=None )
return resp
Build a response by making a request or using the cache. This will end up calling send and returning a potentially cached response
Build a response by making a request or using the cache.
[ "Build", "a", "response", "by", "making", "a", "request", "or", "using", "the", "cache", "." ]
def build_response( self, request, response, from_cache=False, cacheable_methods=None ): """ Build a response by making a request or using the cache. This will end up calling send and returning a potentially cached response """ cacheable = cacheable_methods or self.cacheable_methods if not from_cache and request.method in cacheable: # Check for any heuristics that might update headers # before trying to cache. if self.heuristic: response = self.heuristic.apply(response) # apply any expiration heuristics if response.status == 304: # We must have sent an ETag request. This could mean # that we've been expired already or that we simply # have an etag. In either case, we want to try and # update the cache if that is the case. cached_response = self.controller.update_cached_response( request, response ) if cached_response is not response: from_cache = True # We are done with the server response, read a # possible response body (compliant servers will # not return one, but we cannot be 100% sure) and # release the connection back to the pool. response.read(decode_content=False) response.release_conn() response = cached_response # We always cache the 301 responses elif response.status == 301: self.controller.cache_response(request, response) else: # Wrap the response file with a wrapper that will cache the # response when the stream has been consumed. response._fp = CallbackFileWrapper( response._fp, functools.partial( self.controller.cache_response, request, response ), ) if response.chunked: super_update_chunk_length = response._update_chunk_length def _update_chunk_length(self): super_update_chunk_length() if self.chunk_left == 0: self._fp._close() response._update_chunk_length = types.MethodType( _update_chunk_length, response ) resp = super(CacheControlAdapter, self).build_response(request, response) # See if we should invalidate the cache. if request.method in self.invalidating_methods and resp.ok: cache_url = self.controller.cache_url(request.url) self.cache.delete(cache_url) # Give the request a from_cache attr to let people use it resp.from_cache = from_cache return resp
[ "def", "build_response", "(", "self", ",", "request", ",", "response", ",", "from_cache", "=", "False", ",", "cacheable_methods", "=", "None", ")", ":", "cacheable", "=", "cacheable_methods", "or", "self", ".", "cacheable_methods", "if", "not", "from_cache", "...
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/cachecontrol/adapter.py#L57-L129
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/training/python/training/sequence_queueing_state_saver.py
python
NextQueuedSequenceBatch.save_state
(self, state_name, value, name=None)
Returns an op to save the current batch of state `state_name`. Args: state_name: string, matches a key provided in `initial_states`. value: A `Tensor`. Its type must match that of `initial_states[state_name].dtype`. If we had at input: ```python initial_states[state_name].get_shape() == [d1, d2, ...] ``` then the shape of `value` must match: ```python tf.shape(value) == [batch_size, d1, d2, ...] ``` name: string (optional). The name scope for newly created ops. Returns: A control flow op that stores the new state of each entry into the state saver. This op must be run for every iteration that accesses data from the state saver (otherwise the state saver will never progress through its states and run out of capacity). Raises: KeyError: if `state_name` does not match any of the initial states declared in `initial_states`.
Returns an op to save the current batch of state `state_name`.
[ "Returns", "an", "op", "to", "save", "the", "current", "batch", "of", "state", "state_name", "." ]
def save_state(self, state_name, value, name=None): """Returns an op to save the current batch of state `state_name`. Args: state_name: string, matches a key provided in `initial_states`. value: A `Tensor`. Its type must match that of `initial_states[state_name].dtype`. If we had at input: ```python initial_states[state_name].get_shape() == [d1, d2, ...] ``` then the shape of `value` must match: ```python tf.shape(value) == [batch_size, d1, d2, ...] ``` name: string (optional). The name scope for newly created ops. Returns: A control flow op that stores the new state of each entry into the state saver. This op must be run for every iteration that accesses data from the state saver (otherwise the state saver will never progress through its states and run out of capacity). Raises: KeyError: if `state_name` does not match any of the initial states declared in `initial_states`. """ if state_name not in self._state_saver._received_states.keys(): raise KeyError("state was not declared: %s" % state_name) default_name = "InputQueueingStateSaver_SaveState" with ops.name_scope(name, default_name, values=[value]): # Place all operations on the CPU. Barriers and queues are only # implemented for CPU, but all the other book-keeping operations # (reshape, shape, range, ...) would be placed on GPUs if available, # unless we explicitly tie them to CPU. with ops.colocate_with(self._state_saver._capacity_queue.queue_ref): indices_where_not_done = array_ops.reshape( array_ops.where_v2( math_ops.logical_not(self._state_saver._sequence_is_done)), [-1]) keeping_next_key = array_ops.gather( self._state_saver._received_next_key, indices_where_not_done) value = _check_shape( array_ops.identity( value, name="convert_%s" % state_name), array_ops.shape(self._state_saver._received_states[state_name])) keeping_state = array_ops.gather(value, indices_where_not_done) return self._state_saver._barrier.insert_many( self._state_saver._get_barrier_index("state", state_name), keeping_next_key, keeping_state, name="BarrierInsertState_%s" % state_name)
[ "def", "save_state", "(", "self", ",", "state_name", ",", "value", ",", "name", "=", "None", ")", ":", "if", "state_name", "not", "in", "self", ".", "_state_saver", ".", "_received_states", ".", "keys", "(", ")", ":", "raise", "KeyError", "(", "\"state w...
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/training/python/training/sequence_queueing_state_saver.py#L556-L611
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
tools/check_grd_for_unused_strings.py
python
CheckForUnusedGrdIDsInSources
(grd_files, src_dirs)
return 0
Will collect the message ids out of the given GRD files and then scan the source directories to try and figure out what ids are not currently being used by any source. grd_files: A list of GRD files to collect the ids from. src_dirs: A list of directories to walk looking for source files.
Will collect the message ids out of the given GRD files and then scan the source directories to try and figure out what ids are not currently being used by any source.
[ "Will", "collect", "the", "message", "ids", "out", "of", "the", "given", "GRD", "files", "and", "then", "scan", "the", "source", "directories", "to", "try", "and", "figure", "out", "what", "ids", "are", "not", "currently", "being", "used", "by", "any", "...
def CheckForUnusedGrdIDsInSources(grd_files, src_dirs): """Will collect the message ids out of the given GRD files and then scan the source directories to try and figure out what ids are not currently being used by any source. grd_files: A list of GRD files to collect the ids from. src_dirs: A list of directories to walk looking for source files. """ # Collect all the ids into a large map all_ids = set() file_id_map = {} for y in grd_files: handler = GrdIDExtractor() xml.sax.parse(y, handler) files_ids = handler.allIDs() file_id_map[y] = files_ids all_ids |= files_ids # The regex that will be used to check sources id_regex = re.compile('IDS_[A-Z0-9_]+') # Make sure the regex matches every id found. got_err = False for x in all_ids: match = id_regex.search(x) if match is None: print 'ERROR: "%s" did not match our regex' % (x) got_err = True if not match.group(0) is x: print 'ERROR: "%s" did not fully match our regex' % (x) got_err = True if got_err: return 1 # The regex for deciding what is a source file src_regex = re.compile('\.(([chm])|(mm)|(cc)|(cp)|(cpp)|(xib)|(py))$') ids_left = all_ids.copy() # Scanning time. for src_dir in src_dirs: for root, dirs, files in os.walk(src_dir): # Remove svn directories from recursion if '.svn' in dirs: dirs.remove('.svn') for file in files: if src_regex.search(file.lower()): full_path = os.path.join(root, file) src_file_contents = open(full_path).read() for match in sorted(set(id_regex.findall(src_file_contents))): if match in ids_left: ids_left.remove(match) if DEBUG: if not match in all_ids: print '%s had "%s", which was not in the found IDs' % \ (full_path, match) elif DEBUG > 1: full_path = os.path.join(root, file) print 'Skipping %s.' % (full_path) # Anything left? if len(ids_left) > 0: print 'The following ids are in GRD files, but *appear* to be unused:' for file_path, file_ids in file_id_map.iteritems(): missing = ids_left.intersection(file_ids) if len(missing) > 0: print ' %s:' % (file_path) print '\n'.join(' %s' % (x) for x in sorted(missing)) return 0
[ "def", "CheckForUnusedGrdIDsInSources", "(", "grd_files", ",", "src_dirs", ")", ":", "# Collect all the ids into a large map", "all_ids", "=", "set", "(", ")", "file_id_map", "=", "{", "}", "for", "y", "in", "grd_files", ":", "handler", "=", "GrdIDExtractor", "(",...
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/check_grd_for_unused_strings.py#L38-L110
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/python/ops/control_flow_ops.py
python
WhileContext.from_proto
(context_def, import_scope=None)
return WhileContext(context_def=context_def, import_scope=import_scope)
Returns a `WhileContext` object created from `context_def`. Args: context_def: A `WhileContextDef` protocol buffer. import_scope: Optional `string`. Name scope to add. Returns: A `WhileContext` Python object.
Returns a `WhileContext` object created from `context_def`.
[ "Returns", "a", "WhileContext", "object", "created", "from", "context_def", "." ]
def from_proto(context_def, import_scope=None): """Returns a `WhileContext` object created from `context_def`. Args: context_def: A `WhileContextDef` protocol buffer. import_scope: Optional `string`. Name scope to add. Returns: A `WhileContext` Python object. """ return WhileContext(context_def=context_def, import_scope=import_scope)
[ "def", "from_proto", "(", "context_def", ",", "import_scope", "=", "None", ")", ":", "return", "WhileContext", "(", "context_def", "=", "context_def", ",", "import_scope", "=", "import_scope", ")" ]
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/python/ops/control_flow_ops.py#L2068-L2079
jeog/TOSDataBridge
6a5a08ca5cf3883db1f12e9bc89ef374d098df5a
python/tosdb/_common.py
python
_TOSDB_DataBlock.n_from_marker
()
Return n data-points from an 'atomic' marker It's likely the stream will grow between consecutive calls. This call guarantees to pick up where the last get(), stream_snapshot(), stream_snapshot_from_marker(), or n_from_marker() call ended. Internally the stream maintains a 'marker' that tracks the position of the last value pulled; the act of retreiving 'n' data-points IN FRONT OF the marker(more recent) and moving the marker can be thought of as a single, 'atomic' operation. If the marker doesn't get reset(moved) before it hits the end of stream (block_size) the stream becomes 'dirty' and will raise TOSDB_DataError if throw_if_data_lost == True. As the oldest data is popped off the back of the stream it is lost(the marker can't grow past the end of the stream). * * * n_from_marker(self, item, topic, date_time=False, n=1, throw_if_data_lost=True, data_str_max=STR_DATA_SZ) item :: str :: any item string in the block topic :: str :: any topic string in the block date_time :: bool :: include TOSDB_DateTime objects n :: int :: number of data-points in front of marker throw_if_data_loss :: bool :: how to handle error states (see above) data_str_max :: int :: maximum length of string data returned if beg > internal marker position: returns -> None elif date_time == True: returns -> list of 2-tuple** else: returns -> list** **data are of type int, float, or str (depending on the topic) throws TOSDB_DataTimeError, TOSDB_IndexError, TOSDB_ValueError, TOSDB_DataError, TOSDB_CLibError, TOSDB_TypeError
Return n data-points from an 'atomic' marker
[ "Return", "n", "data", "-", "points", "from", "an", "atomic", "marker" ]
def n_from_marker(): """ Return n data-points from an 'atomic' marker It's likely the stream will grow between consecutive calls. This call guarantees to pick up where the last get(), stream_snapshot(), stream_snapshot_from_marker(), or n_from_marker() call ended. Internally the stream maintains a 'marker' that tracks the position of the last value pulled; the act of retreiving 'n' data-points IN FRONT OF the marker(more recent) and moving the marker can be thought of as a single, 'atomic' operation. If the marker doesn't get reset(moved) before it hits the end of stream (block_size) the stream becomes 'dirty' and will raise TOSDB_DataError if throw_if_data_lost == True. As the oldest data is popped off the back of the stream it is lost(the marker can't grow past the end of the stream). * * * n_from_marker(self, item, topic, date_time=False, n=1, throw_if_data_lost=True, data_str_max=STR_DATA_SZ) item :: str :: any item string in the block topic :: str :: any topic string in the block date_time :: bool :: include TOSDB_DateTime objects n :: int :: number of data-points in front of marker throw_if_data_loss :: bool :: how to handle error states (see above) data_str_max :: int :: maximum length of string data returned if beg > internal marker position: returns -> None elif date_time == True: returns -> list of 2-tuple** else: returns -> list** **data are of type int, float, or str (depending on the topic) throws TOSDB_DataTimeError, TOSDB_IndexError, TOSDB_ValueError, TOSDB_DataError, TOSDB_CLibError, TOSDB_TypeError """ pass
[ "def", "n_from_marker", "(", ")", ":", "pass" ]
https://github.com/jeog/TOSDataBridge/blob/6a5a08ca5cf3883db1f12e9bc89ef374d098df5a/python/tosdb/_common.py#L351-L389
FreeCAD/FreeCAD
ba42231b9c6889b89e064d6d563448ed81e376ec
src/Mod/Draft/draftviewproviders/view_dimension.py
python
ViewProviderDimensionBase.getIcon
(self)
return ":/icons/Draft_Dimension_Tree.svg"
Return the path to the icon used by the viewprovider.
Return the path to the icon used by the viewprovider.
[ "Return", "the", "path", "to", "the", "icon", "used", "by", "the", "viewprovider", "." ]
def getIcon(self): """Return the path to the icon used by the viewprovider.""" return ":/icons/Draft_Dimension_Tree.svg"
[ "def", "getIcon", "(", "self", ")", ":", "return", "\":/icons/Draft_Dimension_Tree.svg\"" ]
https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Draft/draftviewproviders/view_dimension.py#L321-L323
natanielruiz/android-yolo
1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f
jni-build/jni/include/tensorflow/python/ops/array_ops.py
python
rank
(input, name=None)
Returns the rank of a tensor. This operation returns an integer representing the rank of `input`. For example: ```python # 't' is [[[1, 1, 1], [2, 2, 2]], [[3, 3, 3], [4, 4, 4]]] # shape of tensor 't' is [2, 2, 3] rank(t) ==> 3 ``` **Note**: The rank of a tensor is not the same as the rank of a matrix. The rank of a tensor is the number of indices required to uniquely select each element of the tensor. Rank is also known as "order", "degree", or "ndims." Args: input: A `Tensor` or `SparseTensor`. name: A name for the operation (optional). Returns: A `Tensor` of type `int32`.
Returns the rank of a tensor.
[ "Returns", "the", "rank", "of", "a", "tensor", "." ]
def rank(input, name=None): """Returns the rank of a tensor. This operation returns an integer representing the rank of `input`. For example: ```python # 't' is [[[1, 1, 1], [2, 2, 2]], [[3, 3, 3], [4, 4, 4]]] # shape of tensor 't' is [2, 2, 3] rank(t) ==> 3 ``` **Note**: The rank of a tensor is not the same as the rank of a matrix. The rank of a tensor is the number of indices required to uniquely select each element of the tensor. Rank is also known as "order", "degree", or "ndims." Args: input: A `Tensor` or `SparseTensor`. name: A name for the operation (optional). Returns: A `Tensor` of type `int32`. """ with ops.op_scope([input], name, "Rank") as name: if isinstance(input, ops.SparseTensor): return gen_array_ops.size(input.shape, name=name) else: return gen_array_ops.rank(input, name=name)
[ "def", "rank", "(", "input", ",", "name", "=", "None", ")", ":", "with", "ops", ".", "op_scope", "(", "[", "input", "]", ",", "name", ",", "\"Rank\"", ")", "as", "name", ":", "if", "isinstance", "(", "input", ",", "ops", ".", "SparseTensor", ")", ...
https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/python/ops/array_ops.py#L162-L190
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/nntplib.py
python
_NNTPBase.description
(self, group)
return self._getdescriptions(group, False)
Get a description for a single group. If more than one group matches ('group' is a pattern), return the first. If no group matches, return an empty string. This elides the response code from the server, since it can only be '215' or '285' (for xgtitle) anyway. If the response code is needed, use the 'descriptions' method. NOTE: This neither checks for a wildcard in 'group' nor does it check whether the group actually exists.
Get a description for a single group. If more than one group matches ('group' is a pattern), return the first. If no group matches, return an empty string.
[ "Get", "a", "description", "for", "a", "single", "group", ".", "If", "more", "than", "one", "group", "matches", "(", "group", "is", "a", "pattern", ")", "return", "the", "first", ".", "If", "no", "group", "matches", "return", "an", "empty", "string", "...
def description(self, group): """Get a description for a single group. If more than one group matches ('group' is a pattern), return the first. If no group matches, return an empty string. This elides the response code from the server, since it can only be '215' or '285' (for xgtitle) anyway. If the response code is needed, use the 'descriptions' method. NOTE: This neither checks for a wildcard in 'group' nor does it check whether the group actually exists.""" return self._getdescriptions(group, False)
[ "def", "description", "(", "self", ",", "group", ")", ":", "return", "self", ".", "_getdescriptions", "(", "group", ",", "False", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/nntplib.py#L634-L645
psnonis/FinBERT
c0c555d833a14e2316a3701e59c0b5156f804b4e
bert-gpu/tensorrt-inference-server/src/clients/python/ensemble_image_client.py
python
postprocess
(results, filenames, batch_size)
Post-process results to show classifications.
Post-process results to show classifications.
[ "Post", "-", "process", "results", "to", "show", "classifications", "." ]
def postprocess(results, filenames, batch_size): """ Post-process results to show classifications. """ if len(results) != 1: raise Exception("expected 1 result, got {}".format(len(results))) batched_result = list(results.values())[0] if len(batched_result) != batch_size: raise Exception("expected {} results, got {}".format(batch_size, len(batched_result))) if len(filenames) != batch_size: raise Exception("expected {} filenames, got {}".format(batch_size, len(filenames))) for (index, result) in enumerate(batched_result): print("Image '{}':".format(filenames[index])) for cls in result: print(" {} ({}) = {}".format(cls[0], cls[2], cls[1]))
[ "def", "postprocess", "(", "results", ",", "filenames", ",", "batch_size", ")", ":", "if", "len", "(", "results", ")", "!=", "1", ":", "raise", "Exception", "(", "\"expected 1 result, got {}\"", ".", "format", "(", "len", "(", "results", ")", ")", ")", "...
https://github.com/psnonis/FinBERT/blob/c0c555d833a14e2316a3701e59c0b5156f804b4e/bert-gpu/tensorrt-inference-server/src/clients/python/ensemble_image_client.py#L64-L80
microsoft/TSS.MSR
0f2516fca2cd9929c31d5450e39301c9bde43688
TSS.Py/src/TpmTypes.py
python
TPMS_CAPABILITY_DATA.fromTpm
(buf)
return buf.createObj(TPMS_CAPABILITY_DATA)
Returns new TPMS_CAPABILITY_DATA object constructed from its marshaled representation in the given TpmBuffer buffer
Returns new TPMS_CAPABILITY_DATA object constructed from its marshaled representation in the given TpmBuffer buffer
[ "Returns", "new", "TPMS_CAPABILITY_DATA", "object", "constructed", "from", "its", "marshaled", "representation", "in", "the", "given", "TpmBuffer", "buffer" ]
def fromTpm(buf): """ Returns new TPMS_CAPABILITY_DATA object constructed from its marshaled representation in the given TpmBuffer buffer """ return buf.createObj(TPMS_CAPABILITY_DATA)
[ "def", "fromTpm", "(", "buf", ")", ":", "return", "buf", ".", "createObj", "(", "TPMS_CAPABILITY_DATA", ")" ]
https://github.com/microsoft/TSS.MSR/blob/0f2516fca2cd9929c31d5450e39301c9bde43688/TSS.Py/src/TpmTypes.py#L4955-L4959
snap-stanford/snap-python
d53c51b0a26aa7e3e7400b014cdf728948fde80a
setup/snap.py
python
TInt.__init__
(self, *args)
__init__(TInt self) -> TInt __init__(TInt self, int const & _Val) -> TInt Parameters: _Val: int const & __init__(TInt self, TSIn SIn) -> TInt Parameters: SIn: TSIn &
__init__(TInt self) -> TInt __init__(TInt self, int const & _Val) -> TInt
[ "__init__", "(", "TInt", "self", ")", "-", ">", "TInt", "__init__", "(", "TInt", "self", "int", "const", "&", "_Val", ")", "-", ">", "TInt" ]
def __init__(self, *args): """ __init__(TInt self) -> TInt __init__(TInt self, int const & _Val) -> TInt Parameters: _Val: int const & __init__(TInt self, TSIn SIn) -> TInt Parameters: SIn: TSIn & """ _snap.TInt_swiginit(self,_snap.new_TInt(*args))
[ "def", "__init__", "(", "self", ",", "*", "args", ")", ":", "_snap", ".", "TInt_swiginit", "(", "self", ",", "_snap", ".", "new_TInt", "(", "*", "args", ")", ")" ]
https://github.com/snap-stanford/snap-python/blob/d53c51b0a26aa7e3e7400b014cdf728948fde80a/setup/snap.py#L12929-L12943
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/code.py
python
InteractiveInterpreter.showsyntaxerror
(self, filename=None)
Display the syntax error that just occurred. This doesn't display a stack trace because there isn't one. If a filename is given, it is stuffed in the exception instead of what was there before (because Python's parser always uses "<string>" when reading from a string). The output is written by self.write(), below.
Display the syntax error that just occurred.
[ "Display", "the", "syntax", "error", "that", "just", "occurred", "." ]
def showsyntaxerror(self, filename=None): """Display the syntax error that just occurred. This doesn't display a stack trace because there isn't one. If a filename is given, it is stuffed in the exception instead of what was there before (because Python's parser always uses "<string>" when reading from a string). The output is written by self.write(), below. """ type, value, tb = sys.exc_info() sys.last_type = type sys.last_value = value sys.last_traceback = tb if filename and type is SyntaxError: # Work hard to stuff the correct filename in the exception try: msg, (dummy_filename, lineno, offset, line) = value.args except ValueError: # Not the format we expect; leave it alone pass else: # Stuff in the right filename value = SyntaxError(msg, (filename, lineno, offset, line)) sys.last_value = value if sys.excepthook is sys.__excepthook__: lines = traceback.format_exception_only(type, value) self.write(''.join(lines)) else: # If someone has set sys.excepthook, we let that take precedence # over self.write sys.excepthook(type, value, tb)
[ "def", "showsyntaxerror", "(", "self", ",", "filename", "=", "None", ")", ":", "type", ",", "value", ",", "tb", "=", "sys", ".", "exc_info", "(", ")", "sys", ".", "last_type", "=", "type", "sys", ".", "last_value", "=", "value", "sys", ".", "last_tra...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/code.py#L96-L129
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/distribute/coordinator/cluster_coordinator.py
python
Cluster.done
(self)
return self.closure_queue.done()
Returns true if all scheduled functions are executed.
Returns true if all scheduled functions are executed.
[ "Returns", "true", "if", "all", "scheduled", "functions", "are", "executed", "." ]
def done(self): """Returns true if all scheduled functions are executed.""" return self.closure_queue.done()
[ "def", "done", "(", "self", ")", ":", "return", "self", ".", "closure_queue", ".", "done", "(", ")" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/distribute/coordinator/cluster_coordinator.py#L917-L919
dicecco1/fpga_caffe
7a191704efd7873071cfef35772d7e7bf3e3cfd6
scripts/cpp_lint.py
python
ProcessFileData
(filename, file_extension, lines, error, extra_check_functions=[])
Performs lint checks and reports any errors to the given error function. Args: filename: Filename of the file that is being processed. file_extension: The extension (dot not included) of the file. lines: An array of strings, each representing a line of the file, with the last element being empty if the file is terminated with a newline. error: A callable to which errors are reported, which takes 4 arguments: filename, line number, error level, and message extra_check_functions: An array of additional check functions that will be run on each source line. Each function takes 4 arguments: filename, clean_lines, line, error
Performs lint checks and reports any errors to the given error function.
[ "Performs", "lint", "checks", "and", "reports", "any", "errors", "to", "the", "given", "error", "function", "." ]
def ProcessFileData(filename, file_extension, lines, error, extra_check_functions=[]): """Performs lint checks and reports any errors to the given error function. Args: filename: Filename of the file that is being processed. file_extension: The extension (dot not included) of the file. lines: An array of strings, each representing a line of the file, with the last element being empty if the file is terminated with a newline. error: A callable to which errors are reported, which takes 4 arguments: filename, line number, error level, and message extra_check_functions: An array of additional check functions that will be run on each source line. Each function takes 4 arguments: filename, clean_lines, line, error """ lines = (['// marker so line numbers and indices both start at 1'] + lines + ['// marker so line numbers end in a known way']) include_state = _IncludeState() function_state = _FunctionState() nesting_state = _NestingState() ResetNolintSuppressions() CheckForCopyright(filename, lines, error) if file_extension == 'h': CheckForHeaderGuard(filename, lines, error) RemoveMultiLineComments(filename, lines, error) clean_lines = CleansedLines(lines) for line in xrange(clean_lines.NumLines()): ProcessLine(filename, file_extension, clean_lines, line, include_state, function_state, nesting_state, error, extra_check_functions) nesting_state.CheckCompletedBlocks(filename, error) CheckForIncludeWhatYouUse(filename, clean_lines, include_state, error) # We check here rather than inside ProcessLine so that we see raw # lines rather than "cleaned" lines. CheckForBadCharacters(filename, lines, error) CheckForNewlineAtEOF(filename, lines, error)
[ "def", "ProcessFileData", "(", "filename", ",", "file_extension", ",", "lines", ",", "error", ",", "extra_check_functions", "=", "[", "]", ")", ":", "lines", "=", "(", "[", "'// marker so line numbers and indices both start at 1'", "]", "+", "lines", "+", "[", "...
https://github.com/dicecco1/fpga_caffe/blob/7a191704efd7873071cfef35772d7e7bf3e3cfd6/scripts/cpp_lint.py#L4648-L4691
natanielruiz/android-yolo
1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f
jni-build/jni/include/tensorflow/python/client/timeline.py
python
_TensorTracker.add_ref
(self, timestamp)
Adds a reference to this tensor with the specified timestamp. Args: timestamp: Timestamp of object reference as an integer.
Adds a reference to this tensor with the specified timestamp.
[ "Adds", "a", "reference", "to", "this", "tensor", "with", "the", "specified", "timestamp", "." ]
def add_ref(self, timestamp): """Adds a reference to this tensor with the specified timestamp. Args: timestamp: Timestamp of object reference as an integer. """ self._ref_times.append(timestamp)
[ "def", "add_ref", "(", "self", ",", "timestamp", ")", ":", "self", ".", "_ref_times", ".", "append", "(", "timestamp", ")" ]
https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/python/client/timeline.py#L330-L336
h2oai/datatable
753197c3f76041dd6468e0f6a9708af92d80f6aa
src/datatable/xls.py
python
_collapse_ranges
(ranges, ja)
return ja
Within the `ranges` list find those 2d-ranges that overlap with `ranges[ja]` and merge them into `ranges[ja]`. Finally, return the new index of the ja-th range within the `ranges` list.
Within the `ranges` list find those 2d-ranges that overlap with `ranges[ja]` and merge them into `ranges[ja]`. Finally, return the new index of the ja-th range within the `ranges` list.
[ "Within", "the", "ranges", "list", "find", "those", "2d", "-", "ranges", "that", "overlap", "with", "ranges", "[", "ja", "]", "and", "merge", "them", "into", "ranges", "[", "ja", "]", ".", "Finally", "return", "the", "new", "index", "of", "the", "ja", ...
def _collapse_ranges(ranges, ja): """ Within the `ranges` list find those 2d-ranges that overlap with `ranges[ja]` and merge them into `ranges[ja]`. Finally, return the new index of the ja-th range within the `ranges` list. """ arow0, _, acol0, acol1 = ranges[ja] jb = 0 while jb < len(ranges): if jb == ja: jb += 1 continue brow0, brow1, bcol0, bcol1 = ranges[jb] if bcol0 <= acol1 and brow1 >= arow0 and \ not(bcol0 == acol1 and brow1 == arow0): ranges[ja][0] = arow0 = min(arow0, brow0) ranges[ja][3] = acol1 = max(acol1, bcol1) del ranges[jb] if jb < ja: ja -= 1 else: jb += 1 return ja
[ "def", "_collapse_ranges", "(", "ranges", ",", "ja", ")", ":", "arow0", ",", "_", ",", "acol0", ",", "acol1", "=", "ranges", "[", "ja", "]", "jb", "=", "0", "while", "jb", "<", "len", "(", "ranges", ")", ":", "if", "jb", "==", "ja", ":", "jb", ...
https://github.com/h2oai/datatable/blob/753197c3f76041dd6468e0f6a9708af92d80f6aa/src/datatable/xls.py#L234-L256
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/AWSPythonSDK/1.5.8/botocore/vendored/requests/utils.py
python
get_netrc_auth
(url)
Returns the Requests tuple auth for a given url from netrc.
Returns the Requests tuple auth for a given url from netrc.
[ "Returns", "the", "Requests", "tuple", "auth", "for", "a", "given", "url", "from", "netrc", "." ]
def get_netrc_auth(url): """Returns the Requests tuple auth for a given url from netrc.""" try: from netrc import netrc, NetrcParseError netrc_path = None for f in NETRC_FILES: try: loc = os.path.expanduser('~/{0}'.format(f)) except KeyError: # os.path.expanduser can fail when $HOME is undefined and # getpwuid fails. See http://bugs.python.org/issue20164 & # https://github.com/kennethreitz/requests/issues/1846 return if os.path.exists(loc): netrc_path = loc break # Abort early if there isn't one. if netrc_path is None: return ri = urlparse(url) # Strip port numbers from netloc host = ri.netloc.split(':')[0] try: _netrc = netrc(netrc_path).authenticators(host) if _netrc: # Return with login / password login_i = (0 if _netrc[0] else 1) return (_netrc[login_i], _netrc[2]) except (NetrcParseError, IOError): # If there was a parsing error or a permissions issue reading the file, # we'll just skip netrc auth pass # AppEngine hackiness. except (ImportError, AttributeError): pass
[ "def", "get_netrc_auth", "(", "url", ")", ":", "try", ":", "from", "netrc", "import", "netrc", ",", "NetrcParseError", "netrc_path", "=", "None", "for", "f", "in", "NETRC_FILES", ":", "try", ":", "loc", "=", "os", ".", "path", ".", "expanduser", "(", "...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/AWSPythonSDK/1.5.8/botocore/vendored/requests/utils.py#L70-L113
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/Pygments/py3/pygments/lexer.py
python
Lexer.get_tokens
(self, text, unfiltered=False)
return stream
Return an iterable of (tokentype, value) pairs generated from `text`. If `unfiltered` is set to `True`, the filtering mechanism is bypassed even if filters are defined. Also preprocess the text, i.e. expand tabs and strip it if wanted and applies registered filters.
Return an iterable of (tokentype, value) pairs generated from `text`. If `unfiltered` is set to `True`, the filtering mechanism is bypassed even if filters are defined.
[ "Return", "an", "iterable", "of", "(", "tokentype", "value", ")", "pairs", "generated", "from", "text", ".", "If", "unfiltered", "is", "set", "to", "True", "the", "filtering", "mechanism", "is", "bypassed", "even", "if", "filters", "are", "defined", "." ]
def get_tokens(self, text, unfiltered=False): """ Return an iterable of (tokentype, value) pairs generated from `text`. If `unfiltered` is set to `True`, the filtering mechanism is bypassed even if filters are defined. Also preprocess the text, i.e. expand tabs and strip it if wanted and applies registered filters. """ if not isinstance(text, str): if self.encoding == 'guess': text, _ = guess_decode(text) elif self.encoding == 'chardet': try: import chardet except ImportError as e: raise ImportError('To enable chardet encoding guessing, ' 'please install the chardet library ' 'from http://chardet.feedparser.org/') from e # check for BOM first decoded = None for bom, encoding in _encoding_map: if text.startswith(bom): decoded = text[len(bom):].decode(encoding, 'replace') break # no BOM found, so use chardet if decoded is None: enc = chardet.detect(text[:1024]) # Guess using first 1KB decoded = text.decode(enc.get('encoding') or 'utf-8', 'replace') text = decoded else: text = text.decode(self.encoding) if text.startswith('\ufeff'): text = text[len('\ufeff'):] else: if text.startswith('\ufeff'): text = text[len('\ufeff'):] # text now *is* a unicode string text = text.replace('\r\n', '\n') text = text.replace('\r', '\n') if self.stripall: text = text.strip() elif self.stripnl: text = text.strip('\n') if self.tabsize > 0: text = text.expandtabs(self.tabsize) if self.ensurenl and not text.endswith('\n'): text += '\n' def streamer(): for _, t, v in self.get_tokens_unprocessed(text): yield t, v stream = streamer() if not unfiltered: stream = apply_filters(stream, self.filters, self) return stream
[ "def", "get_tokens", "(", "self", ",", "text", ",", "unfiltered", "=", "False", ")", ":", "if", "not", "isinstance", "(", "text", ",", "str", ")", ":", "if", "self", ".", "encoding", "==", "'guess'", ":", "text", ",", "_", "=", "guess_decode", "(", ...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/Pygments/py3/pygments/lexer.py#L135-L192
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
tools/json_to_struct/struct_generator.py
python
GenerateStruct
(type_name, schema)
return '\n'.join(lines) + '\n'
Generate a string defining a structure containing the fields specified in the schema list.
Generate a string defining a structure containing the fields specified in the schema list.
[ "Generate", "a", "string", "defining", "a", "structure", "containing", "the", "fields", "specified", "in", "the", "schema", "list", "." ]
def GenerateStruct(type_name, schema): """Generate a string defining a structure containing the fields specified in the schema list. """ lines = []; lines.append('struct %s {' % type_name) for field_info in schema: if field_info['type'] == 'struct': lines.insert(0, GenerateStruct(field_info['type_name'], field_info['fields'])) elif (field_info['type'] == 'array' and field_info['contents']['type'] == 'struct'): contents = field_info['contents'] lines.insert(0, GenerateStruct(contents['type_name'], contents['fields'])) lines.append(' ' + GenerateField(field_info) + ';') lines.append('};'); return '\n'.join(lines) + '\n';
[ "def", "GenerateStruct", "(", "type_name", ",", "schema", ")", ":", "lines", "=", "[", "]", "lines", ".", "append", "(", "'struct %s {'", "%", "type_name", ")", "for", "field_info", "in", "schema", ":", "if", "field_info", "[", "'type'", "]", "==", "'str...
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/json_to_struct/struct_generator.py#L36-L53
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/propgrid.py
python
PropertyGridInterface_SetBoolChoices
(*args, **kwargs)
return _propgrid.PropertyGridInterface_SetBoolChoices(*args, **kwargs)
PropertyGridInterface_SetBoolChoices(String trueChoice, String falseChoice)
PropertyGridInterface_SetBoolChoices(String trueChoice, String falseChoice)
[ "PropertyGridInterface_SetBoolChoices", "(", "String", "trueChoice", "String", "falseChoice", ")" ]
def PropertyGridInterface_SetBoolChoices(*args, **kwargs): """PropertyGridInterface_SetBoolChoices(String trueChoice, String falseChoice)""" return _propgrid.PropertyGridInterface_SetBoolChoices(*args, **kwargs)
[ "def", "PropertyGridInterface_SetBoolChoices", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_propgrid", ".", "PropertyGridInterface_SetBoolChoices", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/propgrid.py#L1811-L1813
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/numpy/py3/numpy/polynomial/laguerre.py
python
lagcompanion
(c)
return mat
Return the companion matrix of c. The usual companion matrix of the Laguerre polynomials is already symmetric when `c` is a basis Laguerre polynomial, so no scaling is applied. Parameters ---------- c : array_like 1-D array of Laguerre series coefficients ordered from low to high degree. Returns ------- mat : ndarray Companion matrix of dimensions (deg, deg). Notes ----- .. versionadded:: 1.7.0
Return the companion matrix of c.
[ "Return", "the", "companion", "matrix", "of", "c", "." ]
def lagcompanion(c): """ Return the companion matrix of c. The usual companion matrix of the Laguerre polynomials is already symmetric when `c` is a basis Laguerre polynomial, so no scaling is applied. Parameters ---------- c : array_like 1-D array of Laguerre series coefficients ordered from low to high degree. Returns ------- mat : ndarray Companion matrix of dimensions (deg, deg). Notes ----- .. versionadded:: 1.7.0 """ # c is a trimmed copy [c] = pu.as_series([c]) if len(c) < 2: raise ValueError('Series must have maximum degree of at least 1.') if len(c) == 2: return np.array([[1 + c[0]/c[1]]]) n = len(c) - 1 mat = np.zeros((n, n), dtype=c.dtype) top = mat.reshape(-1)[1::n+1] mid = mat.reshape(-1)[0::n+1] bot = mat.reshape(-1)[n::n+1] top[...] = -np.arange(1, n) mid[...] = 2.*np.arange(n) + 1. bot[...] = top mat[:, -1] += (c[:-1]/c[-1])*n return mat
[ "def", "lagcompanion", "(", "c", ")", ":", "# c is a trimmed copy", "[", "c", "]", "=", "pu", ".", "as_series", "(", "[", "c", "]", ")", "if", "len", "(", "c", ")", "<", "2", ":", "raise", "ValueError", "(", "'Series must have maximum degree of at least 1....
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py3/numpy/polynomial/laguerre.py#L1403-L1444
wyrover/book-code
7f4883d9030d553bc6bcfa3da685e34789839900
3rdparty/protobuf/python/google/protobuf/internal/well_known_types.py
python
_IsValidPath
(message_descriptor, path)
return last in message_descriptor.fields_by_name
Checks whether the path is valid for Message Descriptor.
Checks whether the path is valid for Message Descriptor.
[ "Checks", "whether", "the", "path", "is", "valid", "for", "Message", "Descriptor", "." ]
def _IsValidPath(message_descriptor, path): """Checks whether the path is valid for Message Descriptor.""" parts = path.split('.') last = parts.pop() for name in parts: field = message_descriptor.fields_by_name[name] if (field is None or field.label == FieldDescriptor.LABEL_REPEATED or field.type != FieldDescriptor.TYPE_MESSAGE): return False message_descriptor = field.message_type return last in message_descriptor.fields_by_name
[ "def", "_IsValidPath", "(", "message_descriptor", ",", "path", ")", ":", "parts", "=", "path", ".", "split", "(", "'.'", ")", "last", "=", "parts", ".", "pop", "(", ")", "for", "name", "in", "parts", ":", "field", "=", "message_descriptor", ".", "field...
https://github.com/wyrover/book-code/blob/7f4883d9030d553bc6bcfa3da685e34789839900/3rdparty/protobuf/python/google/protobuf/internal/well_known_types.py#L452-L463
miyosuda/TensorFlowAndroidDemo
35903e0221aa5f109ea2dbef27f20b52e317f42d
jni-build/jni/include/tensorflow/python/ops/variables.py
python
Variable.assign_sub
(self, delta, use_locking=False)
return state_ops.assign_sub(self._variable, delta, use_locking=use_locking)
Subtracts a value from this variable. This is essentially a shortcut for `assign_sub(self, delta)`. Args: delta: A `Tensor`. The value to subtract from this variable. use_locking: If `True`, use locking during the operation. Returns: A `Tensor` that will hold the new value of this variable after the subtraction has completed.
Subtracts a value from this variable.
[ "Subtracts", "a", "value", "from", "this", "variable", "." ]
def assign_sub(self, delta, use_locking=False): """Subtracts a value from this variable. This is essentially a shortcut for `assign_sub(self, delta)`. Args: delta: A `Tensor`. The value to subtract from this variable. use_locking: If `True`, use locking during the operation. Returns: A `Tensor` that will hold the new value of this variable after the subtraction has completed. """ return state_ops.assign_sub(self._variable, delta, use_locking=use_locking)
[ "def", "assign_sub", "(", "self", ",", "delta", ",", "use_locking", "=", "False", ")", ":", "return", "state_ops", ".", "assign_sub", "(", "self", ".", "_variable", ",", "delta", ",", "use_locking", "=", "use_locking", ")" ]
https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/python/ops/variables.py#L518-L531
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/_controls.py
python
ListItemAttr.SetBackgroundColour
(*args, **kwargs)
return _controls_.ListItemAttr_SetBackgroundColour(*args, **kwargs)
SetBackgroundColour(self, Colour colBack)
SetBackgroundColour(self, Colour colBack)
[ "SetBackgroundColour", "(", "self", "Colour", "colBack", ")" ]
def SetBackgroundColour(*args, **kwargs): """SetBackgroundColour(self, Colour colBack)""" return _controls_.ListItemAttr_SetBackgroundColour(*args, **kwargs)
[ "def", "SetBackgroundColour", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_controls_", ".", "ListItemAttr_SetBackgroundColour", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_controls.py#L4094-L4096
gem5/gem5
141cc37c2d4b93959d4c249b8f7e6a8b2ef75338
ext/ply/example/BASIC/basparse.py
python
p_command_end
(p)
command : END
command : END
[ "command", ":", "END" ]
def p_command_end(p): '''command : END''' p[0] = ('END',)
[ "def", "p_command_end", "(", "p", ")", ":", "p", "[", "0", "]", "=", "(", "'END'", ",", ")" ]
https://github.com/gem5/gem5/blob/141cc37c2d4b93959d4c249b8f7e6a8b2ef75338/ext/ply/example/BASIC/basparse.py#L203-L205
apache/singa
93fd9da72694e68bfe3fb29d0183a65263d238a1
python/singa/autograd.py
python
greater
(x, y)
return Greater()(x, y)[0]
Return a>b, where a and b are Tensor.
Return a>b, where a and b are Tensor.
[ "Return", "a", ">", "b", "where", "a", "and", "b", "are", "Tensor", "." ]
def greater(x, y): """ Return a>b, where a and b are Tensor. """ return Greater()(x, y)[0]
[ "def", "greater", "(", "x", ",", "y", ")", ":", "return", "Greater", "(", ")", "(", "x", ",", "y", ")", "[", "0", "]" ]
https://github.com/apache/singa/blob/93fd9da72694e68bfe3fb29d0183a65263d238a1/python/singa/autograd.py#L661-L665
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemFramework/v1/ResourceManager/lib/Crypto/PublicKey/DSA.py
python
construct
(tup, consistency_check=True)
return key
Construct a DSA key from a tuple of valid DSA components. Args: tup (tuple): A tuple of long integers, with 4 or 5 items in the following order: 1. Public key (*y*). 2. Sub-group generator (*g*). 3. Modulus, finite field order (*p*). 4. Sub-group order (*q*). 5. Private key (*x*). Optional. consistency_check (boolean): If ``True``, the library will verify that the provided components fulfil the main DSA properties. Raises: ValueError: when the key being imported fails the most basic DSA validity checks. Returns: :class:`DsaKey` : a DSA key object
Construct a DSA key from a tuple of valid DSA components.
[ "Construct", "a", "DSA", "key", "from", "a", "tuple", "of", "valid", "DSA", "components", "." ]
def construct(tup, consistency_check=True): """Construct a DSA key from a tuple of valid DSA components. Args: tup (tuple): A tuple of long integers, with 4 or 5 items in the following order: 1. Public key (*y*). 2. Sub-group generator (*g*). 3. Modulus, finite field order (*p*). 4. Sub-group order (*q*). 5. Private key (*x*). Optional. consistency_check (boolean): If ``True``, the library will verify that the provided components fulfil the main DSA properties. Raises: ValueError: when the key being imported fails the most basic DSA validity checks. Returns: :class:`DsaKey` : a DSA key object """ key_dict = dict(zip(('y', 'g', 'p', 'q', 'x'), map(Integer, tup))) key = DsaKey(key_dict) fmt_error = False if consistency_check: # P and Q must be prime fmt_error = test_probable_prime(key.p) == COMPOSITE fmt_error = test_probable_prime(key.q) == COMPOSITE # Verify Lagrange's theorem for sub-group fmt_error |= ((key.p - 1) % key.q) != 0 fmt_error |= key.g <= 1 or key.g >= key.p fmt_error |= pow(key.g, key.q, key.p) != 1 # Public key fmt_error |= key.y <= 0 or key.y >= key.p if hasattr(key, 'x'): fmt_error |= key.x <= 0 or key.x >= key.q fmt_error |= pow(key.g, key.x, key.p) != key.y if fmt_error: raise ValueError("Invalid DSA key components") return key
[ "def", "construct", "(", "tup", ",", "consistency_check", "=", "True", ")", ":", "key_dict", "=", "dict", "(", "zip", "(", "(", "'y'", ",", "'g'", ",", "'p'", ",", "'q'", ",", "'x'", ")", ",", "map", "(", "Integer", ",", "tup", ")", ")", ")", "...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/ResourceManager/lib/Crypto/PublicKey/DSA.py#L486-L532
hpi-xnor/BMXNet-v2
af2b1859eafc5c721b1397cef02f946aaf2ce20d
python/mxnet/context.py
python
current_context
()
return Context._default_ctx.value
Returns the current context. By default, `mx.cpu()` is used for all the computations and it can be overridden by using `with mx.Context(x)` statement where x can be cpu(device_id) or gpu(device_id). Examples ------- >>> mx.current_context() cpu(0) >>> with mx.Context('gpu', 1): # Context changed in `with` block. ... mx.current_context() # Computation done here will be on gpu(1). ... gpu(1) >>> mx.current_context() # Back to default context. cpu(0) Returns ------- default_ctx : Context
Returns the current context.
[ "Returns", "the", "current", "context", "." ]
def current_context(): """Returns the current context. By default, `mx.cpu()` is used for all the computations and it can be overridden by using `with mx.Context(x)` statement where x can be cpu(device_id) or gpu(device_id). Examples ------- >>> mx.current_context() cpu(0) >>> with mx.Context('gpu', 1): # Context changed in `with` block. ... mx.current_context() # Computation done here will be on gpu(1). ... gpu(1) >>> mx.current_context() # Back to default context. cpu(0) Returns ------- default_ctx : Context """ if not hasattr(Context._default_ctx, "value"): Context._default_ctx.value = Context('cpu', 0) return Context._default_ctx.value
[ "def", "current_context", "(", ")", ":", "if", "not", "hasattr", "(", "Context", ".", "_default_ctx", ",", "\"value\"", ")", ":", "Context", ".", "_default_ctx", ".", "value", "=", "Context", "(", "'cpu'", ",", "0", ")", "return", "Context", ".", "_defau...
https://github.com/hpi-xnor/BMXNet-v2/blob/af2b1859eafc5c721b1397cef02f946aaf2ce20d/python/mxnet/context.py#L303-L327
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py2/pandas/core/generic.py
python
NDFrame._take
(self, indices, axis=0, is_copy=True)
return result
Return the elements in the given *positional* indices along an axis. This means that we are not indexing according to actual values in the index attribute of the object. We are indexing according to the actual position of the element in the object. This is the internal version of ``.take()`` and will contain a wider selection of parameters useful for internal use but not as suitable for public usage. Parameters ---------- indices : array-like An array of ints indicating which positions to take. axis : int, default 0 The axis on which to select elements. "0" means that we are selecting rows, "1" means that we are selecting columns, etc. is_copy : bool, default True Whether to return a copy of the original object or not. Returns ------- taken : same type as caller An array-like containing the elements taken from the object. See Also -------- numpy.ndarray.take numpy.take
Return the elements in the given *positional* indices along an axis.
[ "Return", "the", "elements", "in", "the", "given", "*", "positional", "*", "indices", "along", "an", "axis", "." ]
def _take(self, indices, axis=0, is_copy=True): """ Return the elements in the given *positional* indices along an axis. This means that we are not indexing according to actual values in the index attribute of the object. We are indexing according to the actual position of the element in the object. This is the internal version of ``.take()`` and will contain a wider selection of parameters useful for internal use but not as suitable for public usage. Parameters ---------- indices : array-like An array of ints indicating which positions to take. axis : int, default 0 The axis on which to select elements. "0" means that we are selecting rows, "1" means that we are selecting columns, etc. is_copy : bool, default True Whether to return a copy of the original object or not. Returns ------- taken : same type as caller An array-like containing the elements taken from the object. See Also -------- numpy.ndarray.take numpy.take """ self._consolidate_inplace() new_data = self._data.take(indices, axis=self._get_block_manager_axis(axis), verify=True) result = self._constructor(new_data).__finalize__(self) # Maybe set copy if we didn't actually change the index. if is_copy: if not result._get_axis(axis).equals(self._get_axis(axis)): result._set_is_copy(self) return result
[ "def", "_take", "(", "self", ",", "indices", ",", "axis", "=", "0", ",", "is_copy", "=", "True", ")", ":", "self", ".", "_consolidate_inplace", "(", ")", "new_data", "=", "self", ".", "_data", ".", "take", "(", "indices", ",", "axis", "=", "self", ...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py2/pandas/core/generic.py#L3323-L3367
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_core.py
python
WithImages.SetImageList
(*args, **kwargs)
return _core_.WithImages_SetImageList(*args, **kwargs)
SetImageList(self, ImageList imageList)
SetImageList(self, ImageList imageList)
[ "SetImageList", "(", "self", "ImageList", "imageList", ")" ]
def SetImageList(*args, **kwargs): """SetImageList(self, ImageList imageList)""" return _core_.WithImages_SetImageList(*args, **kwargs)
[ "def", "SetImageList", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "WithImages_SetImageList", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_core.py#L13502-L13504
cms-sw/cmssw
fd9de012d503d3405420bcbeec0ec879baa57cf2
Validation/RecoTrack/python/plotting/plotting.py
python
CutEfficiency.__init__
(self, name, histo, title="")
Constructor Arguments: name -- String for name of the resulting histogram histo -- String for a source histogram (needs to be cumulative)
Constructor
[ "Constructor" ]
def __init__(self, name, histo, title=""): """Constructor Arguments: name -- String for name of the resulting histogram histo -- String for a source histogram (needs to be cumulative) """ self._name = name self._histo = histo self._title = title
[ "def", "__init__", "(", "self", ",", "name", ",", "histo", ",", "title", "=", "\"\"", ")", ":", "self", ".", "_name", "=", "name", "self", ".", "_histo", "=", "histo", "self", ".", "_title", "=", "title" ]
https://github.com/cms-sw/cmssw/blob/fd9de012d503d3405420bcbeec0ec879baa57cf2/Validation/RecoTrack/python/plotting/plotting.py#L905-L914
google/llvm-propeller
45c226984fe8377ebfb2ad7713c680d652ba678d
lldb/third_party/Python/module/pexpect-4.6/pexpect/FSM.py
python
FSM.add_transition_list
(self, list_input_symbols, state, action=None, next_state=None)
This adds the same transition for a list of input symbols. You can pass a list or a string. Note that it is handy to use string.digits, string.whitespace, string.letters, etc. to add transitions that match character classes. The action may be set to None in which case the process() method will ignore the action and only set the next_state. The next_state may be set to None in which case the current state will be unchanged.
This adds the same transition for a list of input symbols. You can pass a list or a string. Note that it is handy to use string.digits, string.whitespace, string.letters, etc. to add transitions that match character classes.
[ "This", "adds", "the", "same", "transition", "for", "a", "list", "of", "input", "symbols", ".", "You", "can", "pass", "a", "list", "or", "a", "string", ".", "Note", "that", "it", "is", "handy", "to", "use", "string", ".", "digits", "string", ".", "wh...
def add_transition_list (self, list_input_symbols, state, action=None, next_state=None): '''This adds the same transition for a list of input symbols. You can pass a list or a string. Note that it is handy to use string.digits, string.whitespace, string.letters, etc. to add transitions that match character classes. The action may be set to None in which case the process() method will ignore the action and only set the next_state. The next_state may be set to None in which case the current state will be unchanged. ''' if next_state is None: next_state = state for input_symbol in list_input_symbols: self.add_transition (input_symbol, state, action, next_state)
[ "def", "add_transition_list", "(", "self", ",", "list_input_symbols", ",", "state", ",", "action", "=", "None", ",", "next_state", "=", "None", ")", ":", "if", "next_state", "is", "None", ":", "next_state", "=", "state", "for", "input_symbol", "in", "list_in...
https://github.com/google/llvm-propeller/blob/45c226984fe8377ebfb2ad7713c680d652ba678d/lldb/third_party/Python/module/pexpect-4.6/pexpect/FSM.py#L148-L162
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/nturl2path.py
python
pathname2url
(p)
return path
OS-specific conversion from a file system path to a relative URL of the 'file' scheme; not recommended for general use.
OS-specific conversion from a file system path to a relative URL of the 'file' scheme; not recommended for general use.
[ "OS", "-", "specific", "conversion", "from", "a", "file", "system", "path", "to", "a", "relative", "URL", "of", "the", "file", "scheme", ";", "not", "recommended", "for", "general", "use", "." ]
def pathname2url(p): """OS-specific conversion from a file system path to a relative URL of the 'file' scheme; not recommended for general use.""" # e.g. # C:\foo\bar\spam.foo # becomes # ///C:/foo/bar/spam.foo import urllib.parse if not ':' in p: # No drive specifier, just convert slashes and quote the name if p[:2] == '\\\\': # path is something like \\host\path\on\remote\host # convert this to ////host/path/on/remote/host # (notice doubling of slashes at the start of the path) p = '\\\\' + p components = p.split('\\') return urllib.parse.quote('/'.join(components)) comp = p.split(':') if len(comp) != 2 or len(comp[0]) > 1: error = 'Bad path: ' + p raise OSError(error) drive = urllib.parse.quote(comp[0].upper()) components = comp[1].split('\\') path = '///' + drive + ':' for comp in components: if comp: path = path + '/' + urllib.parse.quote(comp) return path
[ "def", "pathname2url", "(", "p", ")", ":", "# e.g.", "# C:\\foo\\bar\\spam.foo", "# becomes", "# ///C:/foo/bar/spam.foo", "import", "urllib", ".", "parse", "if", "not", "':'", "in", "p", ":", "# No drive specifier, just convert slashes and quote the name", "if", "p", ...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/nturl2path.py#L45-L73
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/x86/toolchain/lib/python2.7/lib-tk/Tkinter.py
python
Text.__init__
(self, master=None, cnf={}, **kw)
Construct a text widget with the parent MASTER. STANDARD OPTIONS background, borderwidth, cursor, exportselection, font, foreground, highlightbackground, highlightcolor, highlightthickness, insertbackground, insertborderwidth, insertofftime, insertontime, insertwidth, padx, pady, relief, selectbackground, selectborderwidth, selectforeground, setgrid, takefocus, xscrollcommand, yscrollcommand, WIDGET-SPECIFIC OPTIONS autoseparators, height, maxundo, spacing1, spacing2, spacing3, state, tabs, undo, width, wrap,
Construct a text widget with the parent MASTER.
[ "Construct", "a", "text", "widget", "with", "the", "parent", "MASTER", "." ]
def __init__(self, master=None, cnf={}, **kw): """Construct a text widget with the parent MASTER. STANDARD OPTIONS background, borderwidth, cursor, exportselection, font, foreground, highlightbackground, highlightcolor, highlightthickness, insertbackground, insertborderwidth, insertofftime, insertontime, insertwidth, padx, pady, relief, selectbackground, selectborderwidth, selectforeground, setgrid, takefocus, xscrollcommand, yscrollcommand, WIDGET-SPECIFIC OPTIONS autoseparators, height, maxundo, spacing1, spacing2, spacing3, state, tabs, undo, width, wrap, """ Widget.__init__(self, master, 'text', cnf, kw)
[ "def", "__init__", "(", "self", ",", "master", "=", "None", ",", "cnf", "=", "{", "}", ",", "*", "*", "kw", ")", ":", "Widget", ".", "__init__", "(", "self", ",", "master", ",", "'text'", ",", "cnf", ",", "kw", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/lib-tk/Tkinter.py#L2866-L2889
eclipse/sumo
7132a9b8b6eea734bdec38479026b4d8c4336d03
tools/generateRailSignalConstraints.py
python
findConflicts
(options, net, switchRoutes, mergeSignals, signalTimes, stopEdges, vehicleStopRoutes)
return conflicts, intermediateParkingConflicts
find stops that target the same busStop from different branches of the prior merge switch and establish their ordering
find stops that target the same busStop from different branches of the prior merge switch and establish their ordering
[ "find", "stops", "that", "target", "the", "same", "busStop", "from", "different", "branches", "of", "the", "prior", "merge", "switch", "and", "establish", "their", "ordering" ]
def findConflicts(options, net, switchRoutes, mergeSignals, signalTimes, stopEdges, vehicleStopRoutes): """find stops that target the same busStop from different branches of the prior merge switch and establish their ordering""" numConflicts = 0 numRedundant = 0 numIgnoredConflicts = 0 numIgnoredStops = 0 # signal -> [(tripID, otherSignal, otherTripID, limit, line, otherLine, vehID, otherVehID), ...] conflicts = defaultdict(list) intermediateParkingConflicts = defaultdict(list) for switch, stopRoutes2 in switchRoutes.items(): numSwitchConflicts = 0 numRedundantSwitchConflicts = 0 numIgnoredSwitchConflicts = 0 numIgnoredSwitchStops = 0 if switch == options.debugSwitch: print("Switch %s lies ahead of busStops %s" % (switch, stopRoutes2.keys())) # detect approaches that skip stops (#8943) and add extra items stopRoutes3 = defaultdict(list) stopsAfterSwitch = defaultdict(set) # edge -> stops for busStop, stops in stopRoutes2.items(): stopsAfterSwitch[stopEdges[busStop]].add(busStop) for busStop, stops in stopRoutes2.items(): for edgesBefore, stop in stops: intermediateStops = set() for edge in edgesBefore: for s in stopsAfterSwitch[edge]: if s != busStop: intermediateStops.add(s) if len(intermediateStops) != 0: # try to establish an order between vehicles from different arms # of the switch even if their immediate stops differs # this is possible (and necessary) if they have a common stop # and their routes are identical between the merging switch and # the first common stop. # note: the first common stop may differ from all stops in stopRoutes2 for busStop2, stops2 in stopRoutes2.items(): if busStop2 in intermediateStops: for edgesBefore2, stop2 in stops2: addCommonStop(options, switch, edgesBefore, stop, edgesBefore2, stop2, vehicleStopRoutes, stopRoutes3) # print("Stop after switch %s at %s by %s (%s, %s) passes intermediate stops %s" % ( # switch, busStop, stop.vehID, # humanReadableTime(parseTime(stop.arrival)), # humanReadableTime(parseTime(stop.until)), # ",".join(intermediateStops) # )) # delay dict merge until all extra stops have been found for busStop, stops in stopRoutes2.items(): stopRoutes3[busStop] += stops for busStop, stops in stopRoutes3.items(): arrivals = [] for edges, stop in stops: if stop.hasAttribute("arrival"): arrival = parseTime(stop.arrival) elif stop.hasAttribute("until"): arrival = parseTime(stop.until) - parseTime(stop.getAttributeSecure("duration", "0")) else: print("ignoring stop at %s without schedule information (arrival, until)" % busStop) continue if stop.getAttributeSecure("invalid", False): numIgnoredSwitchStops += 1 numIgnoredStops += 1 continue arrivals.append((arrival, edges, stop)) arrivals.sort(key=itemgetter(0)) arrivalsBySignal = defaultdict(list) for (pArrival, pEdges, pStop), (nArrival, nEdges, nStop) in zip(arrivals[:-1], arrivals[1:]): pSignal, pTimeSiSt = mergeSignals[(switch, pEdges)] nSignal, nTimeSiSt = mergeSignals[(switch, nEdges)] if switch == options.debugSwitch: print(pSignal, nSignal, pStop, nStop) if (pSignal != nSignal and pSignal is not None and nSignal is not None and pStop.vehID != nStop.vehID): if options.skipParking and parseBool(nStop.getAttributeSecure("parking", "false")): print("ignoring stop at %s for parking vehicle %s (%s, %s)" % ( busStop, nStop.vehID, humanReadableTime(nArrival), (humanReadableTime(parseTime(nStop.until)) if nStop.hasAttribute("until") else "-"))) numIgnoredConflicts += 1 numIgnoredSwitchConflicts += 1 continue if options.skipParking and parseBool(pStop.getAttributeSecure("parking", "false")): print("ignoring stop at %s for %s (%s, %s) after parking vehicle %s (%s, %s)" % ( busStop, nStop.vehID, humanReadableTime(nArrival), (humanReadableTime(parseTime(nStop.until)) if nStop.hasAttribute("until") else "-"), pStop.vehID, humanReadableTime(pArrival), (humanReadableTime(parseTime(pStop.until)) if pStop.hasAttribute("until") else "-"))) numIgnoredConflicts += 1 numIgnoredSwitchConflicts += 1 continue if (nStop.intermediateStop and pStop.intermediateStop and nStop.intermediateStop.busStop == pStop.intermediateStop.busStop): # intermediate conflict was added via other foes and this particular conflict is a normal one continue numConflicts += 1 numSwitchConflicts += 1 # check for trains that pass the switch in between the # current two trains (heading to another stop) and raise the limit limit = 1 pTimeAtSignal = pArrival - pTimeSiSt nTimeAtSignal = nArrival - nTimeSiSt end = nTimeAtSignal + options.delay if options.verbose and options.debugSignal == pSignal: print("check vehicles between %s and %s (including delay %s) at signal %s pStop=%s nStop=%s" % ( humanReadableTime(pTimeAtSignal), humanReadableTime(end), options.delay, pSignal, pStop, nStop)) times = "arrival=%s foeArrival=%s " % (humanReadableTime(nArrival), humanReadableTime(pArrival)) info = getIntermediateInfo(pStop, nStop) isIntermediateParking = nStop.intermediateStop and parseBool( nStop.intermediateStop.getAttributeSecure("parking", "false")) if isIntermediateParking: # intermediateParkingConflicts: train oder isn't determined at the switch # but rather when the second vehicle leaves it's parking stop stopEdge = stopEdges[nStop.intermediateStop.busStop] signal = findSignal(net, (stopEdge,) + nStop.edgesBeforeCommon) if signal is None: print(("Ignoring intermediate parking insertion conflict between %s and %s at stop '%s' " + "because no rail signal was found after the stop") % (nStop.tripID, pStop.prevTripId, nStop.intermediateStop.busStop), file=sys.stderr) continue times = "intermediateArrival=%s %s" % (humanReadableTime( parseTime(nStop.intermediateStop.arrival)), times) info = "intermediateParking " + info intermediateParkingConflicts[signal].append(Conflict(nStop.prevTripId, signal, pStop.prevTripId, limit, # attributes for adding comments nStop.prevLine, pStop.prevLine, nStop.vehID, pStop.vehID, times, switch, nStop.intermediateStop.busStop, info)) else: info = getIntermediateInfo(pStop, nStop) limit += countPassingTrainsToOtherStops(options, pSignal, busStop, pTimeAtSignal, end, signalTimes) conflicts[nSignal].append(Conflict(nStop.prevTripId, pSignal, pStop.prevTripId, limit, # attributes for adding comments nStop.prevLine, pStop.prevLine, nStop.vehID, pStop.vehID, times, switch, nStop.busStop, info)) if options.redundant >= 0: prevBegin = pTimeAtSignal for p2Arrival, p2Stop in reversed(arrivalsBySignal[pSignal]): if pArrival - p2Arrival > options.redundant: break if (nStop.intermediateStop and pStop.intermediateStop and nStop.intermediateStop.busStop == pStop.intermediateStop.busStop): # intermediate conflict was added via other foes # and this particular conflict is a normal one continue if isIntermediateParking: # no redundant parking insertion conflicts for intermediate stops continue numRedundant += 1 numRedundantSwitchConflicts += 1 p2TimeAtSignal = p2Arrival - pTimeSiSt limit += 1 limit += countPassingTrainsToOtherStops(options, pSignal, busStop, p2TimeAtSignal, prevBegin, signalTimes) info = getIntermediateInfo(p2Stop, nStop) times = "arrival=%s foeArrival=%s " % ( humanReadableTime(nArrival), humanReadableTime(p2Arrival)) conflicts[nSignal].append(Conflict(nStop.prevTripId, pSignal, p2Stop.prevTripId, limit, # attributes for adding comments nStop.prevLine, p2Stop.prevLine, nStop.vehID, p2Stop.vehID, times, switch, nStop.busStop, info)) prevBegin = p2TimeAtSignal if pSignal is not None and not ( options.skipParking and parseBool(pStop.getAttributeSecure("parking", "false"))): arrivalsBySignal[pSignal].append((pArrival, pStop)) if options.verbose: print("Found %s conflicts at switch %s" % (numSwitchConflicts, switch)) if numRedundantSwitchConflicts > 0: print("Found %s redundant conflicts at switch %s" % (numRedundantSwitchConflicts, switch)) if numIgnoredSwitchConflicts > 0 or numIgnoredSwitchStops > 0: print("Ignored %s conflicts and % stops at switch %s" % (numIgnoredSwitchConflicts, numIgnoredSwitchStops, switch)) print("Found %s conflicts" % numConflicts) if numRedundant > 0: print("Found %s redundant conflicts" % numRedundant) if numIgnoredConflicts > 0 or numIgnoredStops > 0: print("Ignored %s conflicts and %s stops" % (numIgnoredConflicts, numIgnoredStops)) return conflicts, intermediateParkingConflicts
[ "def", "findConflicts", "(", "options", ",", "net", ",", "switchRoutes", ",", "mergeSignals", ",", "signalTimes", ",", "stopEdges", ",", "vehicleStopRoutes", ")", ":", "numConflicts", "=", "0", "numRedundant", "=", "0", "numIgnoredConflicts", "=", "0", "numIgnor...
https://github.com/eclipse/sumo/blob/7132a9b8b6eea734bdec38479026b4d8c4336d03/tools/generateRailSignalConstraints.py#L699-L896
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/aui/dockart.py
python
AuiDefaultDockArt.DrawSash
(self, dc, window, orient, rect)
Draws a sash between two windows. :param `dc`: a :class:`DC` device context; :param `window`: an instance of :class:`Window`; :param integer `orient`: the sash orientation; :param Rect `rect`: the sash rectangle.
Draws a sash between two windows.
[ "Draws", "a", "sash", "between", "two", "windows", "." ]
def DrawSash(self, dc, window, orient, rect): """ Draws a sash between two windows. :param `dc`: a :class:`DC` device context; :param `window`: an instance of :class:`Window`; :param integer `orient`: the sash orientation; :param Rect `rect`: the sash rectangle. """ # AG: How do we make this work?!? # RendererNative does not use the sash_brush chosen by the user # and the rect.GetSize() is ignored as the sash is always drawn # 3 pixel wide # wx.RendererNative.Get().DrawSplitterSash(window, dc, rect.GetSize(), pos, orient) dc.SetPen(wx.TRANSPARENT_PEN) dc.SetBrush(self._sash_brush) dc.DrawRectangle(rect.x, rect.y, rect.width, rect.height) draw_sash = self.GetMetric(AUI_DOCKART_DRAW_SASH_GRIP) if draw_sash: self.DrawSashGripper(dc, orient, rect)
[ "def", "DrawSash", "(", "self", ",", "dc", ",", "window", ",", "orient", ",", "rect", ")", ":", "# AG: How do we make this work?!?", "# RendererNative does not use the sash_brush chosen by the user", "# and the rect.GetSize() is ignored as the sash is always drawn", "# 3 pixel wide...
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/aui/dockart.py#L405-L427
etternagame/etterna
8775f74ac9c353320128609d4b4150672e9a6d04
extern/crashpad/crashpad/third_party/mini_chromium/mini_chromium/build/ios/codesign.py
python
ProvisioningProfile.ValidToSignBundle
(self, bundle_identifier)
return fnmatch.fnmatch( '%s.%s' % (self.team_identifier, bundle_identifier), self.application_identifier_pattern)
Checks whether the provisioning profile can sign bundle_identifier. Args: bundle_identifier: the identifier of the bundle that needs to be signed. Returns: True if the mobile provisioning profile can be used to sign a bundle with the corresponding bundle_identifier, False otherwise.
Checks whether the provisioning profile can sign bundle_identifier.
[ "Checks", "whether", "the", "provisioning", "profile", "can", "sign", "bundle_identifier", "." ]
def ValidToSignBundle(self, bundle_identifier): """Checks whether the provisioning profile can sign bundle_identifier. Args: bundle_identifier: the identifier of the bundle that needs to be signed. Returns: True if the mobile provisioning profile can be used to sign a bundle with the corresponding bundle_identifier, False otherwise. """ return fnmatch.fnmatch( '%s.%s' % (self.team_identifier, bundle_identifier), self.application_identifier_pattern)
[ "def", "ValidToSignBundle", "(", "self", ",", "bundle_identifier", ")", ":", "return", "fnmatch", ".", "fnmatch", "(", "'%s.%s'", "%", "(", "self", ".", "team_identifier", ",", "bundle_identifier", ")", ",", "self", ".", "application_identifier_pattern", ")" ]
https://github.com/etternagame/etterna/blob/8775f74ac9c353320128609d4b4150672e9a6d04/extern/crashpad/crashpad/third_party/mini_chromium/mini_chromium/build/ios/codesign.py#L116-L128
whai362/PSENet
4d95395658662f2223805c36dcd573d9e190ce26
eval/ic15_rec/rrc_evaluation_funcs_1_1.py
python
load_zip_file_keys
(file,fileNameRegExp='')
return pairs
Returns an array with the entries of the ZIP file that match with the regular expression. The key's are the names or the file or the capturing group definied in the fileNameRegExp
Returns an array with the entries of the ZIP file that match with the regular expression. The key's are the names or the file or the capturing group definied in the fileNameRegExp
[ "Returns", "an", "array", "with", "the", "entries", "of", "the", "ZIP", "file", "that", "match", "with", "the", "regular", "expression", ".", "The", "key", "s", "are", "the", "names", "or", "the", "file", "or", "the", "capturing", "group", "definied", "i...
def load_zip_file_keys(file,fileNameRegExp=''): """ Returns an array with the entries of the ZIP file that match with the regular expression. The key's are the names or the file or the capturing group definied in the fileNameRegExp """ try: archive=zipfile.ZipFile(file, mode='r', allowZip64=True) except: raise Exception('Error loading the ZIP archive.') pairs = [] for name in archive.namelist(): addFile = True keyName = name if fileNameRegExp!="": m = re.match(fileNameRegExp,name) if m == None: addFile = False else: if len(m.groups())>0: keyName = m.group(1) if addFile: pairs.append( keyName ) return pairs
[ "def", "load_zip_file_keys", "(", "file", ",", "fileNameRegExp", "=", "''", ")", ":", "try", ":", "archive", "=", "zipfile", ".", "ZipFile", "(", "file", ",", "mode", "=", "'r'", ",", "allowZip64", "=", "True", ")", "except", ":", "raise", "Exception", ...
https://github.com/whai362/PSENet/blob/4d95395658662f2223805c36dcd573d9e190ce26/eval/ic15_rec/rrc_evaluation_funcs_1_1.py#L23-L49
CRYTEK/CRYENGINE
232227c59a220cbbd311576f0fbeba7bb53b2a8c
Editor/Python/windows/Lib/site-packages/pip/wheel.py
python
uninstallation_paths
(dist)
Yield all the uninstallation paths for dist based on RECORD-without-.pyc Yield paths to all the files in RECORD. For each .py file in RECORD, add the .pyc in the same directory. UninstallPathSet.add() takes care of the __pycache__ .pyc.
Yield all the uninstallation paths for dist based on RECORD-without-.pyc
[ "Yield", "all", "the", "uninstallation", "paths", "for", "dist", "based", "on", "RECORD", "-", "without", "-", ".", "pyc" ]
def uninstallation_paths(dist): """ Yield all the uninstallation paths for dist based on RECORD-without-.pyc Yield paths to all the files in RECORD. For each .py file in RECORD, add the .pyc in the same directory. UninstallPathSet.add() takes care of the __pycache__ .pyc. """ from pip.utils import FakeFile # circular import r = csv.reader(FakeFile(dist.get_metadata_lines('RECORD'))) for row in r: path = os.path.join(dist.location, row[0]) yield path if path.endswith('.py'): dn, fn = os.path.split(path) base = fn[:-3] path = os.path.join(dn, base + '.pyc') yield path
[ "def", "uninstallation_paths", "(", "dist", ")", ":", "from", "pip", ".", "utils", "import", "FakeFile", "# circular import", "r", "=", "csv", ".", "reader", "(", "FakeFile", "(", "dist", ".", "get_metadata_lines", "(", "'RECORD'", ")", ")", ")", "for", "r...
https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Editor/Python/windows/Lib/site-packages/pip/wheel.py#L520-L538
gem5/gem5
141cc37c2d4b93959d4c249b8f7e6a8b2ef75338
ext/pybind11/pybind11/setup_helpers.py
python
auto_cpp_level
(compiler)
Return the max supported C++ std level (17, 14, or 11). Returns latest on Windows.
Return the max supported C++ std level (17, 14, or 11). Returns latest on Windows.
[ "Return", "the", "max", "supported", "C", "++", "std", "level", "(", "17", "14", "or", "11", ")", ".", "Returns", "latest", "on", "Windows", "." ]
def auto_cpp_level(compiler): """ Return the max supported C++ std level (17, 14, or 11). Returns latest on Windows. """ if WIN: return "latest" global cpp_flag_cache # If this has been previously calculated with the same args, return that with cpp_cache_lock: if cpp_flag_cache: return cpp_flag_cache levels = [17, 14, 11] for level in levels: if has_flag(compiler, STD_TMPL.format(level)): with cpp_cache_lock: cpp_flag_cache = level return level msg = "Unsupported compiler -- at least C++11 support is needed!" raise RuntimeError(msg)
[ "def", "auto_cpp_level", "(", "compiler", ")", ":", "if", "WIN", ":", "return", "\"latest\"", "global", "cpp_flag_cache", "# If this has been previously calculated with the same args, return that", "with", "cpp_cache_lock", ":", "if", "cpp_flag_cache", ":", "return", "cpp_f...
https://github.com/gem5/gem5/blob/141cc37c2d4b93959d4c249b8f7e6a8b2ef75338/ext/pybind11/pybind11/setup_helpers.py#L256-L280
tuttleofx/TuttleOFX
36fc4cae15092a84ea8c29b9c6658c7cabfadb6e
applications/sam/sam_do.py
python
Sam_do._displayClipHelp
(self, clip)
Display help of the given OFXClip.
Display help of the given OFXClip.
[ "Display", "help", "of", "the", "given", "OFXClip", "." ]
def _displayClipHelp(self, clip): """ Display help of the given OFXClip. """ # Components components = clip.getSupportedComponents() componentsStr = [] for component in components: componentsStr.append(component[17:]) # remove 'OfxImageComponent' # Property properties = [] if clip.getProperties().getIntProperty('OfxImageClipPropOptional'): properties.append('optional') if clip.isMask(): properties.append('mask') if clip.temporalAccess(): properties.append('use temporal access') # Print with indent(4): puts('{clipName!s:10}: {clipComponents} {clipProperties}'.format( clipName=colored.green(clip.getName()), clipComponents=('[' + (', '.join(componentsStr)) + ']'), clipProperties=(', '.join(properties))))
[ "def", "_displayClipHelp", "(", "self", ",", "clip", ")", ":", "# Components", "components", "=", "clip", ".", "getSupportedComponents", "(", ")", "componentsStr", "=", "[", "]", "for", "component", "in", "components", ":", "componentsStr", ".", "append", "(",...
https://github.com/tuttleofx/TuttleOFX/blob/36fc4cae15092a84ea8c29b9c6658c7cabfadb6e/applications/sam/sam_do.py#L314-L336
ricardoquesada/Spidermonkey
4a75ea2543408bd1b2c515aa95901523eeef7858
python/mach/mach/logging.py
python
LoggingManager.register_structured_logger
(self, logger)
Register a structured logger. This needs to be called for all structured loggers that don't chain up to the mach logger in order for their output to be captured.
Register a structured logger.
[ "Register", "a", "structured", "logger", "." ]
def register_structured_logger(self, logger): """Register a structured logger. This needs to be called for all structured loggers that don't chain up to the mach logger in order for their output to be captured. """ self.structured_loggers.append(logger)
[ "def", "register_structured_logger", "(", "self", ",", "logger", ")", ":", "self", ".", "structured_loggers", ".", "append", "(", "logger", ")" ]
https://github.com/ricardoquesada/Spidermonkey/blob/4a75ea2543408bd1b2c515aa95901523eeef7858/python/mach/mach/logging.py#L250-L256
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/pkg_resources/__init__.py
python
_version_from_file
(lines)
return safe_version(value.strip()) or None
Given an iterable of lines from a Metadata file, return the value of the Version field, if present, or None otherwise.
Given an iterable of lines from a Metadata file, return the value of the Version field, if present, or None otherwise.
[ "Given", "an", "iterable", "of", "lines", "from", "a", "Metadata", "file", "return", "the", "value", "of", "the", "Version", "field", "if", "present", "or", "None", "otherwise", "." ]
def _version_from_file(lines): """ Given an iterable of lines from a Metadata file, return the value of the Version field, if present, or None otherwise. """ def is_version_line(line): return line.lower().startswith('version:') version_lines = filter(is_version_line, lines) line = next(iter(version_lines), '') _, _, value = line.partition(':') return safe_version(value.strip()) or None
[ "def", "_version_from_file", "(", "lines", ")", ":", "def", "is_version_line", "(", "line", ")", ":", "return", "line", ".", "lower", "(", ")", ".", "startswith", "(", "'version:'", ")", "version_lines", "=", "filter", "(", "is_version_line", ",", "lines", ...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/pkg_resources/__init__.py#L2548-L2558
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/numpy/py3/numpy/compat/_inspect.py
python
ismethod
(object)
return isinstance(object, types.MethodType)
Return true if the object is an instance method. Instance method objects provide these attributes: __doc__ documentation string __name__ name with which this method was defined im_class class object in which this method belongs im_func function object containing implementation of method im_self instance to which this method is bound, or None
Return true if the object is an instance method.
[ "Return", "true", "if", "the", "object", "is", "an", "instance", "method", "." ]
def ismethod(object): """Return true if the object is an instance method. Instance method objects provide these attributes: __doc__ documentation string __name__ name with which this method was defined im_class class object in which this method belongs im_func function object containing implementation of method im_self instance to which this method is bound, or None """ return isinstance(object, types.MethodType)
[ "def", "ismethod", "(", "object", ")", ":", "return", "isinstance", "(", "object", ",", "types", ".", "MethodType", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py3/numpy/compat/_inspect.py#L13-L24
hfinkel/llvm-project-cxxjit
91084ef018240bbb8e24235ff5cd8c355a9c1a1e
lldb/utils/lui/lldbutil.py
python
get_description
(obj, option=None)
return stream.GetData()
Calls lldb_obj.GetDescription() and returns a string, or None. For SBTarget, SBBreakpointLocation, and SBWatchpoint lldb objects, an extra option can be passed in to describe the detailed level of description desired: o lldb.eDescriptionLevelBrief o lldb.eDescriptionLevelFull o lldb.eDescriptionLevelVerbose
Calls lldb_obj.GetDescription() and returns a string, or None.
[ "Calls", "lldb_obj", ".", "GetDescription", "()", "and", "returns", "a", "string", "or", "None", "." ]
def get_description(obj, option=None): """Calls lldb_obj.GetDescription() and returns a string, or None. For SBTarget, SBBreakpointLocation, and SBWatchpoint lldb objects, an extra option can be passed in to describe the detailed level of description desired: o lldb.eDescriptionLevelBrief o lldb.eDescriptionLevelFull o lldb.eDescriptionLevelVerbose """ method = getattr(obj, 'GetDescription') if not method: return None tuple = (lldb.SBTarget, lldb.SBBreakpointLocation, lldb.SBWatchpoint) if isinstance(obj, tuple): if option is None: option = lldb.eDescriptionLevelBrief stream = lldb.SBStream() if option is None: success = method(stream) else: success = method(stream, option) if not success: return None return stream.GetData()
[ "def", "get_description", "(", "obj", ",", "option", "=", "None", ")", ":", "method", "=", "getattr", "(", "obj", ",", "'GetDescription'", ")", "if", "not", "method", ":", "return", "None", "tuple", "=", "(", "lldb", ".", "SBTarget", ",", "lldb", ".", ...
https://github.com/hfinkel/llvm-project-cxxjit/blob/91084ef018240bbb8e24235ff5cd8c355a9c1a1e/lldb/utils/lui/lldbutil.py#L119-L144
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/AWSPythonSDK/1.5.8/boto3/dynamodb/conditions.py
python
Attr.is_in
(self, value)
return In(self, value)
Creates a condition where the attribute is in the value, :type value: list :param value: The value that the attribute is in.
Creates a condition where the attribute is in the value,
[ "Creates", "a", "condition", "where", "the", "attribute", "is", "in", "the", "value" ]
def is_in(self, value): """Creates a condition where the attribute is in the value, :type value: list :param value: The value that the attribute is in. """ return In(self, value)
[ "def", "is_in", "(", "self", ",", "value", ")", ":", "return", "In", "(", "self", ",", "value", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/AWSPythonSDK/1.5.8/boto3/dynamodb/conditions.py#L237-L243
bundy-dns/bundy
3d41934996b82b0cd2fe22dd74d2abc1daba835d
src/lib/python/bundy/ddns/session.py
python
UpdateSession.__prereq_rrset_exists
(self, rrset)
return result == ZoneFinder.SUCCESS
Check whether an rrset with the given name and type exists. Class, TTL, and Rdata (if any) of the given RRset are ignored. RFC2136 Section 2.4.1. Returns True if the prerequisite is satisfied, False otherwise. Note: the only thing used in the call to find() here is the result status. The actual data is immediately dropped. As a future optimization, we may want to add a find() option to only return what the result code would be (and not read/copy any actual data).
Check whether an rrset with the given name and type exists. Class, TTL, and Rdata (if any) of the given RRset are ignored. RFC2136 Section 2.4.1. Returns True if the prerequisite is satisfied, False otherwise.
[ "Check", "whether", "an", "rrset", "with", "the", "given", "name", "and", "type", "exists", ".", "Class", "TTL", "and", "Rdata", "(", "if", "any", ")", "of", "the", "given", "RRset", "are", "ignored", ".", "RFC2136", "Section", "2", ".", "4", ".", "1...
def __prereq_rrset_exists(self, rrset): '''Check whether an rrset with the given name and type exists. Class, TTL, and Rdata (if any) of the given RRset are ignored. RFC2136 Section 2.4.1. Returns True if the prerequisite is satisfied, False otherwise. Note: the only thing used in the call to find() here is the result status. The actual data is immediately dropped. As a future optimization, we may want to add a find() option to only return what the result code would be (and not read/copy any actual data). ''' result, _, _ = self.__diff.find(rrset.get_name(), rrset.get_type()) return result == ZoneFinder.SUCCESS
[ "def", "__prereq_rrset_exists", "(", "self", ",", "rrset", ")", ":", "result", ",", "_", ",", "_", "=", "self", ".", "__diff", ".", "find", "(", "rrset", ".", "get_name", "(", ")", ",", "rrset", ".", "get_type", "(", ")", ")", "return", "result", "...
https://github.com/bundy-dns/bundy/blob/3d41934996b82b0cd2fe22dd74d2abc1daba835d/src/lib/python/bundy/ddns/session.py#L381-L394
intel-iot-devkit/how-to-code-samples
b4ea616f36bbfa2e042beb1698f968cfd651d79f
storage-unit-flood-detector/python/iot_storage_unit_flood_detector/hardware/grove.py
python
GroveBoard.update_hardware_state
(self)
Update hardware state.
Update hardware state.
[ "Update", "hardware", "state", "." ]
def update_hardware_state(self): """ Update hardware state. """ moisture_reading = self.read_moisture() self.trigger_hardware_event(MOISTURE_SAMPLE, moisture_reading)
[ "def", "update_hardware_state", "(", "self", ")", ":", "moisture_reading", "=", "self", ".", "read_moisture", "(", ")", "self", ".", "trigger_hardware_event", "(", "MOISTURE_SAMPLE", ",", "moisture_reading", ")" ]
https://github.com/intel-iot-devkit/how-to-code-samples/blob/b4ea616f36bbfa2e042beb1698f968cfd651d79f/storage-unit-flood-detector/python/iot_storage_unit_flood_detector/hardware/grove.py#L53-L60
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/eager/python/examples/revnet/resnet_preprocessing.py
python
preprocess_image
(image_bytes, is_training=False, use_bfloat16=False, image_size=IMAGE_SIZE)
Preprocesses the given image. Args: image_bytes: `Tensor` representing an image binary of arbitrary size. is_training: `bool` for whether the preprocessing is for training. use_bfloat16: `bool` for whether to use bfloat16. image_size: image size. Returns: A preprocessed image `Tensor`.
Preprocesses the given image.
[ "Preprocesses", "the", "given", "image", "." ]
def preprocess_image(image_bytes, is_training=False, use_bfloat16=False, image_size=IMAGE_SIZE): """Preprocesses the given image. Args: image_bytes: `Tensor` representing an image binary of arbitrary size. is_training: `bool` for whether the preprocessing is for training. use_bfloat16: `bool` for whether to use bfloat16. image_size: image size. Returns: A preprocessed image `Tensor`. """ if is_training: return preprocess_for_train(image_bytes, use_bfloat16, image_size) else: return preprocess_for_eval(image_bytes, use_bfloat16, image_size)
[ "def", "preprocess_image", "(", "image_bytes", ",", "is_training", "=", "False", ",", "use_bfloat16", "=", "False", ",", "image_size", "=", "IMAGE_SIZE", ")", ":", "if", "is_training", ":", "return", "preprocess_for_train", "(", "image_bytes", ",", "use_bfloat16",...
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/eager/python/examples/revnet/resnet_preprocessing.py#L172-L190
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_internal/operations/install/wheel.py
python
rehash
(path, blocksize=1 << 20)
return (digest, str(length))
Return (encoded_digest, length) for path using hashlib.sha256()
Return (encoded_digest, length) for path using hashlib.sha256()
[ "Return", "(", "encoded_digest", "length", ")", "for", "path", "using", "hashlib", ".", "sha256", "()" ]
def rehash(path, blocksize=1 << 20): # type: (str, int) -> Tuple[str, str] """Return (encoded_digest, length) for path using hashlib.sha256()""" h, length = hash_file(path, blocksize) digest = 'sha256=' + urlsafe_b64encode( h.digest() ).decode('latin1').rstrip('=') return (digest, str(length))
[ "def", "rehash", "(", "path", ",", "blocksize", "=", "1", "<<", "20", ")", ":", "# type: (str, int) -> Tuple[str, str]", "h", ",", "length", "=", "hash_file", "(", "path", ",", "blocksize", ")", "digest", "=", "'sha256='", "+", "urlsafe_b64encode", "(", "h",...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_internal/operations/install/wheel.py#L86-L93
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/build/waf-1.7.13/waflib/Utils.py
python
extended_path
(path)
Maximum Path Length Limitation on Windows is 260 characters, use extended-length path to bypass this limitation
Maximum Path Length Limitation on Windows is 260 characters, use extended-length path to bypass this limitation
[ "Maximum", "Path", "Length", "Limitation", "on", "Windows", "is", "260", "characters", "use", "extended", "-", "length", "path", "to", "bypass", "this", "limitation" ]
def extended_path(path): """ Maximum Path Length Limitation on Windows is 260 characters, use extended-length path to bypass this limitation """ if is_win32 and len(path) >= 260: if path.startswith('\\'): return r'\\?\UNC\{}'.format(path.lstrip('\\')) else: return r'\\?\{}'.format(path) else: return path
[ "def", "extended_path", "(", "path", ")", ":", "if", "is_win32", "and", "len", "(", "path", ")", ">=", "260", ":", "if", "path", ".", "startswith", "(", "'\\\\'", ")", ":", "return", "r'\\\\?\\UNC\\{}'", ".", "format", "(", "path", ".", "lstrip", "(", ...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/build/waf-1.7.13/waflib/Utils.py#L113-L123
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_core.py
python
Sizer.Show
(*args, **kwargs)
return _core_.Sizer_Show(*args, **kwargs)
Show(self, item, bool show=True, bool recursive=false) -> bool Shows or hides an item managed by the sizer. To make a sizer item disappear or reappear, use Show followed by `Layout`. The *item* parameter can be either a window, a sizer, or the zero-based index of the item. Use the recursive parameter to show or hide an item in a subsizer. Returns True if the item was found.
Show(self, item, bool show=True, bool recursive=false) -> bool
[ "Show", "(", "self", "item", "bool", "show", "=", "True", "bool", "recursive", "=", "false", ")", "-", ">", "bool" ]
def Show(*args, **kwargs): """ Show(self, item, bool show=True, bool recursive=false) -> bool Shows or hides an item managed by the sizer. To make a sizer item disappear or reappear, use Show followed by `Layout`. The *item* parameter can be either a window, a sizer, or the zero-based index of the item. Use the recursive parameter to show or hide an item in a subsizer. Returns True if the item was found. """ return _core_.Sizer_Show(*args, **kwargs)
[ "def", "Show", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "Sizer_Show", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_core.py#L14966-L14976
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/fitting_widgets/basic_fitting/basic_fitting_view.py
python
BasicFittingView.switch_to_single
(self)
Switches the view to single fit mode.
Switches the view to single fit mode.
[ "Switches", "the", "view", "to", "single", "fit", "mode", "." ]
def switch_to_single(self) -> None: """Switches the view to single fit mode.""" self.fit_function_options.switch_to_single()
[ "def", "switch_to_single", "(", "self", ")", "->", "None", ":", "self", ".", "fit_function_options", ".", "switch_to_single", "(", ")" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/fitting_widgets/basic_fitting/basic_fitting_view.py#L332-L334
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/_core.py
python
MemoryFSHandler.AddFileWithMimeType
(*args, **kwargs)
return _core_.MemoryFSHandler_AddFileWithMimeType(*args, **kwargs)
AddFileWithMimeType(String filename, buffer data, String mimetype)
AddFileWithMimeType(String filename, buffer data, String mimetype)
[ "AddFileWithMimeType", "(", "String", "filename", "buffer", "data", "String", "mimetype", ")" ]
def AddFileWithMimeType(*args, **kwargs): """AddFileWithMimeType(String filename, buffer data, String mimetype)""" return _core_.MemoryFSHandler_AddFileWithMimeType(*args, **kwargs)
[ "def", "AddFileWithMimeType", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "MemoryFSHandler_AddFileWithMimeType", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_core.py#L2569-L2571
Cantera/cantera
0119484b261967ccb55a0066c020599cacc312e4
interfaces/cython/cantera/ck2cti.py
python
get_index
(seq, value)
return None
Find the first location in *seq* which contains a case-insensitive, whitespace-insensitive match for *value*. Returns *None* if no match is found.
Find the first location in *seq* which contains a case-insensitive, whitespace-insensitive match for *value*. Returns *None* if no match is found.
[ "Find", "the", "first", "location", "in", "*", "seq", "*", "which", "contains", "a", "case", "-", "insensitive", "whitespace", "-", "insensitive", "match", "for", "*", "value", "*", ".", "Returns", "*", "None", "*", "if", "no", "match", "is", "found", ...
def get_index(seq, value): """ Find the first location in *seq* which contains a case-insensitive, whitespace-insensitive match for *value*. Returns *None* if no match is found. """ if isinstance(seq, string_types): seq = seq.split() value = value.lower().strip() for i, item in enumerate(seq): if item.lower() == value: return i return None
[ "def", "get_index", "(", "seq", ",", "value", ")", ":", "if", "isinstance", "(", "seq", ",", "string_types", ")", ":", "seq", "=", "seq", ".", "split", "(", ")", "value", "=", "value", ".", "lower", "(", ")", ".", "strip", "(", ")", "for", "i", ...
https://github.com/Cantera/cantera/blob/0119484b261967ccb55a0066c020599cacc312e4/interfaces/cython/cantera/ck2cti.py#L922-L934
taichi-dev/taichi
973c04d6ba40f34e9e3bd5a28ae0ee0802f136a6
python/taichi/lang/common_ops.py
python
TaichiOperations.assign
(self, other)
return ops.assign(self, other)
Assign the expression of the given operand to self. Args: other (Any): Given operand. Returns: :class:`~taichi.lang.expr.Expr`: The expression after assigning.
Assign the expression of the given operand to self.
[ "Assign", "the", "expression", "of", "the", "given", "operand", "to", "self", "." ]
def assign(self, other): """Assign the expression of the given operand to self. Args: other (Any): Given operand. Returns: :class:`~taichi.lang.expr.Expr`: The expression after assigning.""" return ops.assign(self, other)
[ "def", "assign", "(", "self", ",", "other", ")", ":", "return", "ops", ".", "assign", "(", "self", ",", "other", ")" ]
https://github.com/taichi-dev/taichi/blob/973c04d6ba40f34e9e3bd5a28ae0ee0802f136a6/python/taichi/lang/common_ops.py#L227-L235
FreeCAD/FreeCAD
ba42231b9c6889b89e064d6d563448ed81e376ec
src/Mod/Draft/draftviewproviders/view_dimension.py
python
ViewProviderDimensionBase.__setstate__
(self, state)
Set the internal properties from the restored state. Restore the display mode.
Set the internal properties from the restored state.
[ "Set", "the", "internal", "properties", "from", "the", "restored", "state", "." ]
def __setstate__(self, state): """Set the internal properties from the restored state. Restore the display mode. """ if state: self.defaultmode = state self.setDisplayMode(state)
[ "def", "__setstate__", "(", "self", ",", "state", ")", ":", "if", "state", ":", "self", ".", "defaultmode", "=", "state", "self", ".", "setDisplayMode", "(", "state", ")" ]
https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Draft/draftviewproviders/view_dimension.py#L332-L339
zlgopen/awtk
2c49e854a78749d9092907c027a7fba9062be549
3rd/mbedtls/scripts/mbedtls_dev/c_build_helper.py
python
generate_c_file
(c_file, caller, header, main_generator)
Generate a temporary C source file. * ``c_file`` is an open stream on the C source file. * ``caller``: an informational string written in a comment at the top of the file. * ``header``: extra code to insert before any function in the generated C file. * ``main_generator``: a function called with ``c_file`` as its sole argument to generate the body of the ``main()`` function.
Generate a temporary C source file.
[ "Generate", "a", "temporary", "C", "source", "file", "." ]
def generate_c_file(c_file, caller, header, main_generator): """Generate a temporary C source file. * ``c_file`` is an open stream on the C source file. * ``caller``: an informational string written in a comment at the top of the file. * ``header``: extra code to insert before any function in the generated C file. * ``main_generator``: a function called with ``c_file`` as its sole argument to generate the body of the ``main()`` function. """ c_file.write('/* Generated by {} */' .format(caller)) c_file.write(''' #include <stdio.h> ''') c_file.write(header) c_file.write(''' int main(void) { ''') main_generator(c_file) c_file.write(''' return 0; } ''')
[ "def", "generate_c_file", "(", "c_file", ",", "caller", ",", "header", ",", "main_generator", ")", ":", "c_file", ".", "write", "(", "'/* Generated by {} */'", ".", "format", "(", "caller", ")", ")", "c_file", ".", "write", "(", "'''\n#include <stdio.h>\n'''", ...
https://github.com/zlgopen/awtk/blob/2c49e854a78749d9092907c027a7fba9062be549/3rd/mbedtls/scripts/mbedtls_dev/c_build_helper.py#L64-L90
named-data/NFD
b98aa3aca6b583ef34df7ee2f317321358f42dd0
.waf-tools/boost.py
python
check_boost
(self, *k, **kw)
Initialize boost libraries to be used. Keywords: you can pass the same parameters as with the command line (without "--boost-"). Note that the command line has the priority, and should preferably be used.
Initialize boost libraries to be used.
[ "Initialize", "boost", "libraries", "to", "be", "used", "." ]
def check_boost(self, *k, **kw): """ Initialize boost libraries to be used. Keywords: you can pass the same parameters as with the command line (without "--boost-"). Note that the command line has the priority, and should preferably be used. """ if not self.env['CXX']: self.fatal('load a c++ compiler first, conf.load("compiler_cxx")') params = { 'lib': k and k[0] or kw.get('lib', None), 'stlib': kw.get('stlib', None) } for key, value in self.options.__dict__.items(): if not key.startswith('boost_'): continue key = key[len('boost_'):] params[key] = value and value or kw.get(key, '') var = kw.get('uselib_store', 'BOOST') if not self.env.DONE_FIND_BOOST_COMMON: self.find_program('dpkg-architecture', var='DPKG_ARCHITECTURE', mandatory=False) if self.env.DPKG_ARCHITECTURE: deb_host_multiarch = self.cmd_and_log([self.env.DPKG_ARCHITECTURE[0], '-qDEB_HOST_MULTIARCH']) BOOST_LIBS.insert(0, '/usr/lib/%s' % deb_host_multiarch.strip()) self.start_msg('Checking boost includes') self.env['INCLUDES_%s' % var] = inc = self.boost_get_includes(**params) versions = self.boost_get_version(inc) self.env.BOOST_VERSION = versions[0] self.env.BOOST_VERSION_NUMBER = int(versions[1]) self.end_msg('%d.%d.%d' % (int(versions[1]) / 100000, int(versions[1]) / 100 % 1000, int(versions[1]) % 100)) if Logs.verbose: Logs.pprint('CYAN', ' path : %s' % self.env['INCLUDES_%s' % var]) self.env.DONE_FIND_BOOST_COMMON = True if not params['lib'] and not params['stlib']: return if 'static' in kw or 'static' in params: Logs.warn('boost: static parameter is deprecated, use stlib instead.') self.start_msg('Checking boost libs') path, libs, stlibs = self.boost_get_libs(**params) self.env['LIBPATH_%s' % var] = [path] self.env['STLIBPATH_%s' % var] = [path] self.env['LIB_%s' % var] = libs self.env['STLIB_%s' % var] = stlibs self.end_msg(' '.join(libs + stlibs)) if Logs.verbose: Logs.pprint('CYAN', ' path : %s' % path) Logs.pprint('CYAN', ' shared libs : %s' % libs) Logs.pprint('CYAN', ' static libs : %s' % stlibs) def has_shlib(lib): return params['lib'] and lib in params['lib'] def has_stlib(lib): return params['stlib'] and lib in params['stlib'] def has_lib(lib): return has_shlib(lib) or has_stlib(lib) if has_lib('thread'): # not inside try_link to make check visible in the output self._check_pthread_flag(k, kw) def try_link(): if has_lib('system'): self.check_cxx(fragment=BOOST_ERROR_CODE, use=var, execute=False) if has_lib('thread'): self.check_cxx(fragment=BOOST_THREAD_CODE, use=var, execute=False) if has_lib('log') or has_lib('log_setup'): if not has_lib('thread'): self.env['DEFINES_%s' % var] += ['BOOST_LOG_NO_THREADS'] if has_shlib('log') or has_shlib('log_setup'): self.env['DEFINES_%s' % var] += ['BOOST_LOG_DYN_LINK'] if has_lib('log_setup'): self.check_cxx(fragment=BOOST_LOG_SETUP_CODE, use=var, execute=False) else: self.check_cxx(fragment=BOOST_LOG_CODE, use=var, execute=False) if params.get('linkage_autodetect', False): self.start_msg('Attempting to detect boost linkage flags') toolset = self.boost_get_toolset(kw.get('toolset', '')) if toolset in ('vc',): # disable auto-linking feature, causing error LNK1181 # because the code wants to be linked against self.env['DEFINES_%s' % var] += ['BOOST_ALL_NO_LIB'] # if no dlls are present, we guess the .lib files are not stubs has_dlls = False for x in Utils.listdir(path): if x.endswith(self.env.cxxshlib_PATTERN % ''): has_dlls = True break if not has_dlls: self.env['STLIBPATH_%s' % var] = [path] self.env['STLIB_%s' % var] = libs del self.env['LIB_%s' % var] del self.env['LIBPATH_%s' % var] # we attempt to play with some known-to-work CXXFLAGS combinations for cxxflags in (['/MD', '/EHsc'], []): self.env.stash() self.env['CXXFLAGS_%s' % var] += cxxflags try: try_link() self.end_msg('ok: winning cxxflags combination: %s' % (self.env['CXXFLAGS_%s' % var])) exc = None break except Errors.ConfigurationError as e: self.env.revert() exc = e if exc is not None: self.end_msg('Could not auto-detect boost linking flags combination, you may report it to boost.py author', ex=exc) self.fatal('The configuration failed') else: self.end_msg('Boost linkage flags auto-detection not implemented (needed ?) for this toolchain') self.fatal('The configuration failed') else: self.start_msg('Checking for boost linkage') try: try_link() except Errors.ConfigurationError as e: self.end_msg('Could not link against boost libraries using supplied options', 'YELLOW') self.fatal('The configuration failed') self.end_msg('ok')
[ "def", "check_boost", "(", "self", ",", "*", "k", ",", "*", "*", "kw", ")", ":", "if", "not", "self", ".", "env", "[", "'CXX'", "]", ":", "self", ".", "fatal", "(", "'load a c++ compiler first, conf.load(\"compiler_cxx\")'", ")", "params", "=", "{", "'li...
https://github.com/named-data/NFD/blob/b98aa3aca6b583ef34df7ee2f317321358f42dd0/.waf-tools/boost.py#L389-L517
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/pyparsing.py
python
ParserElement.__call__
(self, name=None)
Shortcut for :class:`setResultsName`, with ``listAllMatches=False``. If ``name`` is given with a trailing ``'*'`` character, then ``listAllMatches`` will be passed as ``True``. If ``name` is omitted, same as calling :class:`copy`. Example:: # these are equivalent userdata = Word(alphas).setResultsName("name") + Word(nums + "-").setResultsName("socsecno") userdata = Word(alphas)("name") + Word(nums + "-")("socsecno")
[]
def __call__(self, name=None): """ Shortcut for :class:`setResultsName`, with ``listAllMatches=False``. If ``name`` is given with a trailing ``'*'`` character, then ``listAllMatches`` will be passed as ``True``. If ``name` is omitted, same as calling :class:`copy`. Example:: # these are equivalent userdata = Word(alphas).setResultsName("name") + Word(nums + "-").setResultsName("socsecno") userdata = Word(alphas)("name") + Word(nums + "-")("socsecno") """ if name is not None: return self._setResultsName(name) else: return self.copy()
[ "def", "__call__", "(", "self", ",", "name", "=", "None", ")", ":", "if", "name", "is", "not", "None", ":", "return", "self", ".", "_setResultsName", "(", "name", ")", "else", ":", "return", "self", ".", "copy", "(", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/pyparsing.py#L4827-L4863
google/fhir
d77f57706c1a168529b0b87ca7ccb1c0113e83c2
py/google/fhir/_primitive_time_utils.py
python
timezone_info_for_timezone
(tzstr: str)
Returns a datetime.tzinfo subclass for a timezone string.
Returns a datetime.tzinfo subclass for a timezone string.
[ "Returns", "a", "datetime", ".", "tzinfo", "subclass", "for", "a", "timezone", "string", "." ]
def timezone_info_for_timezone(tzstr: str) -> datetime.tzinfo: """Returns a datetime.tzinfo subclass for a timezone string.""" offset_err = None tzname_err = None try: isoparser = parser.isoparser() return isoparser.parse_tzstr(tzstr) except ValueError as e: offset_err = e # Fall through try: return cast(datetime.tzinfo, zoneinfo.ZoneInfo(tzstr)) except ValueError as e: tzname_err = e # Fall through raise ValueError( f'Cannot serialize timezone: {tzstr!r} ({offset_err!r}, {tzname_err!r}).')
[ "def", "timezone_info_for_timezone", "(", "tzstr", ":", "str", ")", "->", "datetime", ".", "tzinfo", ":", "offset_err", "=", "None", "tzname_err", "=", "None", "try", ":", "isoparser", "=", "parser", ".", "isoparser", "(", ")", "return", "isoparser", ".", ...
https://github.com/google/fhir/blob/d77f57706c1a168529b0b87ca7ccb1c0113e83c2/py/google/fhir/_primitive_time_utils.py#L163-L180
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
third_party/pymock/mock.py
python
_patch.start
(self)
return result
Activate a patch, returning any created mock.
Activate a patch, returning any created mock.
[ "Activate", "a", "patch", "returning", "any", "created", "mock", "." ]
def start(self): """Activate a patch, returning any created mock.""" result = self.__enter__() self._active_patches.add(self) return result
[ "def", "start", "(", "self", ")", ":", "result", "=", "self", ".", "__enter__", "(", ")", "self", ".", "_active_patches", ".", "add", "(", "self", ")", "return", "result" ]
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/third_party/pymock/mock.py#L1394-L1398
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_core.py
python
Window.AcceptsFocusFromKeyboard
(*args, **kwargs)
return _core_.Window_AcceptsFocusFromKeyboard(*args, **kwargs)
AcceptsFocusFromKeyboard(self) -> bool Can this window be given focus by keyboard navigation? if not, the only way to give it focus (provided it accepts it at all) is to click it.
AcceptsFocusFromKeyboard(self) -> bool
[ "AcceptsFocusFromKeyboard", "(", "self", ")", "-", ">", "bool" ]
def AcceptsFocusFromKeyboard(*args, **kwargs): """ AcceptsFocusFromKeyboard(self) -> bool Can this window be given focus by keyboard navigation? if not, the only way to give it focus (provided it accepts it at all) is to click it. """ return _core_.Window_AcceptsFocusFromKeyboard(*args, **kwargs)
[ "def", "AcceptsFocusFromKeyboard", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "Window_AcceptsFocusFromKeyboard", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_core.py#L10174-L10182
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
catboost/benchmarks/training_speed/data_loader.py
python
higgs
(dataset_dir)
return X, y
Higgs dataset from UCI machine learning repository ( https://archive.ics.uci.edu/ml/datasets/HIGGS). TaskType:binclass NumberOfFeatures:28 NumberOfInstances:11M
Higgs dataset from UCI machine learning repository ( https://archive.ics.uci.edu/ml/datasets/HIGGS).
[ "Higgs", "dataset", "from", "UCI", "machine", "learning", "repository", "(", "https", ":", "//", "archive", ".", "ics", ".", "uci", ".", "edu", "/", "ml", "/", "datasets", "/", "HIGGS", ")", "." ]
def higgs(dataset_dir): """ Higgs dataset from UCI machine learning repository ( https://archive.ics.uci.edu/ml/datasets/HIGGS). TaskType:binclass NumberOfFeatures:28 NumberOfInstances:11M """ url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/00280/HIGGS.csv.gz' filename = os.path.join(dataset_dir, 'HIGGS.csv.gz') if not os.path.exists(filename): urlretrieve(url, filename) df = pd.read_csv(filename) X = df.iloc[:, 1:].values y = df.iloc[:, 0].values return X, y
[ "def", "higgs", "(", "dataset_dir", ")", ":", "url", "=", "'https://archive.ics.uci.edu/ml/machine-learning-databases/00280/HIGGS.csv.gz'", "filename", "=", "os", ".", "path", ".", "join", "(", "dataset_dir", ",", "'HIGGS.csv.gz'", ")", "if", "not", "os", ".", "path...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/catboost/benchmarks/training_speed/data_loader.py#L394-L412
HackWebRTC/webrtc
7abfc990c00ab35090fff285fcf635d1d7892433
PRESUBMIT.py
python
CheckNoMixingSources
(input_api, gn_files, output_api)
return []
Disallow mixing C, C++ and Obj-C/Obj-C++ in the same target. See bugs.webrtc.org/7743 for more context.
Disallow mixing C, C++ and Obj-C/Obj-C++ in the same target.
[ "Disallow", "mixing", "C", "C", "++", "and", "Obj", "-", "C", "/", "Obj", "-", "C", "++", "in", "the", "same", "target", "." ]
def CheckNoMixingSources(input_api, gn_files, output_api): """Disallow mixing C, C++ and Obj-C/Obj-C++ in the same target. See bugs.webrtc.org/7743 for more context. """ def _MoreThanOneSourceUsed(*sources_lists): sources_used = 0 for source_list in sources_lists: if len(source_list): sources_used += 1 return sources_used > 1 errors = defaultdict(lambda: []) for gn_file in gn_files: gn_file_content = input_api.ReadFile(gn_file) for target_match in TARGET_RE.finditer(gn_file_content): # list_of_sources is a list of tuples of the form # (c_files, cc_files, objc_files) that keeps track of all the sources # defined in a target. A GN target can have more that on definition of # sources (since it supports if/else statements). # E.g.: # rtc_static_library("foo") { # if (is_win) { # sources = [ "foo.cc" ] # } else { # sources = [ "foo.mm" ] # } # } # This is allowed and the presubmit check should support this case. list_of_sources = [] c_files = [] cc_files = [] objc_files = [] target_name = target_match.group('target_name') target_contents = target_match.group('target_contents') for sources_match in SOURCES_RE.finditer(target_contents): if '+=' not in sources_match.group(0): if c_files or cc_files or objc_files: list_of_sources.append((c_files, cc_files, objc_files)) c_files = [] cc_files = [] objc_files = [] for file_match in FILE_PATH_RE.finditer(sources_match.group(1)): file_path = file_match.group('file_path') extension = file_match.group('extension') if extension == '.c': c_files.append(file_path + extension) if extension == '.cc': cc_files.append(file_path + extension) if extension in ['.m', '.mm']: objc_files.append(file_path + extension) list_of_sources.append((c_files, cc_files, objc_files)) for c_files_list, cc_files_list, objc_files_list in list_of_sources: if _MoreThanOneSourceUsed(c_files_list, cc_files_list, objc_files_list): all_sources = sorted(c_files_list + cc_files_list + objc_files_list) errors[gn_file.LocalPath()].append((target_name, all_sources)) if errors: return [output_api.PresubmitError( 'GN targets cannot mix .c, .cc and .m (or .mm) source files.\n' 'Please create a separate target for each collection of sources.\n' 'Mixed sources: \n' '%s\n' 'Violating GN files:\n%s\n' % (json.dumps(errors, indent=2), '\n'.join(errors.keys())))] return []
[ "def", "CheckNoMixingSources", "(", "input_api", ",", "gn_files", ",", "output_api", ")", ":", "def", "_MoreThanOneSourceUsed", "(", "*", "sources_lists", ")", ":", "sources_used", "=", "0", "for", "source_list", "in", "sources_lists", ":", "if", "len", "(", "...
https://github.com/HackWebRTC/webrtc/blob/7abfc990c00ab35090fff285fcf635d1d7892433/PRESUBMIT.py#L341-L406
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/keras/saving/saved_model_experimental.py
python
_get_variables_dir
(export_dir)
return os.path.join( compat.as_text(export_dir), compat.as_text(constants.VARIABLES_DIRECTORY))
Return variables sub-directory in the SavedModel.
Return variables sub-directory in the SavedModel.
[ "Return", "variables", "sub", "-", "directory", "in", "the", "SavedModel", "." ]
def _get_variables_dir(export_dir): """Return variables sub-directory in the SavedModel.""" return os.path.join( compat.as_text(export_dir), compat.as_text(constants.VARIABLES_DIRECTORY))
[ "def", "_get_variables_dir", "(", "export_dir", ")", ":", "return", "os", ".", "path", ".", "join", "(", "compat", ".", "as_text", "(", "export_dir", ")", ",", "compat", ".", "as_text", "(", "constants", ".", "VARIABLES_DIRECTORY", ")", ")" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/keras/saving/saved_model_experimental.py#L443-L447
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/tracemalloc.py
python
Snapshot.dump
(self, filename)
Write the snapshot into a file.
Write the snapshot into a file.
[ "Write", "the", "snapshot", "into", "a", "file", "." ]
def dump(self, filename): """ Write the snapshot into a file. """ with open(filename, "wb") as fp: pickle.dump(self, fp, pickle.HIGHEST_PROTOCOL)
[ "def", "dump", "(", "self", ",", "filename", ")", ":", "with", "open", "(", "filename", ",", "\"wb\"", ")", "as", "fp", ":", "pickle", ".", "dump", "(", "self", ",", "fp", ",", "pickle", ".", "HIGHEST_PROTOCOL", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/tracemalloc.py#L400-L405
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/importlib/resources.py
python
_normalize_path
(path)
Normalize a path by ensuring it is a string. If the resulting string contains path separators, an exception is raised.
Normalize a path by ensuring it is a string.
[ "Normalize", "a", "path", "by", "ensuring", "it", "is", "a", "string", "." ]
def _normalize_path(path) -> str: """Normalize a path by ensuring it is a string. If the resulting string contains path separators, an exception is raised. """ parent, file_name = os.path.split(path) if parent: raise ValueError('{!r} must be only a file name'.format(path)) else: return file_name
[ "def", "_normalize_path", "(", "path", ")", "->", "str", ":", "parent", ",", "file_name", "=", "os", ".", "path", ".", "split", "(", "path", ")", "if", "parent", ":", "raise", "ValueError", "(", "'{!r} must be only a file name'", ".", "format", "(", "path"...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/importlib/resources.py#L54-L63
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/tkinter/ttk.py
python
Style.element_options
(self, elementname)
return tuple(o.lstrip('-') for o in self.tk.splitlist( self.tk.call(self._name, "element", "options", elementname)))
Return the list of elementname's options.
Return the list of elementname's options.
[ "Return", "the", "list", "of", "elementname", "s", "options", "." ]
def element_options(self, elementname): """Return the list of elementname's options.""" return tuple(o.lstrip('-') for o in self.tk.splitlist( self.tk.call(self._name, "element", "options", elementname)))
[ "def", "element_options", "(", "self", ",", "elementname", ")", ":", "return", "tuple", "(", "o", ".", "lstrip", "(", "'-'", ")", "for", "o", "in", "self", ".", "tk", ".", "splitlist", "(", "self", ".", "tk", ".", "call", "(", "self", ".", "_name",...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/tkinter/ttk.py#L477-L480
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_internal/req/req_file.py
python
build_parser
()
return parser
Return a parser for parsing requirement lines
Return a parser for parsing requirement lines
[ "Return", "a", "parser", "for", "parsing", "requirement", "lines" ]
def build_parser(): # type: () -> optparse.OptionParser """ Return a parser for parsing requirement lines """ parser = optparse.OptionParser(add_help_option=False) option_factories = SUPPORTED_OPTIONS + SUPPORTED_OPTIONS_REQ for option_factory in option_factories: option = option_factory() parser.add_option(option) # By default optparse sys.exits on parsing errors. We want to wrap # that in our own exception. def parser_exit(self, msg): # type: (Any, str) -> NoReturn raise OptionParsingError(msg) # NOTE: mypy disallows assigning to a method # https://github.com/python/mypy/issues/2427 parser.exit = parser_exit # type: ignore return parser
[ "def", "build_parser", "(", ")", ":", "# type: () -> optparse.OptionParser", "parser", "=", "optparse", ".", "OptionParser", "(", "add_help_option", "=", "False", ")", "option_factories", "=", "SUPPORTED_OPTIONS", "+", "SUPPORTED_OPTIONS_REQ", "for", "option_factory", "...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_internal/req/req_file.py#L437-L458
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_windows.py
python
ScrolledWindow.Create
(*args, **kwargs)
return _windows_.ScrolledWindow_Create(*args, **kwargs)
Create(self, Window parent, int id=-1, Point pos=DefaultPosition, Size size=DefaultSize, long style=wxHSCROLL|wxVSCROLL, String name=PanelNameStr) -> bool Create the GUI part of the Window for 2-phase creation mode.
Create(self, Window parent, int id=-1, Point pos=DefaultPosition, Size size=DefaultSize, long style=wxHSCROLL|wxVSCROLL, String name=PanelNameStr) -> bool
[ "Create", "(", "self", "Window", "parent", "int", "id", "=", "-", "1", "Point", "pos", "=", "DefaultPosition", "Size", "size", "=", "DefaultSize", "long", "style", "=", "wxHSCROLL|wxVSCROLL", "String", "name", "=", "PanelNameStr", ")", "-", ">", "bool" ]
def Create(*args, **kwargs): """ Create(self, Window parent, int id=-1, Point pos=DefaultPosition, Size size=DefaultSize, long style=wxHSCROLL|wxVSCROLL, String name=PanelNameStr) -> bool Create the GUI part of the Window for 2-phase creation mode. """ return _windows_.ScrolledWindow_Create(*args, **kwargs)
[ "def", "Create", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_windows_", ".", "ScrolledWindow_Create", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_windows.py#L299-L307
apache/singa
93fd9da72694e68bfe3fb29d0183a65263d238a1
python/singa/tensor.py
python
sum
(t, axis=None, out=None)
Sum of tensor elements over given axis Args: t: Singa.tensor The array_like tensor to be sumed axis: None or int or tuple of ints, optional Axis or axes along which a sum is performed. The default, axis=None, will sum all of the elements of the input array. If axis is negative it counts from the last to the first axis. If axis is a tuple of ints, a sum is performed on all of the axes specified in the tuple instead of a single axis or all the axes as before. out:Singa.tensor optional Alternative output array in which to place the result. It must have the same shape as the expected output, but the type of the output values will be cast if necessary. Returns: A tensor with the same shape as t, with the specified axis removed. If a is a 0-d array, or if axis is None, a scalar is returned. If an output array is specified, a reference to out is returned
Sum of tensor elements over given axis
[ "Sum", "of", "tensor", "elements", "over", "given", "axis" ]
def sum(t, axis=None, out=None): '''Sum of tensor elements over given axis Args: t: Singa.tensor The array_like tensor to be sumed axis: None or int or tuple of ints, optional Axis or axes along which a sum is performed. The default, axis=None, will sum all of the elements of the input array. If axis is negative it counts from the last to the first axis. If axis is a tuple of ints, a sum is performed on all of the axes specified in the tuple instead of a single axis or all the axes as before. out:Singa.tensor optional Alternative output array in which to place the result. It must have the same shape as the expected output, but the type of the output values will be cast if necessary. Returns: A tensor with the same shape as t, with the specified axis removed. If a is a 0-d array, or if axis is None, a scalar is returned. If an output array is specified, a reference to out is returned ''' t_shape = t.shape t_ndim = t.ndim() if axis is None: one = Tensor(t.shape, t.device) one.set_value(1.0) ret = tensordot(t, one, t_ndim) if isinstance(axis, int): if axis < 0: axis += t_ndim axis_shape = t_shape[axis] axis_shape = int(axis_shape) one = Tensor(shape=(axis_shape,), device=t.device) one.set_value(1.0) ret = tensordot(t, one, axes=([axis], [0])) if isinstance(axis, tuple): l_axis = list(axis) axis_shape = [t_shape[x] for x in axis] axisshape = tuple(axis_shape) one = Tensor(axisshape, t.device) one.set_value(1.0) one_axis = [x for x in range(one.ndim())] ret = tensordot(t, one, (l_axis, one_axis)) if out is not None: if out.shape != ret.shape: raise ValueError('dimensions do not match') out[:] = ret return out else: return ret
[ "def", "sum", "(", "t", ",", "axis", "=", "None", ",", "out", "=", "None", ")", ":", "t_shape", "=", "t", ".", "shape", "t_ndim", "=", "t", ".", "ndim", "(", ")", "if", "axis", "is", "None", ":", "one", "=", "Tensor", "(", "t", ".", "shape", ...
https://github.com/apache/singa/blob/93fd9da72694e68bfe3fb29d0183a65263d238a1/python/singa/tensor.py#L1044-L1100
microsoft/TSS.MSR
0f2516fca2cd9929c31d5450e39301c9bde43688
TSS.Py/src/TpmTypes.py
python
RewrapResponse.fromBytes
(buffer)
return TpmBuffer(buffer).createObj(RewrapResponse)
Returns new RewrapResponse object constructed from its marshaled representation in the given byte buffer
Returns new RewrapResponse object constructed from its marshaled representation in the given byte buffer
[ "Returns", "new", "RewrapResponse", "object", "constructed", "from", "its", "marshaled", "representation", "in", "the", "given", "byte", "buffer" ]
def fromBytes(buffer): """ Returns new RewrapResponse object constructed from its marshaled representation in the given byte buffer """ return TpmBuffer(buffer).createObj(RewrapResponse)
[ "def", "fromBytes", "(", "buffer", ")", ":", "return", "TpmBuffer", "(", "buffer", ")", ".", "createObj", "(", "RewrapResponse", ")" ]
https://github.com/microsoft/TSS.MSR/blob/0f2516fca2cd9929c31d5450e39301c9bde43688/TSS.Py/src/TpmTypes.py#L10480-L10484
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/distlib/_backport/tarfile.py
python
TarFile.gzopen
(cls, name, mode="r", fileobj=None, compresslevel=9, **kwargs)
return t
Open gzip compressed tar archive name for reading or writing. Appending is not allowed.
Open gzip compressed tar archive name for reading or writing. Appending is not allowed.
[ "Open", "gzip", "compressed", "tar", "archive", "name", "for", "reading", "or", "writing", ".", "Appending", "is", "not", "allowed", "." ]
def gzopen(cls, name, mode="r", fileobj=None, compresslevel=9, **kwargs): """Open gzip compressed tar archive name for reading or writing. Appending is not allowed. """ if len(mode) > 1 or mode not in "rw": raise ValueError("mode must be 'r' or 'w'") try: import gzip gzip.GzipFile except (ImportError, AttributeError): raise CompressionError("gzip module is not available") extfileobj = fileobj is not None try: fileobj = gzip.GzipFile(name, mode + "b", compresslevel, fileobj) t = cls.taropen(name, mode, fileobj, **kwargs) except IOError: if not extfileobj and fileobj is not None: fileobj.close() if fileobj is None: raise raise ReadError("not a gzip file") except: if not extfileobj and fileobj is not None: fileobj.close() raise t._extfileobj = extfileobj return t
[ "def", "gzopen", "(", "cls", ",", "name", ",", "mode", "=", "\"r\"", ",", "fileobj", "=", "None", ",", "compresslevel", "=", "9", ",", "*", "*", "kwargs", ")", ":", "if", "len", "(", "mode", ")", ">", "1", "or", "mode", "not", "in", "\"rw\"", "...
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/_backport/tarfile.py#L1798-L1826