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
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/AWSPythonSDK/1.5.8/docutils/parsers/rst/states.py
python
RSTState.nested_list_parse
(self, block, input_offset, node, initial_state, blank_finish, blank_finish_state=None, extra_settings={}, match_titles=False, state_machine_class=None, state_machine_kwargs=None)
return state_machine.abs_line_offset(), blank_finish
Create a new StateMachine rooted at `node` and run it over the input `block`. Also keep track of optional intermediate blank lines and the required final one.
Create a new StateMachine rooted at `node` and run it over the input `block`. Also keep track of optional intermediate blank lines and the required final one.
[ "Create", "a", "new", "StateMachine", "rooted", "at", "node", "and", "run", "it", "over", "the", "input", "block", ".", "Also", "keep", "track", "of", "optional", "intermediate", "blank", "lines", "and", "the", "required", "final", "one", "." ]
def nested_list_parse(self, block, input_offset, node, initial_state, blank_finish, blank_finish_state=None, extra_settings={}, match_titles=False, state_machine_class=None, state_machine_kwargs=None): """ Create a new StateMachine rooted at `node` and run it over the input `block`. Also keep track of optional intermediate blank lines and the required final one. """ if state_machine_class is None: state_machine_class = self.nested_sm if state_machine_kwargs is None: state_machine_kwargs = self.nested_sm_kwargs.copy() state_machine_kwargs['initial_state'] = initial_state state_machine = state_machine_class(debug=self.debug, **state_machine_kwargs) if blank_finish_state is None: blank_finish_state = initial_state state_machine.states[blank_finish_state].blank_finish = blank_finish for key, value in extra_settings.items(): setattr(state_machine.states[initial_state], key, value) state_machine.run(block, input_offset, memo=self.memo, node=node, match_titles=match_titles) blank_finish = state_machine.states[blank_finish_state].blank_finish state_machine.unlink() return state_machine.abs_line_offset(), blank_finish
[ "def", "nested_list_parse", "(", "self", ",", "block", ",", "input_offset", ",", "node", ",", "initial_state", ",", "blank_finish", ",", "blank_finish_state", "=", "None", ",", "extra_settings", "=", "{", "}", ",", "match_titles", "=", "False", ",", "state_mac...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/AWSPythonSDK/1.5.8/docutils/parsers/rst/states.py#L294-L322
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
tools/gen_keyboard_overlay_data/gen_keyboard_overlay_data.py
python
FetchSpreadsheetFeeds
(client, key, sheets, cols)
return worksheets_data
Fetch feeds from the spreadsheet. Args: client: A spreadsheet client to be used for fetching data. key: A key string of the spreadsheet to be fetched. sheets: A list of the sheet names to read data from. cols: A list of columns to read data from.
Fetch feeds from the spreadsheet.
[ "Fetch", "feeds", "from", "the", "spreadsheet", "." ]
def FetchSpreadsheetFeeds(client, key, sheets, cols): """Fetch feeds from the spreadsheet. Args: client: A spreadsheet client to be used for fetching data. key: A key string of the spreadsheet to be fetched. sheets: A list of the sheet names to read data from. cols: A list of columns to read data from. """ worksheets_feed = client.GetWorksheetsFeed(key) print 'Fetching data from the worksheet: %s' % worksheets_feed.title.text worksheets_data = {} titles = [] for entry in worksheets_feed.entry: worksheet_id = entry.id.text.split('/')[-1] list_feed = client.GetListFeed(key, worksheet_id) list_data = [] # Hack to deal with sheet names like 'sv (Copy of fl)' title = list_feed.title.text.split('(')[0].strip() titles.append(title) if title not in sheets: continue print 'Reading data from the sheet: %s' % list_feed.title.text for i, entry in enumerate(list_feed.entry): line_data = {} for k in entry.custom: if (k not in cols) or (not entry.custom[k].text): continue line_data[k] = entry.custom[k].text list_data.append(line_data) worksheets_data[title] = list_data PrintDiffs('Exist only on the spreadsheet: ', titles, sheets) PrintDiffs('Specified but do not exist on the spreadsheet: ', sheets, titles) return worksheets_data
[ "def", "FetchSpreadsheetFeeds", "(", "client", ",", "key", ",", "sheets", ",", "cols", ")", ":", "worksheets_feed", "=", "client", ".", "GetWorksheetsFeed", "(", "key", ")", "print", "'Fetching data from the worksheet: %s'", "%", "worksheets_feed", ".", "title", "...
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/tools/gen_keyboard_overlay_data/gen_keyboard_overlay_data.py#L301-L334
BlazingDB/blazingsql
a35643d4c983334757eee96d5b9005b8b9fbd21b
pyblazing/pyblazing/apiv2/context.py
python
BlazingContext.s3
(self, prefix, **kwargs)
return self.fs.s3(self.dask_client, prefix, **kwargs)
Register an AWS S3 bucket. returns a boolean meaning True when Registered Successfully Parameters ---------- name : string that represents the name with which you will refer to your S3 bucket. bucket_name : string name of your S3 bucket. access_key_id : string of your AWS IAM access key. not required for public buckets. secret_key : string of your AWS IAM secret key. not required for public buckets. encryption_type (optional) : None (default), 'AES_256', or 'AWS_KMS'. session_token (optional) : string of your AWS IAM session token. root (optional) : string path of your bucket that will be used as a shortcut path. kms_key_amazon_resource (optional) : string value, required for KMS encryption only. Examples -------- Register and create table from a public S3 bucket: >>> bc.s3('blazingsql-colab', bucket_name='blazingsql-colab') >>> bc.create_table('taxi', >>> 's3://blazingsql-colab/yellow_taxi/1_0_0.parquet') <pyblazing.apiv2.context.BlazingTable at 0x7f6d4e640c90> Register and create table from a private S3 bucket: >>> bc.s3('other-data', bucket_name='kws-parquet-data', >>> access_key_id='AKIASPFMPQMQD2OG54IQ', >>> secret_key='bmt+TLTosdkIelsdw9VQjMe0nBnvAA5nPt0kaSx/Y', >>> encryption_type=S3EncryptionType.AWS_KMS, >>> kms_key_amazon_resource_name= >>> 'arn:aws:kms:region:acct-id:key/key-id') >>> bc.create_table('taxi', 's3://other-data/yellow_taxi/1_0_0.parquet') <pyblazing.apiv2.context.BlazingTable at 0x7f12327c0310> Docs: https://docs.blazingdb.com/docs/s3
Register an AWS S3 bucket. returns a boolean meaning True when Registered Successfully
[ "Register", "an", "AWS", "S3", "bucket", ".", "returns", "a", "boolean", "meaning", "True", "when", "Registered", "Successfully" ]
def s3(self, prefix, **kwargs): """ Register an AWS S3 bucket. returns a boolean meaning True when Registered Successfully Parameters ---------- name : string that represents the name with which you will refer to your S3 bucket. bucket_name : string name of your S3 bucket. access_key_id : string of your AWS IAM access key. not required for public buckets. secret_key : string of your AWS IAM secret key. not required for public buckets. encryption_type (optional) : None (default), 'AES_256', or 'AWS_KMS'. session_token (optional) : string of your AWS IAM session token. root (optional) : string path of your bucket that will be used as a shortcut path. kms_key_amazon_resource (optional) : string value, required for KMS encryption only. Examples -------- Register and create table from a public S3 bucket: >>> bc.s3('blazingsql-colab', bucket_name='blazingsql-colab') >>> bc.create_table('taxi', >>> 's3://blazingsql-colab/yellow_taxi/1_0_0.parquet') <pyblazing.apiv2.context.BlazingTable at 0x7f6d4e640c90> Register and create table from a private S3 bucket: >>> bc.s3('other-data', bucket_name='kws-parquet-data', >>> access_key_id='AKIASPFMPQMQD2OG54IQ', >>> secret_key='bmt+TLTosdkIelsdw9VQjMe0nBnvAA5nPt0kaSx/Y', >>> encryption_type=S3EncryptionType.AWS_KMS, >>> kms_key_amazon_resource_name= >>> 'arn:aws:kms:region:acct-id:key/key-id') >>> bc.create_table('taxi', 's3://other-data/yellow_taxi/1_0_0.parquet') <pyblazing.apiv2.context.BlazingTable at 0x7f12327c0310> Docs: https://docs.blazingdb.com/docs/s3 """ kwargs_validation(kwargs, "s3") return self.fs.s3(self.dask_client, prefix, **kwargs)
[ "def", "s3", "(", "self", ",", "prefix", ",", "*", "*", "kwargs", ")", ":", "kwargs_validation", "(", "kwargs", ",", "\"s3\"", ")", "return", "self", ".", "fs", ".", "s3", "(", "self", ".", "dask_client", ",", "prefix", ",", "*", "*", "kwargs", ")"...
https://github.com/BlazingDB/blazingsql/blob/a35643d4c983334757eee96d5b9005b8b9fbd21b/pyblazing/pyblazing/apiv2/context.py#L1744-L1792
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/media.py
python
MediaCtrl.LoadURI
(*args, **kwargs)
return _media.MediaCtrl_LoadURI(*args, **kwargs)
LoadURI(self, String fileName) -> bool
LoadURI(self, String fileName) -> bool
[ "LoadURI", "(", "self", "String", "fileName", ")", "-", ">", "bool" ]
def LoadURI(*args, **kwargs): """LoadURI(self, String fileName) -> bool""" return _media.MediaCtrl_LoadURI(*args, **kwargs)
[ "def", "LoadURI", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_media", ".", "MediaCtrl_LoadURI", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/media.py#L161-L163
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/AWSPythonSDK/1.5.8/botocore/paginate.py
python
TokenEncoder._encode_bytes
(self, data, path)
return base64.b64encode(data).decode('utf-8'), [path]
Base64 encode a byte string.
Base64 encode a byte string.
[ "Base64", "encode", "a", "byte", "string", "." ]
def _encode_bytes(self, data, path): """Base64 encode a byte string.""" return base64.b64encode(data).decode('utf-8'), [path]
[ "def", "_encode_bytes", "(", "self", ",", "data", ",", "path", ")", ":", "return", "base64", ".", "b64encode", "(", "data", ")", ".", "decode", "(", "'utf-8'", ")", ",", "[", "path", "]" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/AWSPythonSDK/1.5.8/botocore/paginate.py#L103-L105
klzgrad/naiveproxy
ed2c513637c77b18721fe428d7ed395b4d284c83
src/build/android/gyp/util/md5_check.py
python
_Metadata.GetTag
(self, path, subpath=None)
return ret and ret['tag']
Returns the tag for the given path / subpath.
Returns the tag for the given path / subpath.
[ "Returns", "the", "tag", "for", "the", "given", "path", "/", "subpath", "." ]
def GetTag(self, path, subpath=None): """Returns the tag for the given path / subpath.""" ret = self._GetEntry(path, subpath) return ret and ret['tag']
[ "def", "GetTag", "(", "self", ",", "path", ",", "subpath", "=", "None", ")", ":", "ret", "=", "self", ".", "_GetEntry", "(", "path", ",", "subpath", ")", "return", "ret", "and", "ret", "[", "'tag'", "]" ]
https://github.com/klzgrad/naiveproxy/blob/ed2c513637c77b18721fe428d7ed395b4d284c83/src/build/android/gyp/util/md5_check.py#L420-L423
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
scripts/Inelastic/Direct/RunDescriptor.py
python
build_run_file_name
(run_num,inst,file_path='',fext='')
return fname
Build the full name of a runfile from all possible components
Build the full name of a runfile from all possible components
[ "Build", "the", "full", "name", "of", "a", "runfile", "from", "all", "possible", "components" ]
def build_run_file_name(run_num,inst,file_path='',fext=''): """Build the full name of a runfile from all possible components""" if fext is None: fext = '' if isinstance(run_num, str): run_num_str = run_num else: #pylint: disable=protected-access fac = RunDescriptor._holder.facility zero_padding = fac.instrument(inst).zeroPadding(run_num) run_num_str = str(run_num).zfill(zero_padding) fname = '{0}{1}{2}'.format(inst,run_num_str,fext) if file_path is not None: if os.path.exists(file_path): fname = os.path.join(file_path,fname) return fname
[ "def", "build_run_file_name", "(", "run_num", ",", "inst", ",", "file_path", "=", "''", ",", "fext", "=", "''", ")", ":", "if", "fext", "is", "None", ":", "fext", "=", "''", "if", "isinstance", "(", "run_num", ",", "str", ")", ":", "run_num_str", "="...
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/scripts/Inelastic/Direct/RunDescriptor.py#L1821-L1837
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/python/ops/rnn.py
python
static_bidirectional_rnn
(cell_fw, cell_bw, inputs, initial_state_fw=None, initial_state_bw=None, dtype=None, sequence_length=None, scope=None)
return (outputs, output_state_fw, output_state_bw)
Creates a bidirectional recurrent neural network. Similar to the unidirectional case above (rnn) but takes input and builds independent forward and backward RNNs with the final forward and backward outputs depth-concatenated, such that the output will have the format [time][batch][cell_fw.output_size + cell_bw.output_size]. The input_size of forward and backward cell must match. The initial state for both directions is zero by default (but can be set optionally) and no intermediate states are ever returned -- the network is fully unrolled for the given (passed in) length(s) of the sequence(s) or completely unrolled if length(s) is not given. Args: cell_fw: An instance of RNNCell, to be used for forward direction. cell_bw: An instance of RNNCell, to be used for backward direction. inputs: A length T list of inputs, each a tensor of shape [batch_size, input_size], or a nested tuple of such elements. initial_state_fw: (optional) An initial state for the forward RNN. This must be a tensor of appropriate type and shape `[batch_size, cell_fw.state_size]`. If `cell_fw.state_size` is a tuple, this should be a tuple of tensors having shapes `[batch_size, s] for s in cell_fw.state_size`. initial_state_bw: (optional) Same as for `initial_state_fw`, but using the corresponding properties of `cell_bw`. dtype: (optional) The data type for the initial state. Required if either of the initial states are not provided. sequence_length: (optional) An int32/int64 vector, size `[batch_size]`, containing the actual lengths for each of the sequences. scope: VariableScope for the created subgraph; defaults to "bidirectional_rnn" Returns: A tuple (outputs, output_state_fw, output_state_bw) where: outputs is a length `T` list of outputs (one for each input), which are depth-concatenated forward and backward outputs. output_state_fw is the final state of the forward rnn. output_state_bw is the final state of the backward rnn. Raises: TypeError: If `cell_fw` or `cell_bw` is not an instance of `RNNCell`. ValueError: If inputs is None or an empty list.
Creates a bidirectional recurrent neural network.
[ "Creates", "a", "bidirectional", "recurrent", "neural", "network", "." ]
def static_bidirectional_rnn(cell_fw, cell_bw, inputs, initial_state_fw=None, initial_state_bw=None, dtype=None, sequence_length=None, scope=None): """Creates a bidirectional recurrent neural network. Similar to the unidirectional case above (rnn) but takes input and builds independent forward and backward RNNs with the final forward and backward outputs depth-concatenated, such that the output will have the format [time][batch][cell_fw.output_size + cell_bw.output_size]. The input_size of forward and backward cell must match. The initial state for both directions is zero by default (but can be set optionally) and no intermediate states are ever returned -- the network is fully unrolled for the given (passed in) length(s) of the sequence(s) or completely unrolled if length(s) is not given. Args: cell_fw: An instance of RNNCell, to be used for forward direction. cell_bw: An instance of RNNCell, to be used for backward direction. inputs: A length T list of inputs, each a tensor of shape [batch_size, input_size], or a nested tuple of such elements. initial_state_fw: (optional) An initial state for the forward RNN. This must be a tensor of appropriate type and shape `[batch_size, cell_fw.state_size]`. If `cell_fw.state_size` is a tuple, this should be a tuple of tensors having shapes `[batch_size, s] for s in cell_fw.state_size`. initial_state_bw: (optional) Same as for `initial_state_fw`, but using the corresponding properties of `cell_bw`. dtype: (optional) The data type for the initial state. Required if either of the initial states are not provided. sequence_length: (optional) An int32/int64 vector, size `[batch_size]`, containing the actual lengths for each of the sequences. scope: VariableScope for the created subgraph; defaults to "bidirectional_rnn" Returns: A tuple (outputs, output_state_fw, output_state_bw) where: outputs is a length `T` list of outputs (one for each input), which are depth-concatenated forward and backward outputs. output_state_fw is the final state of the forward rnn. output_state_bw is the final state of the backward rnn. Raises: TypeError: If `cell_fw` or `cell_bw` is not an instance of `RNNCell`. ValueError: If inputs is None or an empty list. """ if not _like_rnncell(cell_fw): raise TypeError("cell_fw must be an instance of RNNCell") if not _like_rnncell(cell_bw): raise TypeError("cell_bw must be an instance of RNNCell") if not nest.is_sequence(inputs): raise TypeError("inputs must be a sequence") if not inputs: raise ValueError("inputs must not be empty") with vs.variable_scope(scope or "bidirectional_rnn"): # Forward direction with vs.variable_scope("fw") as fw_scope: output_fw, output_state_fw = static_rnn( cell_fw, inputs, initial_state_fw, dtype, sequence_length, scope=fw_scope) # Backward direction with vs.variable_scope("bw") as bw_scope: reversed_inputs = _reverse_seq(inputs, sequence_length) tmp, output_state_bw = static_rnn( cell_bw, reversed_inputs, initial_state_bw, dtype, sequence_length, scope=bw_scope) output_bw = _reverse_seq(tmp, sequence_length) # Concat each of the forward/backward outputs flat_output_fw = nest.flatten(output_fw) flat_output_bw = nest.flatten(output_bw) flat_outputs = tuple( array_ops.concat([fw, bw], 1) for fw, bw in zip(flat_output_fw, flat_output_bw)) outputs = nest.pack_sequence_as( structure=output_fw, flat_sequence=flat_outputs) return (outputs, output_state_fw, output_state_bw)
[ "def", "static_bidirectional_rnn", "(", "cell_fw", ",", "cell_bw", ",", "inputs", ",", "initial_state_fw", "=", "None", ",", "initial_state_bw", "=", "None", ",", "dtype", "=", "None", ",", "sequence_length", "=", "None", ",", "scope", "=", "None", ")", ":",...
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/ops/rnn.py#L1364-L1457
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scikit-learn/py3/sklearn/feature_extraction/image.py
python
_compute_n_patches
(i_h, i_w, p_h, p_w, max_patches=None)
Compute the number of patches that will be extracted in an image. Read more in the :ref:`User Guide <image_feature_extraction>`. Parameters ---------- i_h : int The image height i_w : int The image with p_h : int The height of a patch p_w : int The width of a patch max_patches : integer or float, optional default is None The maximum number of patches to extract. If max_patches is a float between 0 and 1, it is taken to be a proportion of the total number of patches.
Compute the number of patches that will be extracted in an image.
[ "Compute", "the", "number", "of", "patches", "that", "will", "be", "extracted", "in", "an", "image", "." ]
def _compute_n_patches(i_h, i_w, p_h, p_w, max_patches=None): """Compute the number of patches that will be extracted in an image. Read more in the :ref:`User Guide <image_feature_extraction>`. Parameters ---------- i_h : int The image height i_w : int The image with p_h : int The height of a patch p_w : int The width of a patch max_patches : integer or float, optional default is None The maximum number of patches to extract. If max_patches is a float between 0 and 1, it is taken to be a proportion of the total number of patches. """ n_h = i_h - p_h + 1 n_w = i_w - p_w + 1 all_patches = n_h * n_w if max_patches: if (isinstance(max_patches, (numbers.Integral)) and max_patches < all_patches): return max_patches elif (isinstance(max_patches, (numbers.Integral)) and max_patches >= all_patches): return all_patches elif (isinstance(max_patches, (numbers.Real)) and 0 < max_patches < 1): return int(max_patches * all_patches) else: raise ValueError("Invalid value for max_patches: %r" % max_patches) else: return all_patches
[ "def", "_compute_n_patches", "(", "i_h", ",", "i_w", ",", "p_h", ",", "p_w", ",", "max_patches", "=", "None", ")", ":", "n_h", "=", "i_h", "-", "p_h", "+", "1", "n_w", "=", "i_w", "-", "p_w", "+", "1", "all_patches", "=", "n_h", "*", "n_w", "if",...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py3/sklearn/feature_extraction/image.py#L204-L241
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
qt/python/mantidqtinterfaces/mantidqtinterfaces/reduction_gui/widgets/diffraction/diffraction_adv_setup.py
python
AdvancedSetupWidget._cache_dir_browse_3
(self)
r"""Event handling for browsing the cache directory
r"""Event handling for browsing the cache directory
[ "r", "Event", "handling", "for", "browsing", "the", "cache", "directory" ]
def _cache_dir_browse_3(self): r"""Event handling for browsing the cache directory""" dir_path = self.dir_browse_dialog(title='Select the Cache Directory (scan only)') if dir_path: self._content.cache_dir_edit_3.setText(dir_path)
[ "def", "_cache_dir_browse_3", "(", "self", ")", ":", "dir_path", "=", "self", ".", "dir_browse_dialog", "(", "title", "=", "'Select the Cache Directory (scan only)'", ")", "if", "dir_path", ":", "self", ".", "_content", ".", "cache_dir_edit_3", ".", "setText", "("...
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/reduction_gui/widgets/diffraction/diffraction_adv_setup.py#L310-L314
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/decimal.py
python
Decimal.__pow__
(self, other, modulo=None, context=None)
return ans
Return self ** other [ % modulo]. With two arguments, compute self**other. With three arguments, compute (self**other) % modulo. For the three argument form, the following restrictions on the arguments hold: - all three arguments must be integral - other must be nonnegative - either self or other (or both) must be nonzero - modulo must be nonzero and must have at most p digits, where p is the context precision. If any of these restrictions is violated the InvalidOperation flag is raised. The result of pow(self, other, modulo) is identical to the result that would be obtained by computing (self**other) % modulo with unbounded precision, but is computed more efficiently. It is always exact.
Return self ** other [ % modulo].
[ "Return", "self", "**", "other", "[", "%", "modulo", "]", "." ]
def __pow__(self, other, modulo=None, context=None): """Return self ** other [ % modulo]. With two arguments, compute self**other. With three arguments, compute (self**other) % modulo. For the three argument form, the following restrictions on the arguments hold: - all three arguments must be integral - other must be nonnegative - either self or other (or both) must be nonzero - modulo must be nonzero and must have at most p digits, where p is the context precision. If any of these restrictions is violated the InvalidOperation flag is raised. The result of pow(self, other, modulo) is identical to the result that would be obtained by computing (self**other) % modulo with unbounded precision, but is computed more efficiently. It is always exact. """ if modulo is not None: return self._power_modulo(other, modulo, context) other = _convert_other(other) if other is NotImplemented: return other if context is None: context = getcontext() # either argument is a NaN => result is NaN ans = self._check_nans(other, context) if ans: return ans # 0**0 = NaN (!), x**0 = 1 for nonzero x (including +/-Infinity) if not other: if not self: return context._raise_error(InvalidOperation, '0 ** 0') else: return _One # result has sign 1 iff self._sign is 1 and other is an odd integer result_sign = 0 if self._sign == 1: if other._isinteger(): if not other._iseven(): result_sign = 1 else: # -ve**noninteger = NaN # (-0)**noninteger = 0**noninteger if self: return context._raise_error(InvalidOperation, 'x ** y with x negative and y not an integer') # negate self, without doing any unwanted rounding self = self.copy_negate() # 0**(+ve or Inf)= 0; 0**(-ve or -Inf) = Infinity if not self: if other._sign == 0: return _dec_from_triple(result_sign, '0', 0) else: return _SignedInfinity[result_sign] # Inf**(+ve or Inf) = Inf; Inf**(-ve or -Inf) = 0 if self._isinfinity(): if other._sign == 0: return _SignedInfinity[result_sign] else: return _dec_from_triple(result_sign, '0', 0) # 1**other = 1, but the choice of exponent and the flags # depend on the exponent of self, and on whether other is a # positive integer, a negative integer, or neither if self == _One: if other._isinteger(): # exp = max(self._exp*max(int(other), 0), # 1-context.prec) but evaluating int(other) directly # is dangerous until we know other is small (other # could be 1e999999999) if other._sign == 1: multiplier = 0 elif other > context.prec: multiplier = context.prec else: multiplier = int(other) exp = self._exp * multiplier if exp < 1-context.prec: exp = 1-context.prec context._raise_error(Rounded) else: context._raise_error(Inexact) context._raise_error(Rounded) exp = 1-context.prec return _dec_from_triple(result_sign, '1'+'0'*-exp, exp) # compute adjusted exponent of self self_adj = self.adjusted() # self ** infinity is infinity if self > 1, 0 if self < 1 # self ** -infinity is infinity if self < 1, 0 if self > 1 if other._isinfinity(): if (other._sign == 0) == (self_adj < 0): return _dec_from_triple(result_sign, '0', 0) else: return _SignedInfinity[result_sign] # from here on, the result always goes through the call # to _fix at the end of this function. ans = None exact = False # crude test to catch cases of extreme overflow/underflow. If # log10(self)*other >= 10**bound and bound >= len(str(Emax)) # then 10**bound >= 10**len(str(Emax)) >= Emax+1 and hence # self**other >= 10**(Emax+1), so overflow occurs. The test # for underflow is similar. bound = self._log10_exp_bound() + other.adjusted() if (self_adj >= 0) == (other._sign == 0): # self > 1 and other +ve, or self < 1 and other -ve # possibility of overflow if bound >= len(str(context.Emax)): ans = _dec_from_triple(result_sign, '1', context.Emax+1) else: # self > 1 and other -ve, or self < 1 and other +ve # possibility of underflow to 0 Etiny = context.Etiny() if bound >= len(str(-Etiny)): ans = _dec_from_triple(result_sign, '1', Etiny-1) # try for an exact result with precision +1 if ans is None: ans = self._power_exact(other, context.prec + 1) if ans is not None: if result_sign == 1: ans = _dec_from_triple(1, ans._int, ans._exp) exact = True # usual case: inexact result, x**y computed directly as exp(y*log(x)) if ans is None: p = context.prec x = _WorkRep(self) xc, xe = x.int, x.exp y = _WorkRep(other) yc, ye = y.int, y.exp if y.sign == 1: yc = -yc # compute correctly rounded result: start with precision +3, # then increase precision until result is unambiguously roundable extra = 3 while True: coeff, exp = _dpower(xc, xe, yc, ye, p+extra) if coeff % (5*10**(len(str(coeff))-p-1)): break extra += 3 ans = _dec_from_triple(result_sign, str(coeff), exp) # unlike exp, ln and log10, the power function respects the # rounding mode; no need to switch to ROUND_HALF_EVEN here # There's a difficulty here when 'other' is not an integer and # the result is exact. In this case, the specification # requires that the Inexact flag be raised (in spite of # exactness), but since the result is exact _fix won't do this # for us. (Correspondingly, the Underflow signal should also # be raised for subnormal results.) We can't directly raise # these signals either before or after calling _fix, since # that would violate the precedence for signals. So we wrap # the ._fix call in a temporary context, and reraise # afterwards. if exact and not other._isinteger(): # pad with zeros up to length context.prec+1 if necessary; this # ensures that the Rounded signal will be raised. if len(ans._int) <= context.prec: expdiff = context.prec + 1 - len(ans._int) ans = _dec_from_triple(ans._sign, ans._int+'0'*expdiff, ans._exp-expdiff) # create a copy of the current context, with cleared flags/traps newcontext = context.copy() newcontext.clear_flags() for exception in _signals: newcontext.traps[exception] = 0 # round in the new context ans = ans._fix(newcontext) # raise Inexact, and if necessary, Underflow newcontext._raise_error(Inexact) if newcontext.flags[Subnormal]: newcontext._raise_error(Underflow) # propagate signals to the original context; _fix could # have raised any of Overflow, Underflow, Subnormal, # Inexact, Rounded, Clamped. Overflow needs the correct # arguments. Note that the order of the exceptions is # important here. if newcontext.flags[Overflow]: context._raise_error(Overflow, 'above Emax', ans._sign) for exception in Underflow, Subnormal, Inexact, Rounded, Clamped: if newcontext.flags[exception]: context._raise_error(exception) else: ans = ans._fix(context) return ans
[ "def", "__pow__", "(", "self", ",", "other", ",", "modulo", "=", "None", ",", "context", "=", "None", ")", ":", "if", "modulo", "is", "not", "None", ":", "return", "self", ".", "_power_modulo", "(", "other", ",", "modulo", ",", "context", ")", "other...
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/decimal.py#L2174-L2388
BestSonny/SSTD
174d452189f6bf9cf4b6957719392008bd974069
python/caffe/io.py
python
Transformer.set_channel_swap
(self, in_, order)
Set the input channel order for e.g. RGB to BGR conversion as needed for the reference ImageNet model. N.B. this assumes the channels are the first dimension AFTER transpose. Parameters ---------- in_ : which input to assign this channel order order : the order to take the channels. (2,1,0) maps RGB to BGR for example.
Set the input channel order for e.g. RGB to BGR conversion as needed for the reference ImageNet model. N.B. this assumes the channels are the first dimension AFTER transpose.
[ "Set", "the", "input", "channel", "order", "for", "e", ".", "g", ".", "RGB", "to", "BGR", "conversion", "as", "needed", "for", "the", "reference", "ImageNet", "model", ".", "N", ".", "B", ".", "this", "assumes", "the", "channels", "are", "the", "first"...
def set_channel_swap(self, in_, order): """ Set the input channel order for e.g. RGB to BGR conversion as needed for the reference ImageNet model. N.B. this assumes the channels are the first dimension AFTER transpose. Parameters ---------- in_ : which input to assign this channel order order : the order to take the channels. (2,1,0) maps RGB to BGR for example. """ self.__check_input(in_) if len(order) != self.inputs[in_][1]: raise Exception('Channel swap needs to have the same number of ' 'dimensions as the input channels.') self.channel_swap[in_] = order
[ "def", "set_channel_swap", "(", "self", ",", "in_", ",", "order", ")", ":", "self", ".", "__check_input", "(", "in_", ")", "if", "len", "(", "order", ")", "!=", "self", ".", "inputs", "[", "in_", "]", "[", "1", "]", ":", "raise", "Exception", "(", ...
https://github.com/BestSonny/SSTD/blob/174d452189f6bf9cf4b6957719392008bd974069/python/caffe/io.py#L203-L219
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/roc/api.py
python
deregister
(*args)
Deregister data from the HSA system
Deregister data from the HSA system
[ "Deregister", "data", "from", "the", "HSA", "system" ]
def deregister(*args): """Deregister data from the HSA system """ for data in args: if isinstance(data, np.ndarray): _hsadrv.hsa_memory_deregister(data.ctypes.data, data.nbytes) else: raise TypeError(type(data))
[ "def", "deregister", "(", "*", "args", ")", ":", "for", "data", "in", "args", ":", "if", "isinstance", "(", "data", ",", "np", ".", "ndarray", ")", ":", "_hsadrv", ".", "hsa_memory_deregister", "(", "data", ".", "ctypes", ".", "data", ",", "data", "....
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/roc/api.py#L71-L78
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/init_ops_v2.py
python
lecun_uniform
(seed=None)
return VarianceScaling( scale=1., mode="fan_in", distribution="uniform", seed=seed)
LeCun uniform initializer. It draws samples from a uniform distribution within [-limit, limit] where `limit` is `sqrt(3 / fan_in)` where `fan_in` is the number of input units in the weight tensor. Arguments: seed: A Python integer. Used to seed the random generator. Returns: An initializer. References: - Self-Normalizing Neural Networks, [Klambauer et al., 2017](https://papers.nips.cc/paper/6698-self-normalizing-neural-networks) # pylint: disable=line-too-long ([pdf](https://papers.nips.cc/paper/6698-self-normalizing-neural-networks.pdf)) - Efficient Backprop, [Lecun et al., 1998](http://yann.lecun.com/exdb/publis/pdf/lecun-98b.pdf)
LeCun uniform initializer.
[ "LeCun", "uniform", "initializer", "." ]
def lecun_uniform(seed=None): """LeCun uniform initializer. It draws samples from a uniform distribution within [-limit, limit] where `limit` is `sqrt(3 / fan_in)` where `fan_in` is the number of input units in the weight tensor. Arguments: seed: A Python integer. Used to seed the random generator. Returns: An initializer. References: - Self-Normalizing Neural Networks, [Klambauer et al., 2017](https://papers.nips.cc/paper/6698-self-normalizing-neural-networks) # pylint: disable=line-too-long ([pdf](https://papers.nips.cc/paper/6698-self-normalizing-neural-networks.pdf)) - Efficient Backprop, [Lecun et al., 1998](http://yann.lecun.com/exdb/publis/pdf/lecun-98b.pdf) """ return VarianceScaling( scale=1., mode="fan_in", distribution="uniform", seed=seed)
[ "def", "lecun_uniform", "(", "seed", "=", "None", ")", ":", "return", "VarianceScaling", "(", "scale", "=", "1.", ",", "mode", "=", "\"fan_in\"", ",", "distribution", "=", "\"uniform\"", ",", "seed", "=", "seed", ")" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/init_ops_v2.py#L657-L678
xbmc/xbmc
091211a754589fc40a2a1f239b0ce9f4ee138268
addons/metadata.themoviedb.org.python/python/lib/tmdbscraper/tmdbapi.py
python
get_movie
(mid, language=None, append_to_response=None)
return api_utils.load_info(theurl, params=_set_params(append_to_response, language))
Get movie details :param mid: TMDb movie ID :param language: the language filter for TMDb (optional) :append_to_response: the additional data to get from TMDb (optional) :return: the movie or error
Get movie details
[ "Get", "movie", "details" ]
def get_movie(mid, language=None, append_to_response=None): # type: (Text) -> List[InfoType] """ Get movie details :param mid: TMDb movie ID :param language: the language filter for TMDb (optional) :append_to_response: the additional data to get from TMDb (optional) :return: the movie or error """ xbmc.log('using movie id of %s to get movie details' % mid, xbmc.LOGDEBUG) theurl = MOVIE_URL.format(mid) return api_utils.load_info(theurl, params=_set_params(append_to_response, language))
[ "def", "get_movie", "(", "mid", ",", "language", "=", "None", ",", "append_to_response", "=", "None", ")", ":", "# type: (Text) -> List[InfoType]", "xbmc", ".", "log", "(", "'using movie id of %s to get movie details'", "%", "mid", ",", "xbmc", ".", "LOGDEBUG", ")...
https://github.com/xbmc/xbmc/blob/091211a754589fc40a2a1f239b0ce9f4ee138268/addons/metadata.themoviedb.org.python/python/lib/tmdbscraper/tmdbapi.py#L81-L93
tensorflow/minigo
6d89c202cdceaf449aefc3149ab2110d44f1a6a4
minigo_model.py
python
read_model
(path)
return metadata, model_bytes
Reads a serialized model & metadata in Minigo format. Args: path: the model path. Returns: A (metadata, model_bytes) pair of the model's metadata as a dictionary and the serialized model as bytes.
Reads a serialized model & metadata in Minigo format.
[ "Reads", "a", "serialized", "model", "&", "metadata", "in", "Minigo", "format", "." ]
def read_model(path): """Reads a serialized model & metadata in Minigo format. Args: path: the model path. Returns: A (metadata, model_bytes) pair of the model's metadata as a dictionary and the serialized model as bytes. """ with tf.io.gfile.GFile(path, 'rb') as f: magic = f.read(MAGIC_SIZE).decode('utf-8') if magic != MAGIC: raise RuntimeError( 'expected magic string %s, got %s' % (MAGIC, magic)) version, file_size, metadata_size = struct.unpack( '<QQQ', f.read(HEADER_SIZE)) if version != 1: raise RuntimeError('expected version == 1, got %d' % version) metadata_bytes = f.read(metadata_size).decode('utf-8') if len(metadata_bytes) != metadata_size: raise RuntimeError('expected %dB of metadata, read only %dB' % ( metadata_size, len(metadata_bytes))) metadata = json.loads(metadata_bytes) model_bytes = f.read() model_size = len(model_bytes) bytes_read = MAGIC_SIZE + HEADER_SIZE + model_size + metadata_size if bytes_read != file_size: raise RuntimeError('expected %dB, read only %dB' % (file_size, bytes_read)) return metadata, model_bytes
[ "def", "read_model", "(", "path", ")", ":", "with", "tf", ".", "io", ".", "gfile", ".", "GFile", "(", "path", ",", "'rb'", ")", "as", "f", ":", "magic", "=", "f", ".", "read", "(", "MAGIC_SIZE", ")", ".", "decode", "(", "'utf-8'", ")", "if", "m...
https://github.com/tensorflow/minigo/blob/6d89c202cdceaf449aefc3149ab2110d44f1a6a4/minigo_model.py#L94-L130
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/lib-tk/tkSimpleDialog.py
python
askfloat
(title, prompt, **kw)
return d.result
get a float from the user Arguments: title -- the dialog title prompt -- the label text **kw -- see SimpleDialog class Return value is a float
get a float from the user
[ "get", "a", "float", "from", "the", "user" ]
def askfloat(title, prompt, **kw): '''get a float from the user Arguments: title -- the dialog title prompt -- the label text **kw -- see SimpleDialog class Return value is a float ''' d = _QueryFloat(title, prompt, **kw) return d.result
[ "def", "askfloat", "(", "title", ",", "prompt", ",", "*", "*", "kw", ")", ":", "d", "=", "_QueryFloat", "(", "title", ",", "prompt", ",", "*", "*", "kw", ")", "return", "d", ".", "result" ]
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/lib-tk/tkSimpleDialog.py#L270-L282
cyberbotics/webots
af7fa7d68dcf7b4550f1f2e132092b41e83698fc
resources/web/server/simulation_server.py
python
Client.on_exit
(self)
Callback issued when Webots quits.
Callback issued when Webots quits.
[ "Callback", "issued", "when", "Webots", "quits", "." ]
def on_exit(self): """Callback issued when Webots quits.""" if self.webots_process: logging.warning('[%d] Webots [%d] exited' % (id(self), self.webots_process.pid)) self.webots_process.wait() self.webots_process = None self.on_webots_quit()
[ "def", "on_exit", "(", "self", ")", ":", "if", "self", ".", "webots_process", ":", "logging", ".", "warning", "(", "'[%d] Webots [%d] exited'", "%", "(", "id", "(", "self", ")", ",", "self", ".", "webots_process", ".", "pid", ")", ")", "self", ".", "we...
https://github.com/cyberbotics/webots/blob/af7fa7d68dcf7b4550f1f2e132092b41e83698fc/resources/web/server/simulation_server.py#L327-L333
openbabel/openbabel
f3ed2a9a5166dbd3b9ce386e636a176074a6c34c
scripts/python/openbabel/pybel.py
python
Molecule.calcfp
(self, fptype="FP2")
return Fingerprint(fp)
Calculate a molecular fingerprint. Optional parameters: fptype -- the fingerprint type (default is "FP2"). See the fps variable for a list of of available fingerprint types.
Calculate a molecular fingerprint.
[ "Calculate", "a", "molecular", "fingerprint", "." ]
def calcfp(self, fptype="FP2"): """Calculate a molecular fingerprint. Optional parameters: fptype -- the fingerprint type (default is "FP2"). See the fps variable for a list of of available fingerprint types. """ if sys.platform[:3] == "cli": fp = ob.VectorUInt() else: fp = ob.vectorUnsignedInt() fptype = fptype.lower() try: fingerprinter = _fingerprinters[fptype] except KeyError: raise ValueError( "%s is not a recognised Open Babel Fingerprint type" % fptype) fingerprinter.GetFingerprint(self.OBMol, fp) return Fingerprint(fp)
[ "def", "calcfp", "(", "self", ",", "fptype", "=", "\"FP2\"", ")", ":", "if", "sys", ".", "platform", "[", ":", "3", "]", "==", "\"cli\"", ":", "fp", "=", "ob", ".", "VectorUInt", "(", ")", "else", ":", "fp", "=", "ob", ".", "vectorUnsignedInt", "...
https://github.com/openbabel/openbabel/blob/f3ed2a9a5166dbd3b9ce386e636a176074a6c34c/scripts/python/openbabel/pybel.py#L472-L491
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/setuptools/py2/setuptools/_vendor/pyparsing.py
python
ParserElement.parseFile
( self, file_or_filename, parseAll=False )
Execute the parse expression on the given file or filename. If a filename is specified (instead of a file object), the entire file is opened, read, and closed before parsing.
Execute the parse expression on the given file or filename. If a filename is specified (instead of a file object), the entire file is opened, read, and closed before parsing.
[ "Execute", "the", "parse", "expression", "on", "the", "given", "file", "or", "filename", ".", "If", "a", "filename", "is", "specified", "(", "instead", "of", "a", "file", "object", ")", "the", "entire", "file", "is", "opened", "read", "and", "closed", "b...
def parseFile( self, file_or_filename, parseAll=False ): """ Execute the parse expression on the given file or filename. If a filename is specified (instead of a file object), the entire file is opened, read, and closed before parsing. """ try: file_contents = file_or_filename.read() except AttributeError: with open(file_or_filename, "r") as f: file_contents = f.read() try: return self.parseString(file_contents, parseAll) except ParseBaseException as exc: if ParserElement.verbose_stacktrace: raise else: # catch and re-raise exception from here, clears out pyparsing internal stack trace raise exc
[ "def", "parseFile", "(", "self", ",", "file_or_filename", ",", "parseAll", "=", "False", ")", ":", "try", ":", "file_contents", "=", "file_or_filename", ".", "read", "(", ")", "except", "AttributeError", ":", "with", "open", "(", "file_or_filename", ",", "\"...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/setuptools/py2/setuptools/_vendor/pyparsing.py#L2173-L2191
PaddlePaddle/Paddle
1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c
python/paddle/fluid/contrib/sparsity/utils.py
python
CheckMethod.get_checking_method
(mask_algo)
r""" Get sparsity checking method by mask generating algorithm. Args: mask_algo (MaskAlgo): The algorithm of mask generating. Returns: CheckMethod: The corresponded sparsity checking method. Examples: .. code-block:: python import numpy as np from paddle.static.sparsity import MaskAlgo from paddle.fluid.contrib.sparsity import CheckMethod CheckMethod.get_checking_method(MaskAlgo.MASK_1D) # CheckMethod.CHECK_1D CheckMethod.get_checking_method(MaskAlgo.MASK_2D_GREEDY) # CheckMethod.CHECK_2D CheckMethod.get_checking_method(MaskAlgo.MASK_2D_BEST) # CheckMethod.CHECK_2D
r""" Get sparsity checking method by mask generating algorithm.
[ "r", "Get", "sparsity", "checking", "method", "by", "mask", "generating", "algorithm", "." ]
def get_checking_method(mask_algo): r""" Get sparsity checking method by mask generating algorithm. Args: mask_algo (MaskAlgo): The algorithm of mask generating. Returns: CheckMethod: The corresponded sparsity checking method. Examples: .. code-block:: python import numpy as np from paddle.static.sparsity import MaskAlgo from paddle.fluid.contrib.sparsity import CheckMethod CheckMethod.get_checking_method(MaskAlgo.MASK_1D) # CheckMethod.CHECK_1D CheckMethod.get_checking_method(MaskAlgo.MASK_2D_GREEDY) # CheckMethod.CHECK_2D CheckMethod.get_checking_method(MaskAlgo.MASK_2D_BEST) # CheckMethod.CHECK_2D """ assert isinstance(mask_algo, MaskAlgo), \ "mask_algo should be MaskAlgo type" if mask_algo == MaskAlgo.MASK_1D: return CheckMethod.CHECK_1D else: return CheckMethod.CHECK_2D
[ "def", "get_checking_method", "(", "mask_algo", ")", ":", "assert", "isinstance", "(", "mask_algo", ",", "MaskAlgo", ")", ",", "\"mask_algo should be MaskAlgo type\"", "if", "mask_algo", "==", "MaskAlgo", ".", "MASK_1D", ":", "return", "CheckMethod", ".", "CHECK_1D"...
https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/fluid/contrib/sparsity/utils.py#L55-L84
ricardoquesada/Spidermonkey
4a75ea2543408bd1b2c515aa95901523eeef7858
build/pymake/pymake/data.py
python
Target.searchinlocs
(self, makefile, locs)
return None
Look in the given locations relative to the makefile working directory for a file. Return a pair of the target and the mtime if found, None if not.
Look in the given locations relative to the makefile working directory for a file. Return a pair of the target and the mtime if found, None if not.
[ "Look", "in", "the", "given", "locations", "relative", "to", "the", "makefile", "working", "directory", "for", "a", "file", ".", "Return", "a", "pair", "of", "the", "target", "and", "the", "mtime", "if", "found", "None", "if", "not", "." ]
def searchinlocs(self, makefile, locs): """ Look in the given locations relative to the makefile working directory for a file. Return a pair of the target and the mtime if found, None if not. """ for t in locs: fspath = util.normaljoin(makefile.workdir, t).replace('\\', '/') mtime = getmtime(fspath) # _log.info("Searching %s ... checking %s ... mtime %r" % (t, fspath, mtime)) if mtime is not None: return (t, mtime) return None
[ "def", "searchinlocs", "(", "self", ",", "makefile", ",", "locs", ")", ":", "for", "t", "in", "locs", ":", "fspath", "=", "util", ".", "normaljoin", "(", "makefile", ".", "workdir", ",", "t", ")", ".", "replace", "(", "'\\\\'", ",", "'/'", ")", "mt...
https://github.com/ricardoquesada/Spidermonkey/blob/4a75ea2543408bd1b2c515aa95901523eeef7858/build/pymake/pymake/data.py#L1207-L1220
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/packaging/py3/packaging/version.py
python
_parse_local_version
(local: str)
return None
Takes a string like abc.1.twelve and turns it into ("abc", 1, "twelve").
Takes a string like abc.1.twelve and turns it into ("abc", 1, "twelve").
[ "Takes", "a", "string", "like", "abc", ".", "1", ".", "twelve", "and", "turns", "it", "into", "(", "abc", "1", "twelve", ")", "." ]
def _parse_local_version(local: str) -> Optional[LocalType]: """ Takes a string like abc.1.twelve and turns it into ("abc", 1, "twelve"). """ if local is not None: return tuple( part.lower() if not part.isdigit() else int(part) for part in _local_version_separators.split(local) ) return None
[ "def", "_parse_local_version", "(", "local", ":", "str", ")", "->", "Optional", "[", "LocalType", "]", ":", "if", "local", "is", "not", "None", ":", "return", "tuple", "(", "part", ".", "lower", "(", ")", "if", "not", "part", ".", "isdigit", "(", ")"...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/packaging/py3/packaging/version.py#L432-L441
mongodb/mongo
d8ff665343ad29cf286ee2cf4a1960d29371937b
buildscripts/packager.py
python
crossproduct
(*seqs)
Provide a generator for iterating all the tuples consisting of elements of seqs.
Provide a generator for iterating all the tuples consisting of elements of seqs.
[ "Provide", "a", "generator", "for", "iterating", "all", "the", "tuples", "consisting", "of", "elements", "of", "seqs", "." ]
def crossproduct(*seqs): """Provide a generator for iterating all the tuples consisting of elements of seqs.""" num_seqs = len(seqs) if num_seqs == 0: pass elif num_seqs == 1: for idx in seqs[0]: yield [idx] else: for lst in crossproduct(*seqs[:-1]): for idx in seqs[-1]: lst2 = list(lst) lst2.append(idx) yield lst2
[ "def", "crossproduct", "(", "*", "seqs", ")", ":", "num_seqs", "=", "len", "(", "seqs", ")", "if", "num_seqs", "==", "0", ":", "pass", "elif", "num_seqs", "==", "1", ":", "for", "idx", "in", "seqs", "[", "0", "]", ":", "yield", "[", "idx", "]", ...
https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/buildscripts/packager.py#L443-L456
TimoSaemann/caffe-segnet-cudnn5
abcf30dca449245e101bf4ced519f716177f0885
scripts/cpp_lint.py
python
CheckCaffeDataLayerSetUp
(filename, clean_lines, linenum, error)
Except the base classes, Caffe DataLayer should define DataLayerSetUp instead of LayerSetUp. The base DataLayers define common SetUp steps, the subclasses should not override them. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found.
Except the base classes, Caffe DataLayer should define DataLayerSetUp instead of LayerSetUp. The base DataLayers define common SetUp steps, the subclasses should not override them. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found.
[ "Except", "the", "base", "classes", "Caffe", "DataLayer", "should", "define", "DataLayerSetUp", "instead", "of", "LayerSetUp", ".", "The", "base", "DataLayers", "define", "common", "SetUp", "steps", "the", "subclasses", "should", "not", "override", "them", ".", ...
def CheckCaffeDataLayerSetUp(filename, clean_lines, linenum, error): """Except the base classes, Caffe DataLayer should define DataLayerSetUp instead of LayerSetUp. The base DataLayers define common SetUp steps, the subclasses should not override them. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ line = clean_lines.elided[linenum] ix = line.find('DataLayer<Dtype>::LayerSetUp') if ix >= 0 and ( line.find('void DataLayer<Dtype>::LayerSetUp') != -1 or line.find('void ImageDataLayer<Dtype>::LayerSetUp') != -1 or line.find('void MemoryDataLayer<Dtype>::LayerSetUp') != -1 or line.find('void WindowDataLayer<Dtype>::LayerSetUp') != -1): error(filename, linenum, 'caffe/data_layer_setup', 2, 'Except the base classes, Caffe DataLayer should define' + ' DataLayerSetUp instead of LayerSetUp. The base DataLayers' + ' define common SetUp steps, the subclasses should' + ' not override them.') ix = line.find('DataLayer<Dtype>::DataLayerSetUp') if ix >= 0 and ( line.find('void Base') == -1 and line.find('void DataLayer<Dtype>::DataLayerSetUp') == -1 and line.find('void ImageDataLayer<Dtype>::DataLayerSetUp') == -1 and line.find('void MemoryDataLayer<Dtype>::DataLayerSetUp') == -1 and line.find('void WindowDataLayer<Dtype>::DataLayerSetUp') == -1): error(filename, linenum, 'caffe/data_layer_setup', 2, 'Except the base classes, Caffe DataLayer should define' + ' DataLayerSetUp instead of LayerSetUp. The base DataLayers' + ' define common SetUp steps, the subclasses should' + ' not override them.')
[ "def", "CheckCaffeDataLayerSetUp", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "error", ")", ":", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "ix", "=", "line", ".", "find", "(", "'DataLayer<Dtype>::LayerSetUp'", ")", "if", ...
https://github.com/TimoSaemann/caffe-segnet-cudnn5/blob/abcf30dca449245e101bf4ced519f716177f0885/scripts/cpp_lint.py#L1595-L1631
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/cgutils.py
python
snprintf_stackbuffer
(builder, bufsz, format, *args)
return buffer
Similar to `snprintf()` but the buffer is stack allocated to size *bufsz*. Returns the buffer pointer as i8*.
Similar to `snprintf()` but the buffer is stack allocated to size *bufsz*.
[ "Similar", "to", "snprintf", "()", "but", "the", "buffer", "is", "stack", "allocated", "to", "size", "*", "bufsz", "*", "." ]
def snprintf_stackbuffer(builder, bufsz, format, *args): """Similar to `snprintf()` but the buffer is stack allocated to size *bufsz*. Returns the buffer pointer as i8*. """ assert isinstance(bufsz, int) spacety = ir.ArrayType(ir.IntType(8), bufsz) space = alloca_once(builder, spacety, zfill=True) buffer = builder.bitcast(space, voidptr_t) snprintf(builder, buffer, intp_t(bufsz), format, *args) return buffer
[ "def", "snprintf_stackbuffer", "(", "builder", ",", "bufsz", ",", "format", ",", "*", "args", ")", ":", "assert", "isinstance", "(", "bufsz", ",", "int", ")", "spacety", "=", "ir", ".", "ArrayType", "(", "ir", ".", "IntType", "(", "8", ")", ",", "buf...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/cgutils.py#L1088-L1098
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/ops/variables.py
python
VariableMetaclass._variable_v1_call
(cls, initial_value=None, trainable=None, collections=None, validate_shape=True, caching_device=None, name=None, variable_def=None, dtype=None, expected_shape=None, import_scope=None, constraint=None, use_resource=None, synchronization=VariableSynchronization.AUTO, aggregation=VariableAggregation.NONE, shape=None)
return previous_getter( initial_value=initial_value, trainable=trainable, collections=collections, validate_shape=validate_shape, caching_device=caching_device, name=name, variable_def=variable_def, dtype=dtype, expected_shape=expected_shape, import_scope=import_scope, constraint=constraint, use_resource=use_resource, synchronization=synchronization, aggregation=aggregation, shape=shape)
Call on Variable class. Useful to force the signature.
Call on Variable class. Useful to force the signature.
[ "Call", "on", "Variable", "class", ".", "Useful", "to", "force", "the", "signature", "." ]
def _variable_v1_call(cls, initial_value=None, trainable=None, collections=None, validate_shape=True, caching_device=None, name=None, variable_def=None, dtype=None, expected_shape=None, import_scope=None, constraint=None, use_resource=None, synchronization=VariableSynchronization.AUTO, aggregation=VariableAggregation.NONE, shape=None): """Call on Variable class. Useful to force the signature.""" previous_getter = lambda **kwargs: default_variable_creator(None, **kwargs) for _, getter in ops.get_default_graph()._variable_creator_stack: # pylint: disable=protected-access previous_getter = _make_getter(getter, previous_getter) # Reset `aggregation` that is explicitly set as `None` to the enum NONE. if aggregation is None: aggregation = VariableAggregation.NONE return previous_getter( initial_value=initial_value, trainable=trainable, collections=collections, validate_shape=validate_shape, caching_device=caching_device, name=name, variable_def=variable_def, dtype=dtype, expected_shape=expected_shape, import_scope=import_scope, constraint=constraint, use_resource=use_resource, synchronization=synchronization, aggregation=aggregation, shape=shape)
[ "def", "_variable_v1_call", "(", "cls", ",", "initial_value", "=", "None", ",", "trainable", "=", "None", ",", "collections", "=", "None", ",", "validate_shape", "=", "True", ",", "caching_device", "=", "None", ",", "name", "=", "None", ",", "variable_def", ...
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/variables.py#L185-L224
HackWebRTC/webrtc
7abfc990c00ab35090fff285fcf635d1d7892433
tools_webrtc/network_emulator/network_emulator.py
python
_RunIpfwCommand
(command, fail_msg=None)
return output.strip()
Executes a command and prefixes the appropriate command for Windows or Linux/UNIX. Args: command: Command list to execute. fail_msg: Message describing the error in case the command fails. Raises: NetworkEmulatorError: If command fails a message is set by the fail_msg parameter.
Executes a command and prefixes the appropriate command for Windows or Linux/UNIX.
[ "Executes", "a", "command", "and", "prefixes", "the", "appropriate", "command", "for", "Windows", "or", "Linux", "/", "UNIX", "." ]
def _RunIpfwCommand(command, fail_msg=None): """Executes a command and prefixes the appropriate command for Windows or Linux/UNIX. Args: command: Command list to execute. fail_msg: Message describing the error in case the command fails. Raises: NetworkEmulatorError: If command fails a message is set by the fail_msg parameter. """ if sys.platform == 'win32': ipfw_command = ['ipfw.exe'] else: ipfw_command = ['sudo', '-n', 'ipfw'] cmd_list = ipfw_command[:] + [str(x) for x in command] cmd_string = ' '.join(cmd_list) logging.debug('Running command: %s', cmd_string) process = subprocess.Popen(cmd_list, stdout=subprocess.PIPE, stderr=subprocess.PIPE) output, error = process.communicate() if process.returncode != 0: raise NetworkEmulatorError(fail_msg, cmd_string, process.returncode, output, error) return output.strip()
[ "def", "_RunIpfwCommand", "(", "command", ",", "fail_msg", "=", "None", ")", ":", "if", "sys", ".", "platform", "==", "'win32'", ":", "ipfw_command", "=", "[", "'ipfw.exe'", "]", "else", ":", "ipfw_command", "=", "[", "'sudo'", ",", "'-n'", ",", "'ipfw'"...
https://github.com/HackWebRTC/webrtc/blob/7abfc990c00ab35090fff285fcf635d1d7892433/tools_webrtc/network_emulator/network_emulator.py#L163-L189
adobe/chromium
cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7
third_party/mesa/MesaLib/src/gallium/auxiliary/util/u_format_pack.py
python
generate_format_type
(format)
Generate a structure that describes the format.
Generate a structure that describes the format.
[ "Generate", "a", "structure", "that", "describes", "the", "format", "." ]
def generate_format_type(format): '''Generate a structure that describes the format.''' assert format.layout == PLAIN print 'union util_format_%s {' % format.short_name() if format.block_size() in (8, 16, 32, 64): print ' uint%u_t value;' % (format.block_size(),) use_bitfields = False for channel in format.channels: if channel.size % 8 or not is_pot(channel.size): use_bitfields = True print ' struct {' for channel in format.channels: if use_bitfields: if channel.type == VOID: if channel.size: print ' unsigned %s:%u;' % (channel.name, channel.size) elif channel.type == UNSIGNED: print ' unsigned %s:%u;' % (channel.name, channel.size) elif channel.type in (SIGNED, FIXED): print ' int %s:%u;' % (channel.name, channel.size) elif channel.type == FLOAT: if channel.size == 64: print ' double %s;' % (channel.name) elif channel.size == 32: print ' float %s;' % (channel.name) else: print ' unsigned %s:%u;' % (channel.name, channel.size) else: assert 0 else: assert channel.size % 8 == 0 and is_pot(channel.size) if channel.type == VOID: if channel.size: print ' uint%u_t %s;' % (channel.size, channel.name) elif channel.type == UNSIGNED: print ' uint%u_t %s;' % (channel.size, channel.name) elif channel.type in (SIGNED, FIXED): print ' int%u_t %s;' % (channel.size, channel.name) elif channel.type == FLOAT: if channel.size == 64: print ' double %s;' % (channel.name) elif channel.size == 32: print ' float %s;' % (channel.name) elif channel.size == 16: print ' uint16_t %s;' % (channel.name) else: assert 0 else: assert 0 print ' } chan;' print '};' print
[ "def", "generate_format_type", "(", "format", ")", ":", "assert", "format", ".", "layout", "==", "PLAIN", "print", "'union util_format_%s {'", "%", "format", ".", "short_name", "(", ")", "if", "format", ".", "block_size", "(", ")", "in", "(", "8", ",", "16...
https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/third_party/mesa/MesaLib/src/gallium/auxiliary/util/u_format_pack.py#L43-L99
cvxpy/cvxpy
5165b4fb750dfd237de8659383ef24b4b2e33aaf
cvxpy/lin_ops/lin_utils.py
python
replace_new_vars
(expr, id_to_new_var)
Replaces the given variables in the expression. Parameters ---------- expr : LinOp The expression to replace variables in. id_to_new_var : dict A map of id to new variable. Returns ------- LinOp An LinOp identical to expr, but with the given variables replaced.
Replaces the given variables in the expression.
[ "Replaces", "the", "given", "variables", "in", "the", "expression", "." ]
def replace_new_vars(expr, id_to_new_var): """Replaces the given variables in the expression. Parameters ---------- expr : LinOp The expression to replace variables in. id_to_new_var : dict A map of id to new variable. Returns ------- LinOp An LinOp identical to expr, but with the given variables replaced. """ if expr.type == lo.VARIABLE and expr.data in id_to_new_var: return id_to_new_var[expr.data] else: new_args = [] for arg in expr.args: new_args.append( replace_new_vars(arg, id_to_new_var) ) return lo.LinOp(expr.type, expr.shape, new_args, expr.data)
[ "def", "replace_new_vars", "(", "expr", ",", "id_to_new_var", ")", ":", "if", "expr", ".", "type", "==", "lo", ".", "VARIABLE", "and", "expr", ".", "data", "in", "id_to_new_var", ":", "return", "id_to_new_var", "[", "expr", ".", "data", "]", "else", ":",...
https://github.com/cvxpy/cvxpy/blob/5165b4fb750dfd237de8659383ef24b4b2e33aaf/cvxpy/lin_ops/lin_utils.py#L698-L721
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/richtext.py
python
RichTextCtrl.KeyboardNavigate
(*args, **kwargs)
return _richtext.RichTextCtrl_KeyboardNavigate(*args, **kwargs)
KeyboardNavigate(self, int keyCode, int flags) -> bool
KeyboardNavigate(self, int keyCode, int flags) -> bool
[ "KeyboardNavigate", "(", "self", "int", "keyCode", "int", "flags", ")", "-", ">", "bool" ]
def KeyboardNavigate(*args, **kwargs): """KeyboardNavigate(self, int keyCode, int flags) -> bool""" return _richtext.RichTextCtrl_KeyboardNavigate(*args, **kwargs)
[ "def", "KeyboardNavigate", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_richtext", ".", "RichTextCtrl_KeyboardNavigate", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/richtext.py#L4052-L4054
ricardoquesada/Spidermonkey
4a75ea2543408bd1b2c515aa95901523eeef7858
python/mozbuild/mozpack/chrome/manifest.py
python
ManifestEntry.__init__
(self, base, *flags)
Initialize a manifest entry with the given base path and flags.
Initialize a manifest entry with the given base path and flags.
[ "Initialize", "a", "manifest", "entry", "with", "the", "given", "base", "path", "and", "flags", "." ]
def __init__(self, base, *flags): ''' Initialize a manifest entry with the given base path and flags. ''' self.base = base self.flags = Flags(*flags) if not all(f in self.allowed_flags for f in self.flags): errors.fatal('%s unsupported for %s manifest entries' % (','.join(f for f in self.flags if not f in self.allowed_flags), self.type))
[ "def", "__init__", "(", "self", ",", "base", ",", "*", "flags", ")", ":", "self", ".", "base", "=", "base", "self", ".", "flags", "=", "Flags", "(", "*", "flags", ")", "if", "not", "all", "(", "f", "in", "self", ".", "allowed_flags", "for", "f", ...
https://github.com/ricardoquesada/Spidermonkey/blob/4a75ea2543408bd1b2c515aa95901523eeef7858/python/mozbuild/mozpack/chrome/manifest.py#L40-L49
eclipse/sumo
7132a9b8b6eea734bdec38479026b4d8c4336d03
tools/traci/_vehicle.py
python
VehicleDomain.setMaxSpeed
(self, vehID, speed)
setMaxSpeed(string, double) -> None Sets the maximum speed in m/s for this vehicle.
setMaxSpeed(string, double) -> None
[ "setMaxSpeed", "(", "string", "double", ")", "-", ">", "None" ]
def setMaxSpeed(self, vehID, speed): """setMaxSpeed(string, double) -> None Sets the maximum speed in m/s for this vehicle. """ self._setCmd(tc.VAR_MAXSPEED, vehID, "d", speed)
[ "def", "setMaxSpeed", "(", "self", ",", "vehID", ",", "speed", ")", ":", "self", ".", "_setCmd", "(", "tc", ".", "VAR_MAXSPEED", ",", "vehID", ",", "\"d\"", ",", "speed", ")" ]
https://github.com/eclipse/sumo/blob/7132a9b8b6eea734bdec38479026b4d8c4336d03/tools/traci/_vehicle.py#L1030-L1035
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python/src/Lib/cmd.py
python
Cmd.__init__
(self, completekey='tab', stdin=None, stdout=None)
Instantiate a line-oriented interpreter framework. The optional argument 'completekey' is the readline name of a completion key; it defaults to the Tab key. If completekey is not None and the readline module is available, command completion is done automatically. The optional arguments stdin and stdout specify alternate input and output file objects; if not specified, sys.stdin and sys.stdout are used.
Instantiate a line-oriented interpreter framework.
[ "Instantiate", "a", "line", "-", "oriented", "interpreter", "framework", "." ]
def __init__(self, completekey='tab', stdin=None, stdout=None): """Instantiate a line-oriented interpreter framework. The optional argument 'completekey' is the readline name of a completion key; it defaults to the Tab key. If completekey is not None and the readline module is available, command completion is done automatically. The optional arguments stdin and stdout specify alternate input and output file objects; if not specified, sys.stdin and sys.stdout are used. """ import sys if stdin is not None: self.stdin = stdin else: self.stdin = sys.stdin if stdout is not None: self.stdout = stdout else: self.stdout = sys.stdout self.cmdqueue = [] self.completekey = completekey
[ "def", "__init__", "(", "self", ",", "completekey", "=", "'tab'", ",", "stdin", "=", "None", ",", "stdout", "=", "None", ")", ":", "import", "sys", "if", "stdin", "is", "not", "None", ":", "self", ".", "stdin", "=", "stdin", "else", ":", "self", "....
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/cmd.py#L79-L100
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/richtext.py
python
RichTextPrinting.SetFooterText
(*args, **kwargs)
return _richtext.RichTextPrinting_SetFooterText(*args, **kwargs)
SetFooterText(self, String text, int page=RICHTEXT_PAGE_ALL, int location=RICHTEXT_PAGE_CENTRE)
SetFooterText(self, String text, int page=RICHTEXT_PAGE_ALL, int location=RICHTEXT_PAGE_CENTRE)
[ "SetFooterText", "(", "self", "String", "text", "int", "page", "=", "RICHTEXT_PAGE_ALL", "int", "location", "=", "RICHTEXT_PAGE_CENTRE", ")" ]
def SetFooterText(*args, **kwargs): """SetFooterText(self, String text, int page=RICHTEXT_PAGE_ALL, int location=RICHTEXT_PAGE_CENTRE)""" return _richtext.RichTextPrinting_SetFooterText(*args, **kwargs)
[ "def", "SetFooterText", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_richtext", ".", "RichTextPrinting_SetFooterText", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/richtext.py#L4520-L4522
snap-stanford/snap-python
d53c51b0a26aa7e3e7400b014cdf728948fde80a
setup/snap.py
python
TCnCom.SaveTxt
(*args)
return _snap.TCnCom_SaveTxt(*args)
SaveTxt(TCnComV const & CnComV, TStr FNm, TStr Desc=TStr()) Parameters: CnComV: TCnComV const & FNm: TStr const & Desc: TStr const & SaveTxt(TCnComV const & CnComV, TStr FNm) Parameters: CnComV: TCnComV const & FNm: TStr const &
SaveTxt(TCnComV const & CnComV, TStr FNm, TStr Desc=TStr())
[ "SaveTxt", "(", "TCnComV", "const", "&", "CnComV", "TStr", "FNm", "TStr", "Desc", "=", "TStr", "()", ")" ]
def SaveTxt(*args): """ SaveTxt(TCnComV const & CnComV, TStr FNm, TStr Desc=TStr()) Parameters: CnComV: TCnComV const & FNm: TStr const & Desc: TStr const & SaveTxt(TCnComV const & CnComV, TStr FNm) Parameters: CnComV: TCnComV const & FNm: TStr const & """ return _snap.TCnCom_SaveTxt(*args)
[ "def", "SaveTxt", "(", "*", "args", ")", ":", "return", "_snap", ".", "TCnCom_SaveTxt", "(", "*", "args", ")" ]
https://github.com/snap-stanford/snap-python/blob/d53c51b0a26aa7e3e7400b014cdf728948fde80a/setup/snap.py#L909-L925
adobe/chromium
cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7
third_party/closure_linter/closure_linter/tokenutil.py
python
InsertTokensAfter
(new_tokens, token)
Insert multiple tokens after token. Args: new_tokens: An array of tokens to be added to the stream token: A token already in the stream
Insert multiple tokens after token.
[ "Insert", "multiple", "tokens", "after", "token", "." ]
def InsertTokensAfter(new_tokens, token): """Insert multiple tokens after token. Args: new_tokens: An array of tokens to be added to the stream token: A token already in the stream """ # TODO(user): It would be nicer to have InsertTokenAfter defer to here # instead of vice-versa. current_token = token for new_token in new_tokens: InsertTokenAfter(new_token, current_token) current_token = new_token
[ "def", "InsertTokensAfter", "(", "new_tokens", ",", "token", ")", ":", "# TODO(user): It would be nicer to have InsertTokenAfter defer to here", "# instead of vice-versa.", "current_token", "=", "token", "for", "new_token", "in", "new_tokens", ":", "InsertTokenAfter", "(", "n...
https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/third_party/closure_linter/closure_linter/tokenutil.py#L278-L290
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_core.py
python
Rect2D.GetRightBottom
(*args, **kwargs)
return _core_.Rect2D_GetRightBottom(*args, **kwargs)
GetRightBottom(self) -> Point2D
GetRightBottom(self) -> Point2D
[ "GetRightBottom", "(", "self", ")", "-", ">", "Point2D" ]
def GetRightBottom(*args, **kwargs): """GetRightBottom(self) -> Point2D""" return _core_.Rect2D_GetRightBottom(*args, **kwargs)
[ "def", "GetRightBottom", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "Rect2D_GetRightBottom", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_core.py#L1939-L1941
oracle/graaljs
36a56e8e993d45fc40939a3a4d9c0c24990720f1
graal-nodejs/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/MSVSProject.py
python
Tool.__init__
(self, name, attrs=None)
Initializes the tool. Args: name: Tool name. attrs: Dict of tool attributes; may be None.
Initializes the tool.
[ "Initializes", "the", "tool", "." ]
def __init__(self, name, attrs=None): """Initializes the tool. Args: name: Tool name. attrs: Dict of tool attributes; may be None. """ self._attrs = attrs or {} self._attrs["Name"] = name
[ "def", "__init__", "(", "self", ",", "name", ",", "attrs", "=", "None", ")", ":", "self", ".", "_attrs", "=", "attrs", "or", "{", "}", "self", ".", "_attrs", "[", "\"Name\"", "]", "=", "name" ]
https://github.com/oracle/graaljs/blob/36a56e8e993d45fc40939a3a4d9c0c24990720f1/graal-nodejs/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/MSVSProject.py#L15-L23
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/framework/subscribe.py
python
_scoped_subscribe
(tensor, side_effects, control_cache)
Helper method that subscribes a single tensor to a list of side_effects. This is a thin wrapper around `_subscribe` and ensures that the side effect ops are added within the same device and control flow context of the subscribed tensor. Args: tensor: The `tf.Tensor` to be subscribed. side_effects: List of side_effect functions, see subscribe for details. control_cache: `_ControlOutputCache` helper to get control_outputs faster. Returns: The modified replacement to the passed in tensor which triggers the side effects or the given tensor, if it was already been subscribed.
Helper method that subscribes a single tensor to a list of side_effects.
[ "Helper", "method", "that", "subscribes", "a", "single", "tensor", "to", "a", "list", "of", "side_effects", "." ]
def _scoped_subscribe(tensor, side_effects, control_cache): """Helper method that subscribes a single tensor to a list of side_effects. This is a thin wrapper around `_subscribe` and ensures that the side effect ops are added within the same device and control flow context of the subscribed tensor. Args: tensor: The `tf.Tensor` to be subscribed. side_effects: List of side_effect functions, see subscribe for details. control_cache: `_ControlOutputCache` helper to get control_outputs faster. Returns: The modified replacement to the passed in tensor which triggers the side effects or the given tensor, if it was already been subscribed. """ with ops.device(tensor.device): with _preserve_control_flow_context(tensor): return _subscribe(tensor, side_effects, control_cache)
[ "def", "_scoped_subscribe", "(", "tensor", ",", "side_effects", ",", "control_cache", ")", ":", "with", "ops", ".", "device", "(", "tensor", ".", "device", ")", ":", "with", "_preserve_control_flow_context", "(", "tensor", ")", ":", "return", "_subscribe", "("...
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/framework/subscribe.py#L290-L309
pytorch/pytorch
7176c92687d3cc847cc046bf002269c6949a21c2
torch/ao/quantization/fx/lower_to_qnnpack.py
python
lower_to_qnnpack
(model: QuantizedGraphModule)
return _lower_to_native_backend(model)
Lower a quantized reference model (with reference quantized operator patterns) to qnnpack
Lower a quantized reference model (with reference quantized operator patterns) to qnnpack
[ "Lower", "a", "quantized", "reference", "model", "(", "with", "reference", "quantized", "operator", "patterns", ")", "to", "qnnpack" ]
def lower_to_qnnpack(model: QuantizedGraphModule) -> QuantizedGraphModule: """ Lower a quantized reference model (with reference quantized operator patterns) to qnnpack """ return _lower_to_native_backend(model)
[ "def", "lower_to_qnnpack", "(", "model", ":", "QuantizedGraphModule", ")", "->", "QuantizedGraphModule", ":", "return", "_lower_to_native_backend", "(", "model", ")" ]
https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/torch/ao/quantization/fx/lower_to_qnnpack.py#L4-L8
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_controls.py
python
ListCtrl.GetItemFont
(*args, **kwargs)
return _controls_.ListCtrl_GetItemFont(*args, **kwargs)
GetItemFont(self, long item) -> Font
GetItemFont(self, long item) -> Font
[ "GetItemFont", "(", "self", "long", "item", ")", "-", ">", "Font" ]
def GetItemFont(*args, **kwargs): """GetItemFont(self, long item) -> Font""" return _controls_.ListCtrl_GetItemFont(*args, **kwargs)
[ "def", "GetItemFont", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_controls_", ".", "ListCtrl_GetItemFont", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_controls.py#L4756-L4758
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/build/waf-1.7.13/waflib/Tools/c_config.py
python
check_cc
(self, *k, **kw)
return self.check(*k, **kw)
Same as :py:func:`waflib.Tools.c_config.check` but default to the *c* programming language
Same as :py:func:`waflib.Tools.c_config.check` but default to the *c* programming language
[ "Same", "as", ":", "py", ":", "func", ":", "waflib", ".", "Tools", ".", "c_config", ".", "check", "but", "default", "to", "the", "*", "c", "*", "programming", "language" ]
def check_cc(self, *k, **kw): """ Same as :py:func:`waflib.Tools.c_config.check` but default to the *c* programming language """ kw['compiler'] = 'c' return self.check(*k, **kw)
[ "def", "check_cc", "(", "self", ",", "*", "k", ",", "*", "*", "kw", ")", ":", "kw", "[", "'compiler'", "]", "=", "'c'", "return", "self", ".", "check", "(", "*", "k", ",", "*", "*", "kw", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/build/waf-1.7.13/waflib/Tools/c_config.py#L793-L798
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/lib-tk/Tkinter.py
python
Misc.selection_own
(self, **kw)
Become owner of X selection. A keyword parameter selection specifies the name of the selection (default PRIMARY).
Become owner of X selection.
[ "Become", "owner", "of", "X", "selection", "." ]
def selection_own(self, **kw): """Become owner of X selection. A keyword parameter selection specifies the name of the selection (default PRIMARY).""" self.tk.call(('selection', 'own') + self._options(kw) + (self._w,))
[ "def", "selection_own", "(", "self", ",", "*", "*", "kw", ")", ":", "self", ".", "tk", ".", "call", "(", "(", "'selection'", ",", "'own'", ")", "+", "self", ".", "_options", "(", "kw", ")", "+", "(", "self", ".", "_w", ",", ")", ")" ]
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/lib-tk/Tkinter.py#L693-L699
miyosuda/TensorFlowAndroidDemo
35903e0221aa5f109ea2dbef27f20b52e317f42d
jni-build/jni/include/external/bazel_tools/third_party/py/gflags/__init__.py
python
FlagValues.FindModuleIdDefiningFlag
(self, flagname, default=None)
return default
Return the ID of the module defining this flag, or default. Args: flagname: Name of the flag to lookup. default: Value to return if flagname is not defined. Defaults to None. Returns: The ID of the module which registered the flag with this name. If no such module exists (i.e. no flag with this name exists), we return default.
Return the ID of the module defining this flag, or default.
[ "Return", "the", "ID", "of", "the", "module", "defining", "this", "flag", "or", "default", "." ]
def FindModuleIdDefiningFlag(self, flagname, default=None): """Return the ID of the module defining this flag, or default. Args: flagname: Name of the flag to lookup. default: Value to return if flagname is not defined. Defaults to None. Returns: The ID of the module which registered the flag with this name. If no such module exists (i.e. no flag with this name exists), we return default. """ for module_id, flags in self.FlagsByModuleIdDict().iteritems(): for flag in flags: if flag.name == flagname or flag.short_name == flagname: return module_id return default
[ "def", "FindModuleIdDefiningFlag", "(", "self", ",", "flagname", ",", "default", "=", "None", ")", ":", "for", "module_id", ",", "flags", "in", "self", ".", "FlagsByModuleIdDict", "(", ")", ".", "iteritems", "(", ")", ":", "for", "flag", "in", "flags", "...
https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/external/bazel_tools/third_party/py/gflags/__init__.py#L973-L990
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/lib2to3/fixer_util.py
python
find_binding
(name, node, package=None)
return None
Returns the node which binds variable name, otherwise None. If optional argument package is supplied, only imports will be returned. See test cases for examples.
Returns the node which binds variable name, otherwise None. If optional argument package is supplied, only imports will be returned. See test cases for examples.
[ "Returns", "the", "node", "which", "binds", "variable", "name", "otherwise", "None", ".", "If", "optional", "argument", "package", "is", "supplied", "only", "imports", "will", "be", "returned", ".", "See", "test", "cases", "for", "examples", "." ]
def find_binding(name, node, package=None): """ Returns the node which binds variable name, otherwise None. If optional argument package is supplied, only imports will be returned. See test cases for examples.""" for child in node.children: ret = None if child.type == syms.for_stmt: if _find(name, child.children[1]): return child n = find_binding(name, make_suite(child.children[-1]), package) if n: ret = n elif child.type in (syms.if_stmt, syms.while_stmt): n = find_binding(name, make_suite(child.children[-1]), package) if n: ret = n elif child.type == syms.try_stmt: n = find_binding(name, make_suite(child.children[2]), package) if n: ret = n else: for i, kid in enumerate(child.children[3:]): if kid.type == token.COLON and kid.value == ":": # i+3 is the colon, i+4 is the suite n = find_binding(name, make_suite(child.children[i+4]), package) if n: ret = n elif child.type in _def_syms and child.children[1].value == name: ret = child elif _is_import_binding(child, name, package): ret = child elif child.type == syms.simple_stmt: ret = find_binding(name, child, package) elif child.type == syms.expr_stmt: if _find(name, child.children[0]): ret = child if ret: if not package: return ret if is_import(ret): return ret return None
[ "def", "find_binding", "(", "name", ",", "node", ",", "package", "=", "None", ")", ":", "for", "child", "in", "node", ".", "children", ":", "ret", "=", "None", "if", "child", ".", "type", "==", "syms", ".", "for_stmt", ":", "if", "_find", "(", "nam...
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/lib2to3/fixer_util.py#L340-L380
0vercl0k/blazefox
0ffeddfc1de3acb2254c505388e4cf9ab9d1f0a7
src/js/util/make_unicode.py
python
read_unicode_data
(unicode_data)
If you want to understand how this wonderful file format works checkout Unicode Standard Annex #44 - Unicode Character Database http://www.unicode.org/reports/tr44/
If you want to understand how this wonderful file format works checkout Unicode Standard Annex #44 - Unicode Character Database http://www.unicode.org/reports/tr44/
[ "If", "you", "want", "to", "understand", "how", "this", "wonderful", "file", "format", "works", "checkout", "Unicode", "Standard", "Annex", "#44", "-", "Unicode", "Character", "Database", "http", ":", "//", "www", ".", "unicode", ".", "org", "/", "reports", ...
def read_unicode_data(unicode_data): """ If you want to understand how this wonderful file format works checkout Unicode Standard Annex #44 - Unicode Character Database http://www.unicode.org/reports/tr44/ """ reader = csv.reader(unicode_data, delimiter=str(';')) while True: row = next(reader) name = row[1] # We need to expand the UAX #44 4.2.3 Code Point Range if name.startswith('<') and name.endswith('First>'): next_row = next(reader) for i in range(int(row[0], 16), int(next_row[0], 16) + 1): row[0] = i row[1] = name[1:-8] yield row else: row[0] = int(row[0], 16) yield row
[ "def", "read_unicode_data", "(", "unicode_data", ")", ":", "reader", "=", "csv", ".", "reader", "(", "unicode_data", ",", "delimiter", "=", "str", "(", "';'", ")", ")", "while", "True", ":", "row", "=", "next", "(", "reader", ")", "name", "=", "row", ...
https://github.com/0vercl0k/blazefox/blob/0ffeddfc1de3acb2254c505388e4cf9ab9d1f0a7/src/js/util/make_unicode.py#L110-L134
FreeCAD/FreeCAD
ba42231b9c6889b89e064d6d563448ed81e376ec
src/Mod/Draft/draftguitools/gui_trackers.py
python
gridTracker.update
(self)
Redraw the grid.
Redraw the grid.
[ "Redraw", "the", "grid", "." ]
def update(self): """Redraw the grid.""" # Resize the grid to make sure it fits # an exact pair number of main lines numlines = self.numlines // self.mainlines // 2 * 2 * self.mainlines bound = (numlines // 2) * self.space border = (numlines//2 + self.mainlines/2) * self.space cursor = self.mainlines//4 * self.space pts = [] mpts = [] apts = [] cpts = [] for i in range(numlines + 1): curr = -bound + i * self.space z = 0 if i / float(self.mainlines) == i // self.mainlines: if round(curr, 4) == 0: apts.extend([[-bound, curr, z], [bound, curr, z]]) apts.extend([[curr, -bound, z], [curr, bound, z]]) else: mpts.extend([[-bound, curr, z], [bound, curr, z]]) mpts.extend([[curr, -bound, z], [curr, bound, z]]) cpts.extend([[-border,curr,z], [-border+cursor,curr,z]]) cpts.extend([[border-cursor,curr,z], [border,curr,z]]) cpts.extend([[curr,-border,z], [curr,-border+cursor,z]]) cpts.extend([[curr,border-cursor,z], [curr,border,z]]) else: pts.extend([[-bound, curr, z], [bound, curr, z]]) pts.extend([[curr, -bound, z], [curr, bound, z]]) if pts != self.pts: idx = [] midx = [] #aidx = [] cidx = [] for p in range(0, len(pts), 2): idx.append(2) for mp in range(0, len(mpts), 2): midx.append(2) #for ap in range(0, len(apts), 2): # aidx.append(2) for cp in range(0, len(cpts),2): cidx.append(2) if Draft.getParam("gridBorder", True): # extra border border = (numlines//2 + self.mainlines/2) * self.space mpts.extend([[-border, -border, z], [border, -border, z], [border, border, z], [-border, border, z], [-border, -border, z]]) midx.append(5) # cursors mpts.extend(cpts) midx.extend(cidx) # texts self.font.size = self.space*(self.mainlines//4) or 1 self.font.name = Draft.getParam("textfont","Sans") txt = FreeCAD.Units.Quantity(self.space*self.mainlines,FreeCAD.Units.Length).UserString self.text1.string = txt self.text2.string = txt self.textpos1.translation.setValue((-bound+self.space,-border+self.space,z)) self.textpos2.translation.setValue((-bound-self.space,-bound+self.space,z)) else: self.text1.string = " " self.text2.string = " " self.lines1.numVertices.deleteValues(0) self.lines2.numVertices.deleteValues(0) #self.lines3.numVertices.deleteValues(0) self.coords1.point.setValues(pts) self.lines1.numVertices.setValues(idx) self.coords2.point.setValues(mpts) self.lines2.numVertices.setValues(midx) self.coords3.point.setValues(apts) #self.lines3.numVertices.setValues(aidx) self.pts = pts self.displayHumanFigure() self.setAxesColor()
[ "def", "update", "(", "self", ")", ":", "# Resize the grid to make sure it fits", "# an exact pair number of main lines", "numlines", "=", "self", ".", "numlines", "//", "self", ".", "mainlines", "//", "2", "*", "2", "*", "self", ".", "mainlines", "bound", "=", ...
https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Draft/draftguitools/gui_trackers.py#L1057-L1131
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/setuptools/py3/setuptools/_distutils/command/install.py
python
install.convert_paths
(self, *names)
Call `convert_path` over `names`.
Call `convert_path` over `names`.
[ "Call", "convert_path", "over", "names", "." ]
def convert_paths(self, *names): """Call `convert_path` over `names`.""" for name in names: attr = "install_" + name setattr(self, attr, convert_path(getattr(self, attr)))
[ "def", "convert_paths", "(", "self", ",", "*", "names", ")", ":", "for", "name", "in", "names", ":", "attr", "=", "\"install_\"", "+", "name", "setattr", "(", "self", ",", "attr", ",", "convert_path", "(", "getattr", "(", "self", ",", "attr", ")", ")...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/setuptools/py3/setuptools/_distutils/command/install.py#L548-L552
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/ops/math_grad.py
python
_XLog1pyGrad
(op, grad)
Returns gradient of xlog1py(x, y) with respect to x and y.
Returns gradient of xlog1py(x, y) with respect to x and y.
[ "Returns", "gradient", "of", "xlog1py", "(", "x", "y", ")", "with", "respect", "to", "x", "and", "y", "." ]
def _XLog1pyGrad(op, grad): """Returns gradient of xlog1py(x, y) with respect to x and y.""" x = op.inputs[0] y = op.inputs[1] sx = array_ops.shape(x) sy = array_ops.shape(y) rx, ry = gen_array_ops.broadcast_gradient_args(sx, sy) with ops.control_dependencies([grad]): not_zero_x = math_ops.cast( math_ops.not_equal(x, math_ops.cast(0., dtype=x.dtype)), dtype=x.dtype) partial_x = gen_math_ops.xlog1py(not_zero_x, y) partial_y = gen_math_ops.xdivy(x, y + 1.) return (array_ops.reshape(math_ops.reduce_sum(partial_x * grad, rx), sx), array_ops.reshape(math_ops.reduce_sum(partial_y * grad, ry), sy))
[ "def", "_XLog1pyGrad", "(", "op", ",", "grad", ")", ":", "x", "=", "op", ".", "inputs", "[", "0", "]", "y", "=", "op", ".", "inputs", "[", "1", "]", "sx", "=", "array_ops", ".", "shape", "(", "x", ")", "sy", "=", "array_ops", ".", "shape", "(...
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/math_grad.py#L727-L740
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/prompt-toolkit/py3/prompt_toolkit/key_binding/key_processor.py
python
KeyProcessor.feed_multiple
(self, key_presses: List[KeyPress], first: bool = False)
:param first: If true, insert before everything else.
:param first: If true, insert before everything else.
[ ":", "param", "first", ":", "If", "true", "insert", "before", "everything", "else", "." ]
def feed_multiple(self, key_presses: List[KeyPress], first: bool = False) -> None: """ :param first: If true, insert before everything else. """ if first: self.input_queue.extendleft(reversed(key_presses)) else: self.input_queue.extend(key_presses)
[ "def", "feed_multiple", "(", "self", ",", "key_presses", ":", "List", "[", "KeyPress", "]", ",", "first", ":", "bool", "=", "False", ")", "->", "None", ":", "if", "first", ":", "self", ".", "input_queue", ".", "extendleft", "(", "reversed", "(", "key_p...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/prompt-toolkit/py3/prompt_toolkit/key_binding/key_processor.py#L218-L225
ROCmSoftwarePlatform/hipCaffe
4ec5d482515cce532348553b6db6d00d015675d5
python/caffe/io.py
python
Transformer.set_raw_scale
(self, in_, scale)
Set the scale of raw features s.t. the input blob = input * scale. While Python represents images in [0, 1], certain Caffe models like CaffeNet and AlexNet represent images in [0, 255] so the raw_scale of these models must be 255. Parameters ---------- in_ : which input to assign this scale factor scale : scale coefficient
Set the scale of raw features s.t. the input blob = input * scale. While Python represents images in [0, 1], certain Caffe models like CaffeNet and AlexNet represent images in [0, 255] so the raw_scale of these models must be 255.
[ "Set", "the", "scale", "of", "raw", "features", "s", ".", "t", ".", "the", "input", "blob", "=", "input", "*", "scale", ".", "While", "Python", "represents", "images", "in", "[", "0", "1", "]", "certain", "Caffe", "models", "like", "CaffeNet", "and", ...
def set_raw_scale(self, in_, scale): """ Set the scale of raw features s.t. the input blob = input * scale. While Python represents images in [0, 1], certain Caffe models like CaffeNet and AlexNet represent images in [0, 255] so the raw_scale of these models must be 255. Parameters ---------- in_ : which input to assign this scale factor scale : scale coefficient """ self.__check_input(in_) self.raw_scale[in_] = scale
[ "def", "set_raw_scale", "(", "self", ",", "in_", ",", "scale", ")", ":", "self", ".", "__check_input", "(", "in_", ")", "self", ".", "raw_scale", "[", "in_", "]", "=", "scale" ]
https://github.com/ROCmSoftwarePlatform/hipCaffe/blob/4ec5d482515cce532348553b6db6d00d015675d5/python/caffe/io.py#L221-L234
bigartm/bigartm
47e37f982de87aa67bfd475ff1f39da696b181b3
3rdparty/protobuf-3.0.0/python/google/protobuf/internal/well_known_types.py
python
_FieldMaskTree.IntersectPath
(self, path, intersection)
Calculates the intersection part of a field path with this tree. Args: path: The field path to calculates. intersection: The out tree to record the intersection part.
Calculates the intersection part of a field path with this tree.
[ "Calculates", "the", "intersection", "part", "of", "a", "field", "path", "with", "this", "tree", "." ]
def IntersectPath(self, path, intersection): """Calculates the intersection part of a field path with this tree. Args: path: The field path to calculates. intersection: The out tree to record the intersection part. """ node = self._root for name in path.split('.'): if name not in node: return elif not node[name]: intersection.AddPath(path) return node = node[name] intersection.AddLeafNodes(path, node)
[ "def", "IntersectPath", "(", "self", ",", "path", ",", "intersection", ")", ":", "node", "=", "self", ".", "_root", "for", "name", "in", "path", ".", "split", "(", "'.'", ")", ":", "if", "name", "not", "in", "node", ":", "return", "elif", "not", "n...
https://github.com/bigartm/bigartm/blob/47e37f982de87aa67bfd475ff1f39da696b181b3/3rdparty/protobuf-3.0.0/python/google/protobuf/internal/well_known_types.py#L529-L544
y123456yz/reading-and-annotate-mongodb-3.6
93280293672ca7586dc24af18132aa61e4ed7fcf
mongo/src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Builder.py
python
_node_errors
(builder, env, tlist, slist)
Validate that the lists of target and source nodes are legal for this builder and environment. Raise errors or issue warnings as appropriate.
Validate that the lists of target and source nodes are legal for this builder and environment. Raise errors or issue warnings as appropriate.
[ "Validate", "that", "the", "lists", "of", "target", "and", "source", "nodes", "are", "legal", "for", "this", "builder", "and", "environment", ".", "Raise", "errors", "or", "issue", "warnings", "as", "appropriate", "." ]
def _node_errors(builder, env, tlist, slist): """Validate that the lists of target and source nodes are legal for this builder and environment. Raise errors or issue warnings as appropriate. """ # First, figure out if there are any errors in the way the targets # were specified. for t in tlist: if t.side_effect: raise UserError("Multiple ways to build the same target were specified for: %s" % t) if t.has_explicit_builder(): if not t.env is None and not t.env is env: action = t.builder.action t_contents = t.builder.action.get_contents(tlist, slist, t.env) contents = builder.action.get_contents(tlist, slist, env) if t_contents == contents: msg = "Two different environments were specified for target %s,\n\tbut they appear to have the same action: %s" % (t, action.genstring(tlist, slist, t.env)) SCons.Warnings.warn(SCons.Warnings.DuplicateEnvironmentWarning, msg) else: msg = "Two environments with different actions were specified for the same target: %s\n(action 1: %s)\n(action 2: %s)" % (t,t_contents,contents) raise UserError(msg) if builder.multi: if t.builder != builder: msg = "Two different builders (%s and %s) were specified for the same target: %s" % (t.builder.get_name(env), builder.get_name(env), t) raise UserError(msg) # TODO(batch): list constructed each time! if t.get_executor().get_all_targets() != tlist: msg = "Two different target lists have a target in common: %s (from %s and from %s)" % (t, list(map(str, t.get_executor().get_all_targets())), list(map(str, tlist))) raise UserError(msg) elif t.sources != slist: msg = "Multiple ways to build the same target were specified for: %s (from %s and from %s)" % (t, list(map(str, t.sources)), list(map(str, slist))) raise UserError(msg) if builder.single_source: if len(slist) > 1: raise UserError("More than one source given for single-source builder: targets=%s sources=%s" % (list(map(str,tlist)), list(map(str,slist))))
[ "def", "_node_errors", "(", "builder", ",", "env", ",", "tlist", ",", "slist", ")", ":", "# First, figure out if there are any errors in the way the targets", "# were specified.", "for", "t", "in", "tlist", ":", "if", "t", ".", "side_effect", ":", "raise", "UserErro...
https://github.com/y123456yz/reading-and-annotate-mongodb-3.6/blob/93280293672ca7586dc24af18132aa61e4ed7fcf/mongo/src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Builder.py#L281-L318
qgis/QGIS
15a77662d4bb712184f6aa60d0bd663010a76a75
python/core/additions/qgssettings.py
python
_qgssettings_enum_value
(self, key, enumDefaultValue, section=QgsSettings.NoSection)
return enu_val
Return the setting value for a setting based on an enum. This forces the output to be a valid and existing entry of the enum. Hence if the setting value is incorrect, the given default value is returned. :param self: the QgsSettings object :param key: the setting key :param enumDefaultValue: the default value as an enum value :param section: optional section :return: the setting value .. note:: The enum needs to be declared with Q_ENUM.
Return the setting value for a setting based on an enum. This forces the output to be a valid and existing entry of the enum. Hence if the setting value is incorrect, the given default value is returned.
[ "Return", "the", "setting", "value", "for", "a", "setting", "based", "on", "an", "enum", ".", "This", "forces", "the", "output", "to", "be", "a", "valid", "and", "existing", "entry", "of", "the", "enum", ".", "Hence", "if", "the", "setting", "value", "...
def _qgssettings_enum_value(self, key, enumDefaultValue, section=QgsSettings.NoSection): """ Return the setting value for a setting based on an enum. This forces the output to be a valid and existing entry of the enum. Hence if the setting value is incorrect, the given default value is returned. :param self: the QgsSettings object :param key: the setting key :param enumDefaultValue: the default value as an enum value :param section: optional section :return: the setting value .. note:: The enum needs to be declared with Q_ENUM. """ meta_enum = metaEnumFromValue(enumDefaultValue) if meta_enum is None or not meta_enum.isValid(): # this should not happen raise ValueError("could not get the meta enum for given enum default value (type: {})" .format(enumDefaultValue.__class__)) str_val = self.value(key, meta_enum.valueToKey(enumDefaultValue), str, section) # need a new meta enum as QgsSettings.value is making a copy and leads to seg fault (probably a PyQt issue) meta_enum_2 = metaEnumFromValue(enumDefaultValue) (enu_val, ok) = meta_enum_2.keyToValue(str_val) if not ok: enu_val = enumDefaultValue else: # cast to the enum class enu_val = enumDefaultValue.__class__(enu_val) return enu_val
[ "def", "_qgssettings_enum_value", "(", "self", ",", "key", ",", "enumDefaultValue", ",", "section", "=", "QgsSettings", ".", "NoSection", ")", ":", "meta_enum", "=", "metaEnumFromValue", "(", "enumDefaultValue", ")", "if", "meta_enum", "is", "None", "or", "not",...
https://github.com/qgis/QGIS/blob/15a77662d4bb712184f6aa60d0bd663010a76a75/python/core/additions/qgssettings.py#L25-L58
eyllanesc/stackoverflow
3837cc9ff94541bf5a500aac1b6182f53669537d
questions/55241644/fakeuic/__init__.py
python
compileUi
(uifile, pyfile, execute=False, indent=4, from_imports=False, resource_suffix='_rc', import_from='.')
compileUi(uifile, pyfile, execute=False, indent=4, from_imports=False, resource_suffix='_rc', import_from='.') Creates a Python module from a Qt Designer .ui file. uifile is a file name or file-like object containing the .ui file. pyfile is the file-like object to which the Python code will be written to. execute is optionally set to generate extra Python code that allows the code to be run as a standalone application. The default is False. indent is the optional indentation width using spaces. If it is 0 then a tab is used. The default is 4. from_imports is optionally set to generate relative import statements. At the moment this only applies to the import of resource modules. resource_suffix is the suffix appended to the basename of any resource file specified in the .ui file to create the name of the Python module generated from the resource file by pyrcc4. The default is '_rc', i.e. if the .ui file specified a resource file called foo.qrc then the corresponding Python module is foo_rc. import_from is optionally set to the package used for relative import statements. The default is ``'.'``.
compileUi(uifile, pyfile, execute=False, indent=4, from_imports=False, resource_suffix='_rc', import_from='.')
[ "compileUi", "(", "uifile", "pyfile", "execute", "=", "False", "indent", "=", "4", "from_imports", "=", "False", "resource_suffix", "=", "_rc", "import_from", "=", ".", ")" ]
def compileUi(uifile, pyfile, execute=False, indent=4, from_imports=False, resource_suffix='_rc', import_from='.'): """compileUi(uifile, pyfile, execute=False, indent=4, from_imports=False, resource_suffix='_rc', import_from='.') Creates a Python module from a Qt Designer .ui file. uifile is a file name or file-like object containing the .ui file. pyfile is the file-like object to which the Python code will be written to. execute is optionally set to generate extra Python code that allows the code to be run as a standalone application. The default is False. indent is the optional indentation width using spaces. If it is 0 then a tab is used. The default is 4. from_imports is optionally set to generate relative import statements. At the moment this only applies to the import of resource modules. resource_suffix is the suffix appended to the basename of any resource file specified in the .ui file to create the name of the Python module generated from the resource file by pyrcc4. The default is '_rc', i.e. if the .ui file specified a resource file called foo.qrc then the corresponding Python module is foo_rc. import_from is optionally set to the package used for relative import statements. The default is ``'.'``. """ from PySide2.QtCore import PYQT_VERSION_STR try: uifname = uifile.name except AttributeError: uifname = uifile indenter.indentwidth = indent pyfile.write(_header % (uifname, PYQT_VERSION_STR)) winfo = compiler.UICompiler().compileUi(uifile, pyfile, from_imports, resource_suffix, import_from) if execute: indenter.write_code(_display_code % winfo)
[ "def", "compileUi", "(", "uifile", ",", "pyfile", ",", "execute", "=", "False", ",", "indent", "=", "4", ",", "from_imports", "=", "False", ",", "resource_suffix", "=", "'_rc'", ",", "import_from", "=", "'.'", ")", ":", "from", "PySide2", ".", "QtCore", ...
https://github.com/eyllanesc/stackoverflow/blob/3837cc9ff94541bf5a500aac1b6182f53669537d/questions/55241644/fakeuic/__init__.py#L131-L167
microsoft/TSS.MSR
0f2516fca2cd9929c31d5450e39301c9bde43688
TSS.Py/src/TpmTypes.py
python
TPM2_SequenceComplete_REQUEST.__init__
(self, sequenceHandle = TPM_HANDLE(), buffer = None, hierarchy = TPM_HANDLE())
This command adds the last part of data, if any, to a hash/HMAC sequence and returns the result. Attributes: sequenceHandle (TPM_HANDLE): Authorization for the sequence Auth Index: 1 Auth Role: USER buffer (bytes): Data to be added to the hash/HMAC hierarchy (TPM_HANDLE): Hierarchy of the ticket for a hash
This command adds the last part of data, if any, to a hash/HMAC sequence and returns the result.
[ "This", "command", "adds", "the", "last", "part", "of", "data", "if", "any", "to", "a", "hash", "/", "HMAC", "sequence", "and", "returns", "the", "result", "." ]
def __init__(self, sequenceHandle = TPM_HANDLE(), buffer = None, hierarchy = TPM_HANDLE()): """ This command adds the last part of data, if any, to a hash/HMAC sequence and returns the result. Attributes: sequenceHandle (TPM_HANDLE): Authorization for the sequence Auth Index: 1 Auth Role: USER buffer (bytes): Data to be added to the hash/HMAC hierarchy (TPM_HANDLE): Hierarchy of the ticket for a hash """ self.sequenceHandle = sequenceHandle self.buffer = buffer self.hierarchy = hierarchy
[ "def", "__init__", "(", "self", ",", "sequenceHandle", "=", "TPM_HANDLE", "(", ")", ",", "buffer", "=", "None", ",", "hierarchy", "=", "TPM_HANDLE", "(", ")", ")", ":", "self", ".", "sequenceHandle", "=", "sequenceHandle", "self", ".", "buffer", "=", "bu...
https://github.com/microsoft/TSS.MSR/blob/0f2516fca2cd9929c31d5450e39301c9bde43688/TSS.Py/src/TpmTypes.py#L12198-L12211
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/dataview.py
python
DataViewCtrl.EnsureVisible
(*args, **kwargs)
return _dataview.DataViewCtrl_EnsureVisible(*args, **kwargs)
EnsureVisible(self, DataViewItem item, DataViewColumn column=None)
EnsureVisible(self, DataViewItem item, DataViewColumn column=None)
[ "EnsureVisible", "(", "self", "DataViewItem", "item", "DataViewColumn", "column", "=", "None", ")" ]
def EnsureVisible(*args, **kwargs): """EnsureVisible(self, DataViewItem item, DataViewColumn column=None)""" return _dataview.DataViewCtrl_EnsureVisible(*args, **kwargs)
[ "def", "EnsureVisible", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_dataview", ".", "DataViewCtrl_EnsureVisible", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/dataview.py#L1811-L1813
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/urllib3/util/ssl_.py
python
create_urllib3_context
( ssl_version=None, cert_reqs=None, options=None, ciphers=None )
return context
All arguments have the same meaning as ``ssl_wrap_socket``. By default, this function does a lot of the same work that ``ssl.create_default_context`` does on Python 3.4+. It: - Disables SSLv2, SSLv3, and compression - Sets a restricted set of server ciphers If you wish to enable SSLv3, you can do:: from pip._vendor.urllib3.util import ssl_ context = ssl_.create_urllib3_context() context.options &= ~ssl_.OP_NO_SSLv3 You can do the same to enable compression (substituting ``COMPRESSION`` for ``SSLv3`` in the last line above). :param ssl_version: The desired protocol version to use. This will default to PROTOCOL_SSLv23 which will negotiate the highest protocol that both the server and your installation of OpenSSL support. :param cert_reqs: Whether to require the certificate verification. This defaults to ``ssl.CERT_REQUIRED``. :param options: Specific OpenSSL options. These default to ``ssl.OP_NO_SSLv2``, ``ssl.OP_NO_SSLv3``, ``ssl.OP_NO_COMPRESSION``, and ``ssl.OP_NO_TICKET``. :param ciphers: Which cipher suites to allow the server to select. :returns: Constructed SSLContext object with specified options :rtype: SSLContext
All arguments have the same meaning as ``ssl_wrap_socket``.
[ "All", "arguments", "have", "the", "same", "meaning", "as", "ssl_wrap_socket", "." ]
def create_urllib3_context( ssl_version=None, cert_reqs=None, options=None, ciphers=None ): """All arguments have the same meaning as ``ssl_wrap_socket``. By default, this function does a lot of the same work that ``ssl.create_default_context`` does on Python 3.4+. It: - Disables SSLv2, SSLv3, and compression - Sets a restricted set of server ciphers If you wish to enable SSLv3, you can do:: from pip._vendor.urllib3.util import ssl_ context = ssl_.create_urllib3_context() context.options &= ~ssl_.OP_NO_SSLv3 You can do the same to enable compression (substituting ``COMPRESSION`` for ``SSLv3`` in the last line above). :param ssl_version: The desired protocol version to use. This will default to PROTOCOL_SSLv23 which will negotiate the highest protocol that both the server and your installation of OpenSSL support. :param cert_reqs: Whether to require the certificate verification. This defaults to ``ssl.CERT_REQUIRED``. :param options: Specific OpenSSL options. These default to ``ssl.OP_NO_SSLv2``, ``ssl.OP_NO_SSLv3``, ``ssl.OP_NO_COMPRESSION``, and ``ssl.OP_NO_TICKET``. :param ciphers: Which cipher suites to allow the server to select. :returns: Constructed SSLContext object with specified options :rtype: SSLContext """ context = SSLContext(ssl_version or PROTOCOL_TLS) context.set_ciphers(ciphers or DEFAULT_CIPHERS) # Setting the default here, as we may have no ssl module on import cert_reqs = ssl.CERT_REQUIRED if cert_reqs is None else cert_reqs if options is None: options = 0 # SSLv2 is easily broken and is considered harmful and dangerous options |= OP_NO_SSLv2 # SSLv3 has several problems and is now dangerous options |= OP_NO_SSLv3 # Disable compression to prevent CRIME attacks for OpenSSL 1.0+ # (issue #309) options |= OP_NO_COMPRESSION # TLSv1.2 only. Unless set explicitly, do not request tickets. # This may save some bandwidth on wire, and although the ticket is encrypted, # there is a risk associated with it being on wire, # if the server is not rotating its ticketing keys properly. options |= OP_NO_TICKET context.options |= options # Enable post-handshake authentication for TLS 1.3, see GH #1634. PHA is # necessary for conditional client cert authentication with TLS 1.3. # The attribute is None for OpenSSL <= 1.1.0 or does not exist in older # versions of Python. We only enable on Python 3.7.4+ or if certificate # verification is enabled to work around Python issue #37428 # See: https://bugs.python.org/issue37428 if (cert_reqs == ssl.CERT_REQUIRED or sys.version_info >= (3, 7, 4)) and getattr( context, "post_handshake_auth", None ) is not None: context.post_handshake_auth = True context.verify_mode = cert_reqs if ( getattr(context, "check_hostname", None) is not None ): # Platform-specific: Python 3.2 # We do our own verification, including fingerprints and alternative # hostnames. So disable it here context.check_hostname = False # Enable logging of TLS session keys via defacto standard environment variable # 'SSLKEYLOGFILE', if the feature is available (Python 3.8+). Skip empty values. if hasattr(context, "keylog_filename"): sslkeylogfile = os.environ.get("SSLKEYLOGFILE") if sslkeylogfile: context.keylog_filename = sslkeylogfile return context
[ "def", "create_urllib3_context", "(", "ssl_version", "=", "None", ",", "cert_reqs", "=", "None", ",", "options", "=", "None", ",", "ciphers", "=", "None", ")", ":", "context", "=", "SSLContext", "(", "ssl_version", "or", "PROTOCOL_TLS", ")", "context", ".", ...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/urllib3/util/ssl_.py#L489-L661
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/AWSPythonSDK/1.5.8/botocore/vendored/requests/models.py
python
Response.is_permanent_redirect
(self)
return ('location' in self.headers and self.status_code in (codes.moved_permanently, codes.permanent_redirect))
True if this Response one of the permanant versions of redirect
True if this Response one of the permanant versions of redirect
[ "True", "if", "this", "Response", "one", "of", "the", "permanant", "versions", "of", "redirect" ]
def is_permanent_redirect(self): """True if this Response one of the permanant versions of redirect""" return ('location' in self.headers and self.status_code in (codes.moved_permanently, codes.permanent_redirect))
[ "def", "is_permanent_redirect", "(", "self", ")", ":", "return", "(", "'location'", "in", "self", ".", "headers", "and", "self", ".", "status_code", "in", "(", "codes", ".", "moved_permanently", ",", "codes", ".", "permanent_redirect", ")", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/AWSPythonSDK/1.5.8/botocore/vendored/requests/models.py#L650-L652
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/klampt/robotsim.py
python
RobotModel.velocityFromDrivers
(self, driverVelocities: Vector)
return _robotsim.RobotModel_velocityFromDrivers(self, driverVelocities)
r""" Converts a list of driver velocities (length numDrivers()) to a full velocity vector (length numLinks()). Args: driverVelocities (:obj:`list of floats`)
r""" Converts a list of driver velocities (length numDrivers()) to a full velocity vector (length numLinks()).
[ "r", "Converts", "a", "list", "of", "driver", "velocities", "(", "length", "numDrivers", "()", ")", "to", "a", "full", "velocity", "vector", "(", "length", "numLinks", "()", ")", "." ]
def velocityFromDrivers(self, driverVelocities: Vector) ->None: r""" Converts a list of driver velocities (length numDrivers()) to a full velocity vector (length numLinks()). Args: driverVelocities (:obj:`list of floats`) """ return _robotsim.RobotModel_velocityFromDrivers(self, driverVelocities)
[ "def", "velocityFromDrivers", "(", "self", ",", "driverVelocities", ":", "Vector", ")", "->", "None", ":", "return", "_robotsim", ".", "RobotModel_velocityFromDrivers", "(", "self", ",", "driverVelocities", ")" ]
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/robotsim.py#L5155-L5163
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/scipy/optimize/optimize.py
python
rosen_der
(x)
return der
The derivative (i.e. gradient) of the Rosenbrock function. Parameters ---------- x : array_like 1-D array of points at which the derivative is to be computed. Returns ------- rosen_der : (N,) ndarray The gradient of the Rosenbrock function at `x`. See Also -------- rosen, rosen_hess, rosen_hess_prod
The derivative (i.e. gradient) of the Rosenbrock function.
[ "The", "derivative", "(", "i", ".", "e", ".", "gradient", ")", "of", "the", "Rosenbrock", "function", "." ]
def rosen_der(x): """ The derivative (i.e. gradient) of the Rosenbrock function. Parameters ---------- x : array_like 1-D array of points at which the derivative is to be computed. Returns ------- rosen_der : (N,) ndarray The gradient of the Rosenbrock function at `x`. See Also -------- rosen, rosen_hess, rosen_hess_prod """ x = asarray(x) xm = x[1:-1] xm_m1 = x[:-2] xm_p1 = x[2:] der = numpy.zeros_like(x) der[1:-1] = (200 * (xm - xm_m1**2) - 400 * (xm_p1 - xm**2) * xm - 2 * (1 - xm)) der[0] = -400 * x[0] * (x[1] - x[0]**2) - 2 * (1 - x[0]) der[-1] = 200 * (x[-1] - x[-2]**2) return der
[ "def", "rosen_der", "(", "x", ")", ":", "x", "=", "asarray", "(", "x", ")", "xm", "=", "x", "[", "1", ":", "-", "1", "]", "xm_m1", "=", "x", "[", ":", "-", "2", "]", "xm_p1", "=", "x", "[", "2", ":", "]", "der", "=", "numpy", ".", "zero...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/scipy/optimize/optimize.py#L193-L221
rtbkit/rtbkit
502d06acc3f8d90438946b6ae742190f2f4b4fbb
jml-build/jmlbuild.py
python
next_line
(stream)
return result
Returns the next line that needs parsing. The returned line is guaranteed to be striped of leading and trailing white spaces. We also ensure that a line broken up by the \ character will be returned as a single line.
Returns the next line that needs parsing. The returned line is guaranteed to be striped of leading and trailing white spaces. We also ensure that a line broken up by the \ character will be returned as a single line.
[ "Returns", "the", "next", "line", "that", "needs", "parsing", ".", "The", "returned", "line", "is", "guaranteed", "to", "be", "striped", "of", "leading", "and", "trailing", "white", "spaces", ".", "We", "also", "ensure", "that", "a", "line", "broken", "up"...
def next_line(stream): """ Returns the next line that needs parsing. The returned line is guaranteed to be striped of leading and trailing white spaces. We also ensure that a line broken up by the \ character will be returned as a single line. """ result = "" while True: line = stream.readline() if len(line) == 0: break line = strip_line(line) # Continue on empty line only if we don't have anything. This is a # workaround for having a trailing slash at the end of a variable # definition. if len(line) == 0: if len(result) == 0: continue else: break if len(result) > 0: result += " " # read the next line if we have a trailing slash. if line[-1] == "\\": result += strip_line(line[:-1]) continue result += line break if len(result) == 0: print_dbg("\tEOF") return None print_dbg("\tline: " + result) return result
[ "def", "next_line", "(", "stream", ")", ":", "result", "=", "\"\"", "while", "True", ":", "line", "=", "stream", ".", "readline", "(", ")", "if", "len", "(", "line", ")", "==", "0", ":", "break", "line", "=", "strip_line", "(", "line", ")", "# Cont...
https://github.com/rtbkit/rtbkit/blob/502d06acc3f8d90438946b6ae742190f2f4b4fbb/jml-build/jmlbuild.py#L171-L207
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/richtext.py
python
RichTextCtrl.SetInternalSelectionRange
(*args, **kwargs)
return _richtext.RichTextCtrl_SetInternalSelectionRange(*args, **kwargs)
SetInternalSelectionRange(self, RichTextRange range) Set the selection range in character positions. The range is in internal format, i.e. a single character selection is denoted by (n,n).
SetInternalSelectionRange(self, RichTextRange range)
[ "SetInternalSelectionRange", "(", "self", "RichTextRange", "range", ")" ]
def SetInternalSelectionRange(*args, **kwargs): """ SetInternalSelectionRange(self, RichTextRange range) Set the selection range in character positions. The range is in internal format, i.e. a single character selection is denoted by (n,n). """ return _richtext.RichTextCtrl_SetInternalSelectionRange(*args, **kwargs)
[ "def", "SetInternalSelectionRange", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_richtext", ".", "RichTextCtrl_SetInternalSelectionRange", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/richtext.py#L3682-L3689
openvinotoolkit/openvino
dedcbeafa8b84cccdc55ca64b8da516682b381c7
tools/mo/openvino/tools/mo/utils/model_analysis.py
python
AnalyzeAction.run_after
(self)
return [LoadFinish]
Returns list of replacer classes which this replacer must be run after. :return: list of classes
Returns list of replacer classes which this replacer must be run after. :return: list of classes
[ "Returns", "list", "of", "replacer", "classes", "which", "this", "replacer", "must", "be", "run", "after", ".", ":", "return", ":", "list", "of", "classes" ]
def run_after(self): """ Returns list of replacer classes which this replacer must be run after. :return: list of classes """ return [LoadFinish]
[ "def", "run_after", "(", "self", ")", ":", "return", "[", "LoadFinish", "]" ]
https://github.com/openvinotoolkit/openvino/blob/dedcbeafa8b84cccdc55ca64b8da516682b381c7/tools/mo/openvino/tools/mo/utils/model_analysis.py#L90-L95
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/ultimatelistctrl.py
python
UltimateListTextCtrl.AcceptChanges
(self)
return True
Accepts/refuses the changes made by the user.
Accepts/refuses the changes made by the user.
[ "Accepts", "/", "refuses", "the", "changes", "made", "by", "the", "user", "." ]
def AcceptChanges(self): """ Accepts/refuses the changes made by the user. """ value = self.GetValue() if value == self._startValue: # nothing changed, always accept # when an item remains unchanged, the owner # needs to be notified that the user decided # not to change the tree item label, and that # the edit has been cancelled self._owner.OnRenameCancelled(self._itemEdited) return True if not self._owner.OnRenameAccept(self._itemEdited, value): # vetoed by the user return False # accepted, do rename the item self._owner.SetItemText(self._itemEdited, value) if value.count("\n") != self._startValue.count("\n"): self._owner.ResetLineDimensions() self._owner.Refresh() return True
[ "def", "AcceptChanges", "(", "self", ")", ":", "value", "=", "self", ".", "GetValue", "(", ")", "if", "value", "==", "self", ".", "_startValue", ":", "# nothing changed, always accept", "# when an item remains unchanged, the owner", "# needs to be notified that the user d...
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/ultimatelistctrl.py#L5815-L5840
learnforpractice/pyeos
4f04eb982c86c1fdb413084af77c713a6fda3070
libraries/vm/vm_cpython_ss/lib/codecs.py
python
Codec.decode
(self, input, errors='strict')
Decodes the object input and returns a tuple (output object, length consumed). input must be an object which provides the bf_getreadbuf buffer slot. Python strings, buffer objects and memory mapped files are examples of objects providing this slot. errors defines the error handling to apply. It defaults to 'strict' handling. The method may not store state in the Codec instance. Use StreamReader for codecs which have to keep state in order to make decoding efficient. The decoder must be able to handle zero length input and return an empty object of the output object type in this situation.
Decodes the object input and returns a tuple (output object, length consumed).
[ "Decodes", "the", "object", "input", "and", "returns", "a", "tuple", "(", "output", "object", "length", "consumed", ")", "." ]
def decode(self, input, errors='strict'): """ Decodes the object input and returns a tuple (output object, length consumed). input must be an object which provides the bf_getreadbuf buffer slot. Python strings, buffer objects and memory mapped files are examples of objects providing this slot. errors defines the error handling to apply. It defaults to 'strict' handling. The method may not store state in the Codec instance. Use StreamReader for codecs which have to keep state in order to make decoding efficient. The decoder must be able to handle zero length input and return an empty object of the output object type in this situation. """ raise NotImplementedError
[ "def", "decode", "(", "self", ",", "input", ",", "errors", "=", "'strict'", ")", ":", "raise", "NotImplementedError" ]
https://github.com/learnforpractice/pyeos/blob/4f04eb982c86c1fdb413084af77c713a6fda3070/libraries/vm/vm_cpython_ss/lib/codecs.py#L156-L177
hughperkins/tf-coriander
970d3df6c11400ad68405f22b0c42a52374e94ca
tensorflow/python/training/supervisor.py
python
Supervisor.start_queue_runners
(self, sess, queue_runners=None)
return threads
Start threads for `QueueRunners`. Note that the queue runners collected in the graph key `QUEUE_RUNNERS` are already started automatically when you create a session with the supervisor, so unless you have non-collected queue runners to start you do not need to call this explicitly. Args: sess: A `Session`. queue_runners: A list of `QueueRunners`. If not specified, we'll use the list of queue runners gathered in the graph under the key `GraphKeys.QUEUE_RUNNERS`. Returns: The list of threads started for the `QueueRunners`.
Start threads for `QueueRunners`.
[ "Start", "threads", "for", "QueueRunners", "." ]
def start_queue_runners(self, sess, queue_runners=None): """Start threads for `QueueRunners`. Note that the queue runners collected in the graph key `QUEUE_RUNNERS` are already started automatically when you create a session with the supervisor, so unless you have non-collected queue runners to start you do not need to call this explicitly. Args: sess: A `Session`. queue_runners: A list of `QueueRunners`. If not specified, we'll use the list of queue runners gathered in the graph under the key `GraphKeys.QUEUE_RUNNERS`. Returns: The list of threads started for the `QueueRunners`. """ if queue_runners is None: queue_runners = self._graph.get_collection(ops.GraphKeys.QUEUE_RUNNERS) threads = [] for qr in queue_runners: threads.extend(qr.create_threads(sess, coord=self._coord, daemon=True, start=True)) return threads
[ "def", "start_queue_runners", "(", "self", ",", "sess", ",", "queue_runners", "=", "None", ")", ":", "if", "queue_runners", "is", "None", ":", "queue_runners", "=", "self", ".", "_graph", ".", "get_collection", "(", "ops", ".", "GraphKeys", ".", "QUEUE_RUNNE...
https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/python/training/supervisor.py#L732-L755
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/ops/summary_ops_v2.py
python
audio
(name, tensor, sample_rate, max_outputs, family=None, step=None)
return summary_writer_function(name, tensor, function, family=family)
Writes an audio summary if possible.
Writes an audio summary if possible.
[ "Writes", "an", "audio", "summary", "if", "possible", "." ]
def audio(name, tensor, sample_rate, max_outputs, family=None, step=None): """Writes an audio summary if possible.""" def function(tag, scope): # Note the identity to move the tensor to the CPU. return gen_summary_ops.write_audio_summary( _summary_state.writer._resource, # pylint: disable=protected-access _choose_step(step), tag, array_ops.identity(tensor), sample_rate=sample_rate, max_outputs=max_outputs, name=scope) return summary_writer_function(name, tensor, function, family=family)
[ "def", "audio", "(", "name", ",", "tensor", ",", "sample_rate", ",", "max_outputs", ",", "family", "=", "None", ",", "step", "=", "None", ")", ":", "def", "function", "(", "tag", ",", "scope", ")", ":", "# Note the identity to move the tensor to the CPU.", "...
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/summary_ops_v2.py#L948-L962
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/AWSPythonSDK/1.5.8/docutils/utils/math/math2html.py
python
Trace.error
(cls, message)
Show an error message
Show an error message
[ "Show", "an", "error", "message" ]
def error(cls, message): "Show an error message" message = '* ' + message if Trace.prefix and Trace.showlinesmode: message = Trace.prefix + message Trace.show(message, sys.stderr)
[ "def", "error", "(", "cls", ",", "message", ")", ":", "message", "=", "'* '", "+", "message", "if", "Trace", ".", "prefix", "and", "Trace", ".", "showlinesmode", ":", "message", "=", "Trace", ".", "prefix", "+", "message", "Trace", ".", "show", "(", ...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/AWSPythonSDK/1.5.8/docutils/utils/math/math2html.py#L51-L56
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/ops/sparse_grad.py
python
_SparseSoftmaxGrad
(op, grad)
return [None, grad_x, None]
Gradients for SparseSoftmax. The calculation is the same as SoftmaxGrad: grad_x = grad_softmax * softmax - sum(grad_softmax * softmax) * softmax where we now only operate on the non-zero values present in the SparseTensors. Args: op: the SparseSoftmax op. grad: the upstream gradient w.r.t. the non-zero SparseSoftmax output values. Returns: Gradients w.r.t. the input (sp_indices, sp_values, sp_shape).
Gradients for SparseSoftmax.
[ "Gradients", "for", "SparseSoftmax", "." ]
def _SparseSoftmaxGrad(op, grad): """Gradients for SparseSoftmax. The calculation is the same as SoftmaxGrad: grad_x = grad_softmax * softmax - sum(grad_softmax * softmax) * softmax where we now only operate on the non-zero values present in the SparseTensors. Args: op: the SparseSoftmax op. grad: the upstream gradient w.r.t. the non-zero SparseSoftmax output values. Returns: Gradients w.r.t. the input (sp_indices, sp_values, sp_shape). """ indices, shape = op.inputs[0], op.inputs[2] out_vals = op.outputs[0] sp_output = sparse_tensor.SparseTensor(indices, out_vals, shape) sp_grad = sparse_tensor.SparseTensor(indices, grad, shape) sp_product = sparse_tensor.SparseTensor(indices, sp_output.values * sp_grad.values, shape) # [..., B, 1], dense. sum_reduced = -sparse_ops.sparse_reduce_sum(sp_product, [-1], keepdims=True) # sparse [..., B, C] + dense [..., B, 1] with broadcast; outputs sparse. sp_sum = sparse_ops.sparse_dense_cwise_add(sp_grad, sum_reduced) grad_x = sp_sum.values * sp_output.values return [None, grad_x, None]
[ "def", "_SparseSoftmaxGrad", "(", "op", ",", "grad", ")", ":", "indices", ",", "shape", "=", "op", ".", "inputs", "[", "0", "]", ",", "op", ".", "inputs", "[", "2", "]", "out_vals", "=", "op", ".", "outputs", "[", "0", "]", "sp_output", "=", "spa...
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/sparse_grad.py#L284-L314
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scikit-learn/py3/sklearn/linear_model/_omp.py
python
OrthogonalMatchingPursuit.fit
(self, X, y)
return self
Fit the model using X, y as training data. Parameters ---------- X : array-like, shape (n_samples, n_features) Training data. y : array-like, shape (n_samples,) or (n_samples, n_targets) Target values. Will be cast to X's dtype if necessary Returns ------- self : object returns an instance of self.
Fit the model using X, y as training data.
[ "Fit", "the", "model", "using", "X", "y", "as", "training", "data", "." ]
def fit(self, X, y): """Fit the model using X, y as training data. Parameters ---------- X : array-like, shape (n_samples, n_features) Training data. y : array-like, shape (n_samples,) or (n_samples, n_targets) Target values. Will be cast to X's dtype if necessary Returns ------- self : object returns an instance of self. """ X, y = check_X_y(X, y, multi_output=True, y_numeric=True) n_features = X.shape[1] X, y, X_offset, y_offset, X_scale, Gram, Xy = \ _pre_fit(X, y, None, self.precompute, self.normalize, self.fit_intercept, copy=True) if y.ndim == 1: y = y[:, np.newaxis] if self.n_nonzero_coefs is None and self.tol is None: # default for n_nonzero_coefs is 0.1 * n_features # but at least one. self.n_nonzero_coefs_ = max(int(0.1 * n_features), 1) else: self.n_nonzero_coefs_ = self.n_nonzero_coefs if Gram is False: coef_, self.n_iter_ = orthogonal_mp( X, y, self.n_nonzero_coefs_, self.tol, precompute=False, copy_X=True, return_n_iter=True) else: norms_sq = np.sum(y ** 2, axis=0) if self.tol is not None else None coef_, self.n_iter_ = orthogonal_mp_gram( Gram, Xy=Xy, n_nonzero_coefs=self.n_nonzero_coefs_, tol=self.tol, norms_squared=norms_sq, copy_Gram=True, copy_Xy=True, return_n_iter=True) self.coef_ = coef_.T self._set_intercept(X_offset, y_offset, X_scale) return self
[ "def", "fit", "(", "self", ",", "X", ",", "y", ")", ":", "X", ",", "y", "=", "check_X_y", "(", "X", ",", "y", ",", "multi_output", "=", "True", ",", "y_numeric", "=", "True", ")", "n_features", "=", "X", ".", "shape", "[", "1", "]", "X", ",",...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py3/sklearn/linear_model/_omp.py#L627-L676
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/python/framework/meta_graph.py
python
read_meta_graph_file
(filename)
return meta_graph_def
Reads a file containing `MetaGraphDef` and returns the protocol buffer. Args: filename: `meta_graph_def` filename including the path. Returns: A `MetaGraphDef` protocol buffer. Raises: IOError: If the file doesn't exist, or cannot be successfully parsed.
Reads a file containing `MetaGraphDef` and returns the protocol buffer.
[ "Reads", "a", "file", "containing", "MetaGraphDef", "and", "returns", "the", "protocol", "buffer", "." ]
def read_meta_graph_file(filename): """Reads a file containing `MetaGraphDef` and returns the protocol buffer. Args: filename: `meta_graph_def` filename including the path. Returns: A `MetaGraphDef` protocol buffer. Raises: IOError: If the file doesn't exist, or cannot be successfully parsed. """ meta_graph_def = meta_graph_pb2.MetaGraphDef() if not file_io.file_exists(filename): raise IOError("File %s does not exist." % filename) # First try to read it as a binary file. file_content = file_io.FileIO(filename, "rb").read() try: meta_graph_def.ParseFromString(file_content) return meta_graph_def except Exception: # pylint: disable=broad-except pass # Next try to read it as a text file. try: text_format.Merge(file_content.decode("utf-8"), meta_graph_def) except text_format.ParseError as e: raise IOError("Cannot parse file %s: %s." % (filename, str(e))) return meta_graph_def
[ "def", "read_meta_graph_file", "(", "filename", ")", ":", "meta_graph_def", "=", "meta_graph_pb2", ".", "MetaGraphDef", "(", ")", "if", "not", "file_io", ".", "file_exists", "(", "filename", ")", ":", "raise", "IOError", "(", "\"File %s does not exist.\"", "%", ...
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/framework/meta_graph.py#L541-L570
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/smtplib.py
python
SMTP.help
(self, args='')
return self.getreply()[1]
SMTP 'help' command. Returns help text from server.
SMTP 'help' command. Returns help text from server.
[ "SMTP", "help", "command", ".", "Returns", "help", "text", "from", "server", "." ]
def help(self, args=''): """SMTP 'help' command. Returns help text from server.""" self.putcmd("help", args) return self.getreply()[1]
[ "def", "help", "(", "self", ",", "args", "=", "''", ")", ":", "self", ".", "putcmd", "(", "\"help\"", ",", "args", ")", "return", "self", ".", "getreply", "(", ")", "[", "1", "]" ]
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/smtplib.py#L453-L457
mhammond/pywin32
44afd86ba8485194df93234639243252deeb40d5
com/win32com/client/__init__.py
python
GetActiveObject
(Class, clsctx=pythoncom.CLSCTX_ALL)
return __WrapDispatch(dispatch, Class, resultCLSID=resultCLSID, clsctx=clsctx)
Python friendly version of GetObject's ProgID/CLSID functionality.
Python friendly version of GetObject's ProgID/CLSID functionality.
[ "Python", "friendly", "version", "of", "GetObject", "s", "ProgID", "/", "CLSID", "functionality", "." ]
def GetActiveObject(Class, clsctx=pythoncom.CLSCTX_ALL): """ Python friendly version of GetObject's ProgID/CLSID functionality. """ resultCLSID = pywintypes.IID(Class) dispatch = pythoncom.GetActiveObject(resultCLSID) dispatch = dispatch.QueryInterface(pythoncom.IID_IDispatch) return __WrapDispatch(dispatch, Class, resultCLSID=resultCLSID, clsctx=clsctx)
[ "def", "GetActiveObject", "(", "Class", ",", "clsctx", "=", "pythoncom", ".", "CLSCTX_ALL", ")", ":", "resultCLSID", "=", "pywintypes", ".", "IID", "(", "Class", ")", "dispatch", "=", "pythoncom", ".", "GetActiveObject", "(", "resultCLSID", ")", "dispatch", ...
https://github.com/mhammond/pywin32/blob/44afd86ba8485194df93234639243252deeb40d5/com/win32com/client/__init__.py#L88-L95
tfwu/FaceDetection-ConvNet-3D
f9251c48eb40c5aec8fba7455115c355466555be
python/build/lib.linux-x86_64-2.7/mxnet/kvstore.py
python
_ctype_key_value
(keys, vals)
Return ctype arrays for the key-value args, for internal use
Return ctype arrays for the key-value args, for internal use
[ "Return", "ctype", "arrays", "for", "the", "key", "-", "value", "args", "for", "internal", "use" ]
def _ctype_key_value(keys, vals): """ Return ctype arrays for the key-value args, for internal use """ if isinstance(keys, int): if isinstance(vals, NDArray): return (c_array(ctypes.c_int, [keys]), c_array(NDArrayHandle, [vals.handle])) else: for value in vals: assert(isinstance(value, NDArray)) return (c_array(ctypes.c_int, [keys] * len(vals)), c_array(NDArrayHandle, [value.handle for value in vals])) else: assert(len(keys) == len(vals)) for k in keys: assert(isinstance(k, int)) c_keys = [] c_vals = [] for i in range(len(keys)): c_key_i, c_val_i = _ctype_key_value(keys[i], vals[i]) c_keys += c_key_i c_vals += c_val_i return (c_array(ctypes.c_int, c_keys), c_array(NDArrayHandle, c_vals))
[ "def", "_ctype_key_value", "(", "keys", ",", "vals", ")", ":", "if", "isinstance", "(", "keys", ",", "int", ")", ":", "if", "isinstance", "(", "vals", ",", "NDArray", ")", ":", "return", "(", "c_array", "(", "ctypes", ".", "c_int", ",", "[", "keys", ...
https://github.com/tfwu/FaceDetection-ConvNet-3D/blob/f9251c48eb40c5aec8fba7455115c355466555be/python/build/lib.linux-x86_64-2.7/mxnet/kvstore.py#L13-L36
generalized-intelligence/GAAS
29ab17d3e8a4ba18edef3a57c36d8db6329fac73
algorithms/src/SystemManagement/json_request_response_lib/src/third_party/nlohmann_json/third_party/cpplint/cpplint.py
python
_Quiet
()
return _cpplint_state.quiet
Return's the module's quiet setting.
Return's the module's quiet setting.
[ "Return", "s", "the", "module", "s", "quiet", "setting", "." ]
def _Quiet(): """Return's the module's quiet setting.""" return _cpplint_state.quiet
[ "def", "_Quiet", "(", ")", ":", "return", "_cpplint_state", ".", "quiet" ]
https://github.com/generalized-intelligence/GAAS/blob/29ab17d3e8a4ba18edef3a57c36d8db6329fac73/algorithms/src/SystemManagement/json_request_response_lib/src/third_party/nlohmann_json/third_party/cpplint/cpplint.py#L1171-L1173
qgis/QGIS
15a77662d4bb712184f6aa60d0bd663010a76a75
python/plugins/db_manager/dlg_create_table.py
python
DlgCreateTable.updatePkeyCombo
(self, selRow=None)
called when list of columns changes. if 'sel' is None, it keeps current index
called when list of columns changes. if 'sel' is None, it keeps current index
[ "called", "when", "list", "of", "columns", "changes", ".", "if", "sel", "is", "None", "it", "keeps", "current", "index" ]
def updatePkeyCombo(self, selRow=None): """ called when list of columns changes. if 'sel' is None, it keeps current index """ if selRow is None: selRow = self.cboPrimaryKey.currentIndex() self.cboPrimaryKey.clear() m = self.fields.model() for row in range(m.rowCount()): name = m.data(m.index(row, 0)) self.cboPrimaryKey.addItem(name) self.cboPrimaryKey.setCurrentIndex(selRow)
[ "def", "updatePkeyCombo", "(", "self", ",", "selRow", "=", "None", ")", ":", "if", "selRow", "is", "None", ":", "selRow", "=", "self", ".", "cboPrimaryKey", ".", "currentIndex", "(", ")", "self", ".", "cboPrimaryKey", ".", "clear", "(", ")", "m", "=", ...
https://github.com/qgis/QGIS/blob/15a77662d4bb712184f6aa60d0bd663010a76a75/python/plugins/db_manager/dlg_create_table.py#L160-L173
bh107/bohrium
5b83e7117285fefc7779ed0e9acb0f8e74c7e068
bridge/bh107/bh107/random.py
python
RandomState.rand
(self, *shape)
return self.random_sample(shape)
Random values in a given shape. Create an array of the given shape and propagate it with random samples from a uniform distribution over ``[0, 1)``. Parameters ---------- d0, d1, ..., dn : int, optional The dimensions of the returned array, should all be positive. If no argument is given a single Python float is returned. Returns ------- out : BhArray, shape ``(d0, d1, ..., dn)`` Random values. See Also -------- random Notes ----- This is a convenience function. If you want an interface that takes a shape-tuple as the first argument, refer to np.random.random_sample . Examples -------- >>> np.random.rand(3,2) array([[ 0.14022471, 0.96360618], #random [ 0.37601032, 0.25528411], #random [ 0.49313049, 0.94909878]]) #random
Random values in a given shape.
[ "Random", "values", "in", "a", "given", "shape", "." ]
def rand(self, *shape): """Random values in a given shape. Create an array of the given shape and propagate it with random samples from a uniform distribution over ``[0, 1)``. Parameters ---------- d0, d1, ..., dn : int, optional The dimensions of the returned array, should all be positive. If no argument is given a single Python float is returned. Returns ------- out : BhArray, shape ``(d0, d1, ..., dn)`` Random values. See Also -------- random Notes ----- This is a convenience function. If you want an interface that takes a shape-tuple as the first argument, refer to np.random.random_sample . Examples -------- >>> np.random.rand(3,2) array([[ 0.14022471, 0.96360618], #random [ 0.37601032, 0.25528411], #random [ 0.49313049, 0.94909878]]) #random """ return self.random_sample(shape)
[ "def", "rand", "(", "self", ",", "*", "shape", ")", ":", "return", "self", ".", "random_sample", "(", "shape", ")" ]
https://github.com/bh107/bohrium/blob/5b83e7117285fefc7779ed0e9acb0f8e74c7e068/bridge/bh107/bh107/random.py#L320-L356
KhronosGroup/Vulkan-Samples
11a0eeffa223e3c049780fd783900da0bfe50431
.github/docker/scripts/run-clang-tidy.py
python
apply_fixes
(args, tmpdir)
Calls clang-apply-fixes on a given directory.
Calls clang-apply-fixes on a given directory.
[ "Calls", "clang", "-", "apply", "-", "fixes", "on", "a", "given", "directory", "." ]
def apply_fixes(args, tmpdir): """Calls clang-apply-fixes on a given directory.""" invocation = [args.clang_apply_replacements_binary] if args.format: invocation.append('-format') if args.style: invocation.append('-style=' + args.style) invocation.append(tmpdir) subprocess.call(invocation)
[ "def", "apply_fixes", "(", "args", ",", "tmpdir", ")", ":", "invocation", "=", "[", "args", ".", "clang_apply_replacements_binary", "]", "if", "args", ".", "format", ":", "invocation", ".", "append", "(", "'-format'", ")", "if", "args", ".", "style", ":", ...
https://github.com/KhronosGroup/Vulkan-Samples/blob/11a0eeffa223e3c049780fd783900da0bfe50431/.github/docker/scripts/run-clang-tidy.py#L144-L152
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/pdfviewer/viewer.py
python
pdfViewer.UsePrintDirect
(self)
return self._usePrintDirect
Property to control to use either Cairo (via a page buffer) or dcGraphicsContext depending.
Property to control to use either Cairo (via a page buffer) or dcGraphicsContext depending.
[ "Property", "to", "control", "to", "use", "either", "Cairo", "(", "via", "a", "page", "buffer", ")", "or", "dcGraphicsContext", "depending", "." ]
def UsePrintDirect(self): """ Property to control to use either Cairo (via a page buffer) or dcGraphicsContext depending. """ return self._usePrintDirect
[ "def", "UsePrintDirect", "(", "self", ")", ":", "return", "self", ".", "_usePrintDirect" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/pdfviewer/viewer.py#L289-L294
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/stc.py
python
StyledTextCtrl.MarkerNext
(*args, **kwargs)
return _stc.StyledTextCtrl_MarkerNext(*args, **kwargs)
MarkerNext(self, int lineStart, int markerMask) -> int Find the next line after lineStart that includes a marker in mask.
MarkerNext(self, int lineStart, int markerMask) -> int
[ "MarkerNext", "(", "self", "int", "lineStart", "int", "markerMask", ")", "-", ">", "int" ]
def MarkerNext(*args, **kwargs): """ MarkerNext(self, int lineStart, int markerMask) -> int Find the next line after lineStart that includes a marker in mask. """ return _stc.StyledTextCtrl_MarkerNext(*args, **kwargs)
[ "def", "MarkerNext", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_stc", ".", "StyledTextCtrl_MarkerNext", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/stc.py#L2394-L2400
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/animate.py
python
AnimationCtrlBase.Stop
(*args, **kwargs)
return _animate.AnimationCtrlBase_Stop(*args, **kwargs)
Stop(self)
Stop(self)
[ "Stop", "(", "self", ")" ]
def Stop(*args, **kwargs): """Stop(self)""" return _animate.AnimationCtrlBase_Stop(*args, **kwargs)
[ "def", "Stop", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_animate", ".", "AnimationCtrlBase_Stop", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/animate.py#L169-L171
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/pydoc.py
python
writedoc
(thing, forceload=0)
Write HTML documentation to a file in the current directory.
Write HTML documentation to a file in the current directory.
[ "Write", "HTML", "documentation", "to", "a", "file", "in", "the", "current", "directory", "." ]
def writedoc(thing, forceload=0): """Write HTML documentation to a file in the current directory.""" try: object, name = resolve(thing, forceload) page = html.page(describe(object), html.document(object, name)) with open(name + '.html', 'w', encoding='utf-8') as file: file.write(page) print('wrote', name + '.html') except (ImportError, ErrorDuringImport) as value: print(value)
[ "def", "writedoc", "(", "thing", ",", "forceload", "=", "0", ")", ":", "try", ":", "object", ",", "name", "=", "resolve", "(", "thing", ",", "forceload", ")", "page", "=", "html", ".", "page", "(", "describe", "(", "object", ")", ",", "html", ".", ...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/pydoc.py#L1786-L1795
D-X-Y/caffe-faster-rcnn
eb50c97ff48f3df115d0e85fe0a32b0c7e2aa4cb
python/caffe/draw.py
python
get_layer_label
(layer, rankdir)
return node_label
Define node label based on layer type. Parameters ---------- layer : ? rankdir : {'LR', 'TB', 'BT'} Direction of graph layout. Returns ------- string : A label for the current layer
Define node label based on layer type.
[ "Define", "node", "label", "based", "on", "layer", "type", "." ]
def get_layer_label(layer, rankdir): """Define node label based on layer type. Parameters ---------- layer : ? rankdir : {'LR', 'TB', 'BT'} Direction of graph layout. Returns ------- string : A label for the current layer """ if rankdir in ('TB', 'BT'): # If graph orientation is vertical, horizontal space is free and # vertical space is not; separate words with spaces separator = ' ' else: # If graph orientation is horizontal, vertical space is free and # horizontal space is not; separate words with newlines separator = '\\n' if layer.type == 'Convolution' or layer.type == 'Deconvolution': # Outer double quotes needed or else colon characters don't parse # properly node_label = '"%s%s(%s)%skernel size: %d%sstride: %d%spad: %d"' %\ (layer.name, separator, layer.type, separator, layer.convolution_param.kernel_size[0] if len(layer.convolution_param.kernel_size) else 1, separator, layer.convolution_param.stride[0] if len(layer.convolution_param.stride) else 1, separator, layer.convolution_param.pad[0] if len(layer.convolution_param.pad) else 0) elif layer.type == 'Pooling': pooling_types_dict = get_pooling_types_dict() node_label = '"%s%s(%s %s)%skernel size: %d%sstride: %d%spad: %d"' %\ (layer.name, separator, pooling_types_dict[layer.pooling_param.pool], layer.type, separator, layer.pooling_param.kernel_size, separator, layer.pooling_param.stride, separator, layer.pooling_param.pad) else: node_label = '"%s%s(%s)"' % (layer.name, separator, layer.type) return node_label
[ "def", "get_layer_label", "(", "layer", ",", "rankdir", ")", ":", "if", "rankdir", "in", "(", "'TB'", ",", "'BT'", ")", ":", "# If graph orientation is vertical, horizontal space is free and", "# vertical space is not; separate words with spaces", "separator", "=", "' '", ...
https://github.com/D-X-Y/caffe-faster-rcnn/blob/eb50c97ff48f3df115d0e85fe0a32b0c7e2aa4cb/python/caffe/draw.py#L62-L114
carla-simulator/carla
8854804f4d7748e14d937ec763a2912823a7e5f5
PythonAPI/docs/doc_gen.py
python
Documentation.gen_body
(self)
return md.data().strip()
Generates the documentation body
Generates the documentation body
[ "Generates", "the", "documentation", "body" ]
def gen_body(self): """Generates the documentation body""" md = MarkdownFile() md.first_title() md.textn( "This reference contains all the details the Python API. To consult a previous reference for a specific CARLA release, change the documentation version using the panel in the bottom right corner.<br>" +"This will change the whole documentation to a previous state. Remember that the <i>latest</i> version is the `dev` branch and may show features not available in any packaged versions of CARLA.<hr>") for module_name in sorted(self.master_dict): module = self.master_dict[module_name] module_key = module_name # Generate class doc (if any) if valid_dic_val(module, 'classes'): for cl in sorted(module['classes'], key = lambda i: i['class_name']): class_name = cl['class_name'] class_key = join([module_key, class_name], '.') current_title = module_name+'.'+class_name md.title(2, join([current_title,'<a name="',current_title,'"></a>'])) # Inheritance if valid_dic_val(cl, 'parent'): inherits = italic(create_hyperlinks(cl['parent'])) md.inherit_join(inherits) # Class main doc if valid_dic_val(cl, 'doc'): md.textn(create_hyperlinks(md.prettify_doc(cl['doc']))) # Generate instance variable doc (if any) if valid_dic_val(cl, 'instance_variables'): md.title(3, 'Instance Variables') for inst_var in cl['instance_variables']: add_doc_inst_var(md, inst_var, class_key) # Generate method doc (if any) if valid_dic_val(cl, 'methods'): method_list = list() dunder_list = list() get_list = list() set_list = list() for method in sorted(cl['methods'], key = lambda i: i['def_name']): method_name = method['def_name'] if method_name[0] == '_' and method_name != '__init__': dunder_list.append(method) elif method_name[:4] == 'get_': get_list.append(method) elif method_name[:4] == 'set_': set_list.append(method) else: method_list.append(method) md.title(3, 'Methods') for method in method_list: add_doc_method(md, method, class_key) if len(get_list)>0: md.title(5, 'Getters') for method in get_list: add_doc_getter_setter(md, method, class_key, True, set_list) if len(set_list)>0: md.title(5, 'Setters') for method in set_list: add_doc_getter_setter(md, method, class_key, False, get_list) if len(dunder_list)>0: md.title(5, 'Dunder methods') for method in dunder_list: add_doc_dunder(md, method, class_key) md.separator() append_code_snipets(md) append_snipet_button_script(md) return md.data().strip()
[ "def", "gen_body", "(", "self", ")", ":", "md", "=", "MarkdownFile", "(", ")", "md", ".", "first_title", "(", ")", "md", ".", "textn", "(", "\"This reference contains all the details the Python API. To consult a previous reference for a specific CARLA release, change the docu...
https://github.com/carla-simulator/carla/blob/8854804f4d7748e14d937ec763a2912823a7e5f5/PythonAPI/docs/doc_gen.py#L652-L715
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pyparsing/py3/pyparsing/helpers.py
python
match_previous_expr
(expr: ParserElement)
return rep
Helper to define an expression that is indirectly defined from the tokens matched in a previous expression, that is, it looks for a 'repeat' of a previous expression. For example:: first = Word(nums) second = match_previous_expr(first) match_expr = first + ":" + second will match ``"1:1"``, but not ``"1:2"``. Because this matches by expressions, will *not* match the leading ``"1:1"`` in ``"1:10"``; the expressions are evaluated first, and then compared, so ``"1"`` is compared with ``"10"``. Do *not* use with packrat parsing enabled.
Helper to define an expression that is indirectly defined from the tokens matched in a previous expression, that is, it looks for a 'repeat' of a previous expression. For example::
[ "Helper", "to", "define", "an", "expression", "that", "is", "indirectly", "defined", "from", "the", "tokens", "matched", "in", "a", "previous", "expression", "that", "is", "it", "looks", "for", "a", "repeat", "of", "a", "previous", "expression", ".", "For", ...
def match_previous_expr(expr: ParserElement) -> ParserElement: """Helper to define an expression that is indirectly defined from the tokens matched in a previous expression, that is, it looks for a 'repeat' of a previous expression. For example:: first = Word(nums) second = match_previous_expr(first) match_expr = first + ":" + second will match ``"1:1"``, but not ``"1:2"``. Because this matches by expressions, will *not* match the leading ``"1:1"`` in ``"1:10"``; the expressions are evaluated first, and then compared, so ``"1"`` is compared with ``"10"``. Do *not* use with packrat parsing enabled. """ rep = Forward() e2 = expr.copy() rep <<= e2 def copy_token_to_repeater(s, l, t): matchTokens = _flatten(t.as_list()) def must_match_these_tokens(s, l, t): theseTokens = _flatten(t.as_list()) if theseTokens != matchTokens: raise ParseException(s, l, "Expected {}, found{}".format(matchTokens, theseTokens)) rep.set_parse_action(must_match_these_tokens, callDuringTry=True) expr.add_parse_action(copy_token_to_repeater, callDuringTry=True) rep.set_name("(prev) " + str(expr)) return rep
[ "def", "match_previous_expr", "(", "expr", ":", "ParserElement", ")", "->", "ParserElement", ":", "rep", "=", "Forward", "(", ")", "e2", "=", "expr", ".", "copy", "(", ")", "rep", "<<=", "e2", "def", "copy_token_to_repeater", "(", "s", ",", "l", ",", "...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pyparsing/py3/pyparsing/helpers.py#L163-L194
kamyu104/LeetCode-Solutions
77605708a927ea3b85aee5a479db733938c7c211
Python/escape-the-ghosts.py
python
Solution.escapeGhosts
(self, ghosts, target)
return all(total < abs(target[0]-i)+abs(target[1]-j) for i, j in ghosts)
:type ghosts: List[List[int]] :type target: List[int] :rtype: bool
:type ghosts: List[List[int]] :type target: List[int] :rtype: bool
[ ":", "type", "ghosts", ":", "List", "[", "List", "[", "int", "]]", ":", "type", "target", ":", "List", "[", "int", "]", ":", "rtype", ":", "bool" ]
def escapeGhosts(self, ghosts, target): """ :type ghosts: List[List[int]] :type target: List[int] :rtype: bool """ total = abs(target[0])+abs(target[1]) return all(total < abs(target[0]-i)+abs(target[1]-j) for i, j in ghosts)
[ "def", "escapeGhosts", "(", "self", ",", "ghosts", ",", "target", ")", ":", "total", "=", "abs", "(", "target", "[", "0", "]", ")", "+", "abs", "(", "target", "[", "1", "]", ")", "return", "all", "(", "total", "<", "abs", "(", "target", "[", "0...
https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/escape-the-ghosts.py#L5-L12
google/llvm-propeller
45c226984fe8377ebfb2ad7713c680d652ba678d
llvm/utils/llvm-build/llvmbuild/main.py
python
LLVMProjectInfo.write_cmake_exports_fragment
(self, output_path, enabled_optional_components)
write_cmake_exports_fragment(output_path) -> None Generate a CMake fragment which includes LLVMBuild library dependencies expressed similarly to how CMake would write them via install(EXPORT).
write_cmake_exports_fragment(output_path) -> None
[ "write_cmake_exports_fragment", "(", "output_path", ")", "-", ">", "None" ]
def write_cmake_exports_fragment(self, output_path, enabled_optional_components): """ write_cmake_exports_fragment(output_path) -> None Generate a CMake fragment which includes LLVMBuild library dependencies expressed similarly to how CMake would write them via install(EXPORT). """ dependencies = list(self.get_fragment_dependencies()) # Write out the CMake exports fragment. make_install_dir(os.path.dirname(output_path)) f = open(output_path, 'w') f.write("""\ # Explicit library dependency information. # # The following property assignments tell CMake about link # dependencies of libraries imported from LLVM. """) self.foreach_cmake_library( lambda ci: f.write("""\ set_property(TARGET %s PROPERTY IMPORTED_LINK_INTERFACE_LIBRARIES %s)\n""" % ( ci.get_prefixed_library_name(), " ".join(sorted( dep.get_prefixed_library_name() for dep in self.get_required_libraries_for_component(ci))))) , enabled_optional_components, skip_disabled = True, skip_not_installed = True # Do not export internal libraries like gtest ) f.close()
[ "def", "write_cmake_exports_fragment", "(", "self", ",", "output_path", ",", "enabled_optional_components", ")", ":", "dependencies", "=", "list", "(", "self", ".", "get_fragment_dependencies", "(", ")", ")", "# Write out the CMake exports fragment.", "make_install_dir", ...
https://github.com/google/llvm-propeller/blob/45c226984fe8377ebfb2ad7713c680d652ba678d/llvm/utils/llvm-build/llvmbuild/main.py#L595-L629
ApolloAuto/apollo-platform
86d9dc6743b496ead18d597748ebabd34a513289
ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/lib/function_base.py
python
unique
(x)
This function is deprecated. Use numpy.lib.arraysetops.unique() instead.
This function is deprecated. Use numpy.lib.arraysetops.unique() instead.
[ "This", "function", "is", "deprecated", ".", "Use", "numpy", ".", "lib", ".", "arraysetops", ".", "unique", "()", "instead", "." ]
def unique(x): """ This function is deprecated. Use numpy.lib.arraysetops.unique() instead. """ try: tmp = x.flatten() if tmp.size == 0: return tmp tmp.sort() idx = concatenate(([True], tmp[1:]!=tmp[:-1])) return tmp[idx] except AttributeError: items = sorted(set(x)) return asarray(items)
[ "def", "unique", "(", "x", ")", ":", "try", ":", "tmp", "=", "x", ".", "flatten", "(", ")", "if", "tmp", ".", "size", "==", "0", ":", "return", "tmp", "tmp", ".", "sort", "(", ")", "idx", "=", "concatenate", "(", "(", "[", "True", "]", ",", ...
https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/lib/function_base.py#L1262-L1276
PaddlePaddle/Paddle
1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c
python/paddle/distributed/auto_parallel/operators/dist_reshape.py
python
DistributedReshapeImpl0.forward
(ctx, *args, **kwargs)
kwargs: inputname_mapping & outputname_mapping
kwargs: inputname_mapping & outputname_mapping
[ "kwargs", ":", "inputname_mapping", "&", "outputname_mapping" ]
def forward(ctx, *args, **kwargs): """ kwargs: inputname_mapping & outputname_mapping """ dist_op_context = ctx.dist_op_context main_block = dist_op_context.get_dst_main_program().global_block() src_op = dist_op_context.get_cur_src_op() rank_id = dist_op_context.get_rank_id() op_dist_attr = ctx.get_op_dist_attr_for_program(src_op) assert op_dist_attr is not None, "backward op [{}] don't have dist attribute !".format( str(src_op)) # check validation of inputs / outputs for input_name in src_op.desc.input_names(): assert input_name in kwargs, "input [{}] is not given".format( input_name) assert len(kwargs[input_name]) == len( src_op.desc.input(input_name) ), "number of tensor for input [{}] is not match".format(input_name) for output_name in src_op.desc.output_names(): assert output_name in kwargs, "input [{}] is not given".format( output_name) assert len(kwargs[output_name]) == len( src_op.desc.output(output_name) ), "number of tensor for input [{}] is not match".format( output_name) X_var = main_block.var(kwargs['X'][0]) Out_var = main_block.var(kwargs['Out'][0]) XShape_var = main_block.var(kwargs['XShape'][0]) shape_list = src_op.desc.attr("shape") ShapeTensor_var_list = [] for name in kwargs['ShapeTensor']: ShapeTensor_var_list.append(name) Shape_var_list = [] for name in kwargs['Shape']: Shape_var_list.append(name) # got dist attribute info dim_mapping = op_dist_attr.get_output_dims_mapping(Out_var.name) process_mesh_shape = op_dist_attr.process_mesh.topology # modify target shape for idx, axis in enumerate(dim_mapping): if axis >= 0: if len(shape_list) > idx: shape_list[idx] = shape_list[idx] // process_mesh_shape[ axis] # create op new_op_desc = main_block.desc.append_op() new_op_desc.copy_from(src_op.desc) set_dist_op_desc_original_id(new_op_desc, src_op.desc, ctx) new_op_desc.set_input('ShapeTensor', ShapeTensor_var_list) new_op_desc.set_input('Shape', Shape_var_list) new_op_desc.set_input('X', [X_var.name]) new_op_desc.set_output('XShape', [XShape_var.name]) new_op_desc.set_output('Out', [Out_var.name]) new_op_desc._set_attr('shape', shape_list) main_block._sync_with_cpp()
[ "def", "forward", "(", "ctx", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "dist_op_context", "=", "ctx", ".", "dist_op_context", "main_block", "=", "dist_op_context", ".", "get_dst_main_program", "(", ")", ".", "global_block", "(", ")", "src_op", ...
https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/distributed/auto_parallel/operators/dist_reshape.py#L127-L188
NVIDIAGameWorks/kaolin
e5148d05e9c1e2ce92a07881ce3593b1c5c3f166
kaolin/render/mesh/deftet.py
python
_base_naive_deftet_render
( pixel_coords, # (2,) render_range, # (2,) face_vertices_z, # (num_faces, 3) face_vertices_min, # (num_faces, 2) face_vertices_max, # (num_faces, 2) ax, ay, m, p, n, q, k3)
return in_bbox_idx[selected_mask][in_render_range_mask][order]
Base function for :func:`_naive_deftet_sparse_render` non-batched and for a single pixel This is because most operations are vectorized on faces but then only few outputs of those vectorized operations are used (so it's the memory is only used temporarily).
Base function for :func:`_naive_deftet_sparse_render` non-batched and for a single pixel
[ "Base", "function", "for", ":", "func", ":", "_naive_deftet_sparse_render", "non", "-", "batched", "and", "for", "a", "single", "pixel" ]
def _base_naive_deftet_render( pixel_coords, # (2,) render_range, # (2,) face_vertices_z, # (num_faces, 3) face_vertices_min, # (num_faces, 2) face_vertices_max, # (num_faces, 2) ax, ay, m, p, n, q, k3): # int """Base function for :func:`_naive_deftet_sparse_render` non-batched and for a single pixel This is because most operations are vectorized on faces but then only few outputs of those vectorized operations are used (so it's the memory is only used temporarily). """ in_bbox_mask = torch.logical_and( pixel_coords.unsqueeze(0) > face_vertices_min, pixel_coords.unsqueeze(0) < face_vertices_max) in_bbox_mask = torch.logical_and(in_bbox_mask[:, 0], in_bbox_mask[:, 1]) in_bbox_idx = torch.where(in_bbox_mask)[0] ax = ax[in_bbox_idx] ay = ay[in_bbox_idx] m = m[in_bbox_idx] p = p[in_bbox_idx] n = n[in_bbox_idx] q = q[in_bbox_idx] k3 = k3[in_bbox_idx] s = pixel_coords[0] - ax t = pixel_coords[1] - ay k1 = s * q - n * t k2 = m * t - s * p w1 = k1 / (k3 + NAIVE_EPS) w2 = k2 / (k3 + NAIVE_EPS) w0 = 1. - w1 - w2 selected_mask = (w0 >= -NAIVE_EPS) & (w1 >= -NAIVE_EPS) & (w2 >= -NAIVE_EPS) selected_face_vertices_z = face_vertices_z[in_bbox_idx][selected_mask] selected_weights = torch.stack([ w0[selected_mask], w1[selected_mask], w2[selected_mask]], dim=-1) pixel_depth = torch.sum(selected_weights * face_vertices_z[in_bbox_idx][selected_mask], dim=-1) in_render_range_mask = torch.logical_and( pixel_depth > render_range[0], pixel_depth < render_range[1] ) order = torch.argsort(pixel_depth[in_render_range_mask], descending=True, dim=0) return in_bbox_idx[selected_mask][in_render_range_mask][order]
[ "def", "_base_naive_deftet_render", "(", "pixel_coords", ",", "# (2,)", "render_range", ",", "# (2,)", "face_vertices_z", ",", "# (num_faces, 3)", "face_vertices_min", ",", "# (num_faces, 2)", "face_vertices_max", ",", "# (num_faces, 2)", "ax", ",", "ay", ",", "m", ",",...
https://github.com/NVIDIAGameWorks/kaolin/blob/e5148d05e9c1e2ce92a07881ce3593b1c5c3f166/kaolin/render/mesh/deftet.py#L27-L74
turi-code/SFrame
796b9bdfb2fa1b881d82080754643c7e68629cd2
oss_src/unity/python/sframe/data_structures/sketch.py
python
Sketch.num_elements_processed
(self)
Returns the number of elements processed so far. If the sketch is created with background == False (default), this will always return the length of the input array. Otherwise, this will return the number of elements processed so far.
Returns the number of elements processed so far. If the sketch is created with background == False (default), this will always return the length of the input array. Otherwise, this will return the number of elements processed so far.
[ "Returns", "the", "number", "of", "elements", "processed", "so", "far", ".", "If", "the", "sketch", "is", "created", "with", "background", "==", "False", "(", "default", ")", "this", "will", "always", "return", "the", "length", "of", "the", "input", "array...
def num_elements_processed(self): """ Returns the number of elements processed so far. If the sketch is created with background == False (default), this will always return the length of the input array. Otherwise, this will return the number of elements processed so far. """ with cython_context(): return self.__proxy__.num_elements_processed()
[ "def", "num_elements_processed", "(", "self", ")", ":", "with", "cython_context", "(", ")", ":", "return", "self", ".", "__proxy__", ".", "num_elements_processed", "(", ")" ]
https://github.com/turi-code/SFrame/blob/796b9bdfb2fa1b881d82080754643c7e68629cd2/oss_src/unity/python/sframe/data_structures/sketch.py#L499-L507
mhammond/pywin32
44afd86ba8485194df93234639243252deeb40d5
Pythonwin/pywin/framework/app.py
python
CApp.OnRClick
(self, params)
return 0
Handle right click message
Handle right click message
[ "Handle", "right", "click", "message" ]
def OnRClick(self, params): "Handle right click message" # put up the entire FILE menu! menu = win32ui.LoadMenu(win32ui.IDR_TEXTTYPE).GetSubMenu(0) menu.TrackPopupMenu(params[5]) # track at mouse position. return 0
[ "def", "OnRClick", "(", "self", ",", "params", ")", ":", "# put up the entire FILE menu!", "menu", "=", "win32ui", ".", "LoadMenu", "(", "win32ui", ".", "IDR_TEXTTYPE", ")", ".", "GetSubMenu", "(", "0", ")", "menu", ".", "TrackPopupMenu", "(", "params", "[",...
https://github.com/mhammond/pywin32/blob/44afd86ba8485194df93234639243252deeb40d5/Pythonwin/pywin/framework/app.py#L278-L283
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python/src/Lib/calendar.py
python
HTMLCalendar.formatmonthname
(self, theyear, themonth, withyear=True)
return '<tr><th colspan="7" class="month">%s</th></tr>' % s
Return a month name as a table row.
Return a month name as a table row.
[ "Return", "a", "month", "name", "as", "a", "table", "row", "." ]
def formatmonthname(self, theyear, themonth, withyear=True): """ Return a month name as a table row. """ if withyear: s = '%s %s' % (month_name[themonth], theyear) else: s = '%s' % month_name[themonth] return '<tr><th colspan="7" class="month">%s</th></tr>' % s
[ "def", "formatmonthname", "(", "self", ",", "theyear", ",", "themonth", ",", "withyear", "=", "True", ")", ":", "if", "withyear", ":", "s", "=", "'%s %s'", "%", "(", "month_name", "[", "themonth", "]", ",", "theyear", ")", "else", ":", "s", "=", "'%s...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/calendar.py#L414-L422
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/grid.py
python
Grid.SetColMinimalAcceptableWidth
(*args, **kwargs)
return _grid.Grid_SetColMinimalAcceptableWidth(*args, **kwargs)
SetColMinimalAcceptableWidth(self, int width)
SetColMinimalAcceptableWidth(self, int width)
[ "SetColMinimalAcceptableWidth", "(", "self", "int", "width", ")" ]
def SetColMinimalAcceptableWidth(*args, **kwargs): """SetColMinimalAcceptableWidth(self, int width)""" return _grid.Grid_SetColMinimalAcceptableWidth(*args, **kwargs)
[ "def", "SetColMinimalAcceptableWidth", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_grid", ".", "Grid_SetColMinimalAcceptableWidth", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/grid.py#L1918-L1920
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/nn_impl.py
python
sufficient_statistics_v2
(x, axes, shift=None, keepdims=False, name=None)
return sufficient_statistics( x=x, axes=axes, shift=shift, keep_dims=keepdims, name=name)
Calculate the sufficient statistics for the mean and variance of `x`. These sufficient statistics are computed using the one pass algorithm on an input that's optionally shifted. See: https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Computing_shifted_data Args: x: A `Tensor`. axes: Array of ints. Axes along which to compute mean and variance. shift: A `Tensor` containing the value by which to shift the data for numerical stability, or `None` if no shift is to be performed. A shift close to the true mean provides the most numerically stable results. keepdims: produce statistics with the same dimensionality as the input. name: Name used to scope the operations that compute the sufficient stats. Returns: Four `Tensor` objects of the same type as `x`: * the count (number of elements to average over). * the (possibly shifted) sum of the elements in the array. * the (possibly shifted) sum of squares of the elements in the array. * the shift by which the mean must be corrected or None if `shift` is None.
Calculate the sufficient statistics for the mean and variance of `x`.
[ "Calculate", "the", "sufficient", "statistics", "for", "the", "mean", "and", "variance", "of", "x", "." ]
def sufficient_statistics_v2(x, axes, shift=None, keepdims=False, name=None): """Calculate the sufficient statistics for the mean and variance of `x`. These sufficient statistics are computed using the one pass algorithm on an input that's optionally shifted. See: https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Computing_shifted_data Args: x: A `Tensor`. axes: Array of ints. Axes along which to compute mean and variance. shift: A `Tensor` containing the value by which to shift the data for numerical stability, or `None` if no shift is to be performed. A shift close to the true mean provides the most numerically stable results. keepdims: produce statistics with the same dimensionality as the input. name: Name used to scope the operations that compute the sufficient stats. Returns: Four `Tensor` objects of the same type as `x`: * the count (number of elements to average over). * the (possibly shifted) sum of the elements in the array. * the (possibly shifted) sum of squares of the elements in the array. * the shift by which the mean must be corrected or None if `shift` is None. """ return sufficient_statistics( x=x, axes=axes, shift=shift, keep_dims=keepdims, name=name)
[ "def", "sufficient_statistics_v2", "(", "x", ",", "axes", ",", "shift", "=", "None", ",", "keepdims", "=", "False", ",", "name", "=", "None", ")", ":", "return", "sufficient_statistics", "(", "x", "=", "x", ",", "axes", "=", "axes", ",", "shift", "=", ...
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/nn_impl.py#L1111-L1136
FreeCAD/FreeCAD
ba42231b9c6889b89e064d6d563448ed81e376ec
src/Mod/Draft/DraftGui.py
python
DraftToolBar.getDefaultColor
(self,type,rgb=False)
gets color from the preferences or toolbar
gets color from the preferences or toolbar
[ "gets", "color", "from", "the", "preferences", "or", "toolbar" ]
def getDefaultColor(self,type,rgb=False): """gets color from the preferences or toolbar""" r = 0 g = 0 b = 0 if type == "snap": color = Draft.getParam("snapcolor",4294967295) r = ((color>>24)&0xFF)/255 g = ((color>>16)&0xFF)/255 b = ((color>>8)&0xFF)/255 elif type == "ui": print("draft: deprecation warning: Do not use getDefaultColor(\"ui\") anymore - use getDefaultColor(\"line\") instead.") r = float(self.color.red()/255.0) g = float(self.color.green()/255.0) b = float(self.color.blue()/255.0) elif type == "line": color = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/View")\ .GetUnsigned("DefaultShapeLineColor",255) r = ((color>>24)&0xFF)/255 g = ((color>>16)&0xFF)/255 b = ((color>>8)&0xFF)/255 elif type == "text": color = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/Draft")\ .GetUnsigned("DefaultTextColor",255) r = ((color>>24)&0xFF)/255 g = ((color>>16)&0xFF)/255 b = ((color>>8)&0xFF)/255 elif type == "face": color = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/View")\ .GetUnsigned("DefaultShapeColor",4294967295) r = ((color>>24)&0xFF)/255 g = ((color>>16)&0xFF)/255 b = ((color>>8)&0xFF)/255 elif type == "constr": color = Draft.getParam("constructioncolor",746455039) r = ((color>>24)&0xFF)/255 g = ((color>>16)&0xFF)/255 b = ((color>>8)&0xFF)/255 else: print("draft: error: couldn't get a color for ",type," type.") if rgb: return("rgb("+str(int(r*255))+","+str(int(g*255))+","+str(int(b*255))+")") else: return (r,g,b)
[ "def", "getDefaultColor", "(", "self", ",", "type", ",", "rgb", "=", "False", ")", ":", "r", "=", "0", "g", "=", "0", "b", "=", "0", "if", "type", "==", "\"snap\"", ":", "color", "=", "Draft", ".", "getParam", "(", "\"snapcolor\"", ",", "4294967295...
https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Draft/DraftGui.py#L1841-L1884
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/framework/tensor_spec.py
python
BoundedTensorSpec.__init__
(self, shape, dtype, minimum, maximum, name=None)
Initializes a new `BoundedTensorSpec`. Args: shape: Value convertible to `tf.TensorShape`. The shape of the tensor. dtype: Value convertible to `tf.DType`. The type of the tensor values. minimum: Number or sequence specifying the minimum element bounds (inclusive). Must be broadcastable to `shape`. maximum: Number or sequence specifying the maximum element bounds (inclusive). Must be broadcastable to `shape`. name: Optional string containing a semantic name for the corresponding array. Defaults to `None`. Raises: ValueError: If `minimum` or `maximum` are not provided or not broadcastable to `shape`. TypeError: If the shape is not an iterable or if the `dtype` is an invalid numpy dtype.
Initializes a new `BoundedTensorSpec`.
[ "Initializes", "a", "new", "BoundedTensorSpec", "." ]
def __init__(self, shape, dtype, minimum, maximum, name=None): """Initializes a new `BoundedTensorSpec`. Args: shape: Value convertible to `tf.TensorShape`. The shape of the tensor. dtype: Value convertible to `tf.DType`. The type of the tensor values. minimum: Number or sequence specifying the minimum element bounds (inclusive). Must be broadcastable to `shape`. maximum: Number or sequence specifying the maximum element bounds (inclusive). Must be broadcastable to `shape`. name: Optional string containing a semantic name for the corresponding array. Defaults to `None`. Raises: ValueError: If `minimum` or `maximum` are not provided or not broadcastable to `shape`. TypeError: If the shape is not an iterable or if the `dtype` is an invalid numpy dtype. """ super(BoundedTensorSpec, self).__init__(shape, dtype, name) if minimum is None or maximum is None: raise ValueError("minimum and maximum must be provided; but saw " "'%s' and '%s'" % (minimum, maximum)) try: minimum_shape = np.shape(minimum) common_shapes.broadcast_shape( tensor_shape.TensorShape(minimum_shape), self.shape) except ValueError as exception: raise ValueError("minimum is not compatible with shape. " "Message: {!r}.".format(exception)) try: maximum_shape = np.shape(maximum) common_shapes.broadcast_shape( tensor_shape.TensorShape(maximum_shape), self.shape) except ValueError as exception: raise ValueError("maximum is not compatible with shape. " "Message: {!r}.".format(exception)) self._minimum = np.array(minimum, dtype=self.dtype.as_numpy_dtype()) self._minimum.setflags(write=False) self._maximum = np.array(maximum, dtype=self.dtype.as_numpy_dtype()) self._maximum.setflags(write=False)
[ "def", "__init__", "(", "self", ",", "shape", ",", "dtype", ",", "minimum", ",", "maximum", ",", "name", "=", "None", ")", ":", "super", "(", "BoundedTensorSpec", ",", "self", ")", ".", "__init__", "(", "shape", ",", "dtype", ",", "name", ")", "if", ...
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/framework/tensor_spec.py#L208-L253
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/gsutil/third_party/boto/boto/route53/zone.py
python
Zone.get_records
(self)
return self.route53connection.get_all_rrsets(self.id)
Return a ResourceRecordsSets for all of the records in this zone.
Return a ResourceRecordsSets for all of the records in this zone.
[ "Return", "a", "ResourceRecordsSets", "for", "all", "of", "the", "records", "in", "this", "zone", "." ]
def get_records(self): """ Return a ResourceRecordsSets for all of the records in this zone. """ return self.route53connection.get_all_rrsets(self.id)
[ "def", "get_records", "(", "self", ")", ":", "return", "self", ".", "route53connection", ".", "get_all_rrsets", "(", "self", ".", "id", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/boto/boto/route53/zone.py#L402-L406