nwo
stringlengths
5
86
sha
stringlengths
40
40
path
stringlengths
4
189
language
stringclasses
1 value
identifier
stringlengths
1
94
parameters
stringlengths
2
4.03k
argument_list
stringclasses
1 value
return_statement
stringlengths
0
11.5k
docstring
stringlengths
1
33.2k
docstring_summary
stringlengths
0
5.15k
docstring_tokens
list
function
stringlengths
34
151k
function_tokens
list
url
stringlengths
90
278
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/tools/Editra/src/syntax/_ruby.py
python
KeywordString
(option=0)
return RUBY_KW[1]
Returns the specified Keyword String @note: not used by most modules
Returns the specified Keyword String @note: not used by most modules
[ "Returns", "the", "specified", "Keyword", "String", "@note", ":", "not", "used", "by", "most", "modules" ]
def KeywordString(option=0): """Returns the specified Keyword String @note: not used by most modules """ return RUBY_KW[1]
[ "def", "KeywordString", "(", "option", "=", "0", ")", ":", "return", "RUBY_KW", "[", "1", "]" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/syntax/_ruby.py#L142-L147
hpi-xnor/BMXNet
ed0b201da6667887222b8e4b5f997c4f6b61943d
python/mxnet/module/sequential_module.py
python
SequentialModule.get_params
(self)
return (arg_params, aux_params)
Gets current parameters. Returns ------- (arg_params, aux_params) A pair of dictionaries each mapping parameter names to NDArray values. This is a merged dictionary of all the parameters in the modules.
Gets current parameters.
[ "Gets", "current", "parameters", "." ]
def get_params(self): """Gets current parameters. Returns ------- (arg_params, aux_params) A pair of dictionaries each mapping parameter names to NDArray values. This is a merged dictionary of all the parameters in the modules. """ assert self.binded and self.params_initialized arg_params = dict() aux_params = dict() for module in self._modules: arg, aux = module.get_params() arg_params.update(arg) aux_params.update(aux) return (arg_params, aux_params)
[ "def", "get_params", "(", "self", ")", ":", "assert", "self", ".", "binded", "and", "self", ".", "params_initialized", "arg_params", "=", "dict", "(", ")", "aux_params", "=", "dict", "(", ")", "for", "module", "in", "self", ".", "_modules", ":", "arg", ...
https://github.com/hpi-xnor/BMXNet/blob/ed0b201da6667887222b8e4b5f997c4f6b61943d/python/mxnet/module/sequential_module.py#L152-L171
macchina-io/macchina.io
ef24ba0e18379c3dd48fb84e6dbf991101cb8db0
platform/JS/V8/tools/gyp/pylib/gyp/generator/make.py
python
MakefileWriter.Write
(self, qualified_target, base_path, output_filename, spec, configs, part_of_all)
The main entry point: writes a .mk file for a single target. Arguments: qualified_target: target we're generating base_path: path relative to source root we're building in, used to resolve target-relative paths output_filename: output .mk file name to write spec, configs: gyp info part_of_all: flag indicating this target is part of 'all'
The main entry point: writes a .mk file for a single target.
[ "The", "main", "entry", "point", ":", "writes", "a", ".", "mk", "file", "for", "a", "single", "target", "." ]
def Write(self, qualified_target, base_path, output_filename, spec, configs, part_of_all): """The main entry point: writes a .mk file for a single target. Arguments: qualified_target: target we're generating base_path: path relative to source root we're building in, used to resolve target-relative paths output_filename: output .mk file name to write spec, configs: gyp info part_of_all: flag indicating this target is part of 'all' """ gyp.common.EnsureDirExists(output_filename) self.fp = open(output_filename, 'w') self.fp.write(header) self.qualified_target = qualified_target self.path = base_path self.target = spec['target_name'] self.type = spec['type'] self.toolset = spec['toolset'] self.is_mac_bundle = gyp.xcode_emulation.IsMacBundle(self.flavor, spec) if self.flavor == 'mac': self.xcode_settings = gyp.xcode_emulation.XcodeSettings(spec) else: self.xcode_settings = None deps, link_deps = self.ComputeDeps(spec) # Some of the generation below can add extra output, sources, or # link dependencies. All of the out params of the functions that # follow use names like extra_foo. extra_outputs = [] extra_sources = [] extra_link_deps = [] extra_mac_bundle_resources = [] mac_bundle_deps = [] if self.is_mac_bundle: self.output = self.ComputeMacBundleOutput(spec) self.output_binary = self.ComputeMacBundleBinaryOutput(spec) else: self.output = self.output_binary = self.ComputeOutput(spec) self.is_standalone_static_library = bool( spec.get('standalone_static_library', 0)) self._INSTALLABLE_TARGETS = ('executable', 'loadable_module', 'shared_library') if (self.is_standalone_static_library or self.type in self._INSTALLABLE_TARGETS): self.alias = os.path.basename(self.output) install_path = self._InstallableTargetInstallPath() else: self.alias = self.output install_path = self.output self.WriteLn("TOOLSET := " + self.toolset) self.WriteLn("TARGET := " + self.target) # Actions must come first, since they can generate more OBJs for use below. if 'actions' in spec: self.WriteActions(spec['actions'], extra_sources, extra_outputs, extra_mac_bundle_resources, part_of_all) # Rules must be early like actions. if 'rules' in spec: self.WriteRules(spec['rules'], extra_sources, extra_outputs, extra_mac_bundle_resources, part_of_all) if 'copies' in spec: self.WriteCopies(spec['copies'], extra_outputs, part_of_all) # Bundle resources. if self.is_mac_bundle: all_mac_bundle_resources = ( spec.get('mac_bundle_resources', []) + extra_mac_bundle_resources) self.WriteMacBundleResources(all_mac_bundle_resources, mac_bundle_deps) self.WriteMacInfoPlist(mac_bundle_deps) # Sources. all_sources = spec.get('sources', []) + extra_sources if all_sources: if self.flavor == 'mac': # libtool on OS X generates warnings for duplicate basenames in the same # target. _ValidateSourcesForOSX(spec, all_sources) self.WriteSources( configs, deps, all_sources, extra_outputs, extra_link_deps, part_of_all, gyp.xcode_emulation.MacPrefixHeader( self.xcode_settings, lambda p: Sourceify(self.Absolutify(p)), self.Pchify)) sources = filter(Compilable, all_sources) if sources: self.WriteLn(SHARED_HEADER_SUFFIX_RULES_COMMENT1) extensions = set([os.path.splitext(s)[1] for s in sources]) for ext in extensions: if ext in self.suffix_rules_srcdir: self.WriteLn(self.suffix_rules_srcdir[ext]) self.WriteLn(SHARED_HEADER_SUFFIX_RULES_COMMENT2) for ext in extensions: if ext in self.suffix_rules_objdir1: self.WriteLn(self.suffix_rules_objdir1[ext]) for ext in extensions: if ext in self.suffix_rules_objdir2: self.WriteLn(self.suffix_rules_objdir2[ext]) self.WriteLn('# End of this set of suffix rules') # Add dependency from bundle to bundle binary. if self.is_mac_bundle: mac_bundle_deps.append(self.output_binary) self.WriteTarget(spec, configs, deps, extra_link_deps + link_deps, mac_bundle_deps, extra_outputs, part_of_all) # Update global list of target outputs, used in dependency tracking. target_outputs[qualified_target] = install_path # Update global list of link dependencies. if self.type in ('static_library', 'shared_library'): target_link_deps[qualified_target] = self.output_binary # Currently any versions have the same effect, but in future the behavior # could be different. if self.generator_flags.get('android_ndk_version', None): self.WriteAndroidNdkModuleRule(self.target, all_sources, link_deps) self.fp.close()
[ "def", "Write", "(", "self", ",", "qualified_target", ",", "base_path", ",", "output_filename", ",", "spec", ",", "configs", ",", "part_of_all", ")", ":", "gyp", ".", "common", ".", "EnsureDirExists", "(", "output_filename", ")", "self", ".", "fp", "=", "o...
https://github.com/macchina-io/macchina.io/blob/ef24ba0e18379c3dd48fb84e6dbf991101cb8db0/platform/JS/V8/tools/gyp/pylib/gyp/generator/make.py#L706-L836
daijifeng001/caffe-rfcn
543f8f6a4b7c88256ea1445ae951a12d1ad9cffd
python/caffe/classifier.py
python
Classifier.predict
(self, inputs, oversample=True)
return predictions
Predict classification probabilities of inputs. Parameters ---------- inputs : iterable of (H x W x K) input ndarrays. oversample : boolean average predictions across center, corners, and mirrors when True (default). Center-only prediction when False. Returns ------- predictions: (N x C) ndarray of class probabilities for N images and C classes.
Predict classification probabilities of inputs.
[ "Predict", "classification", "probabilities", "of", "inputs", "." ]
def predict(self, inputs, oversample=True): """ Predict classification probabilities of inputs. Parameters ---------- inputs : iterable of (H x W x K) input ndarrays. oversample : boolean average predictions across center, corners, and mirrors when True (default). Center-only prediction when False. Returns ------- predictions: (N x C) ndarray of class probabilities for N images and C classes. """ # Scale to standardize input dimensions. input_ = np.zeros((len(inputs), self.image_dims[0], self.image_dims[1], inputs[0].shape[2]), dtype=np.float32) for ix, in_ in enumerate(inputs): input_[ix] = caffe.io.resize_image(in_, self.image_dims) if oversample: # Generate center, corner, and mirrored crops. input_ = caffe.io.oversample(input_, self.crop_dims) else: # Take center crop. center = np.array(self.image_dims) / 2.0 crop = np.tile(center, (1, 2))[0] + np.concatenate([ -self.crop_dims / 2.0, self.crop_dims / 2.0 ]) crop = crop.astype(int) input_ = input_[:, crop[0]:crop[2], crop[1]:crop[3], :] # Classify caffe_in = np.zeros(np.array(input_.shape)[[0, 3, 1, 2]], dtype=np.float32) for ix, in_ in enumerate(input_): caffe_in[ix] = self.transformer.preprocess(self.inputs[0], in_) out = self.forward_all(**{self.inputs[0]: caffe_in}) predictions = out[self.outputs[0]] # For oversampling, average predictions across crops. if oversample: predictions = predictions.reshape((len(predictions) / 10, 10, -1)) predictions = predictions.mean(1) return predictions
[ "def", "predict", "(", "self", ",", "inputs", ",", "oversample", "=", "True", ")", ":", "# Scale to standardize input dimensions.", "input_", "=", "np", ".", "zeros", "(", "(", "len", "(", "inputs", ")", ",", "self", ".", "image_dims", "[", "0", "]", ","...
https://github.com/daijifeng001/caffe-rfcn/blob/543f8f6a4b7c88256ea1445ae951a12d1ad9cffd/python/caffe/classifier.py#L47-L98
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/_gdi.py
python
DC.SetClippingRegionAsRegion
(*args, **kwargs)
return _gdi_.DC_SetClippingRegionAsRegion(*args, **kwargs)
SetClippingRegionAsRegion(self, Region region) Sets the clipping region for this device context to the intersection of the given region described by the parameters of this method and the previously set clipping region. You should call `DestroyClippingRegion` if you want to set the clipping region exactly to the region specified. The clipping region is an area to which drawing is restricted. Possible uses for the clipping region are for clipping text or for speeding up window redraws when only a known area of the screen is damaged.
SetClippingRegionAsRegion(self, Region region)
[ "SetClippingRegionAsRegion", "(", "self", "Region", "region", ")" ]
def SetClippingRegionAsRegion(*args, **kwargs): """ SetClippingRegionAsRegion(self, Region region) Sets the clipping region for this device context to the intersection of the given region described by the parameters of this method and the previously set clipping region. You should call `DestroyClippingRegion` if you want to set the clipping region exactly to the region specified. The clipping region is an area to which drawing is restricted. Possible uses for the clipping region are for clipping text or for speeding up window redraws when only a known area of the screen is damaged. """ return _gdi_.DC_SetClippingRegionAsRegion(*args, **kwargs)
[ "def", "SetClippingRegionAsRegion", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_gdi_", ".", "DC_SetClippingRegionAsRegion", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_gdi.py#L3863-L3878
ideawu/ssdb-rocks
a3cbb322cafb2f493252829c608e2239df98c9ac
deps/cpy/antlr3/streams.py
python
CommonTokenStream.get
(self, i)
return self.tokens[i]
Return absolute token i; ignore which channel the tokens are on; that is, count all tokens not just on-channel tokens.
Return absolute token i; ignore which channel the tokens are on; that is, count all tokens not just on-channel tokens.
[ "Return", "absolute", "token", "i", ";", "ignore", "which", "channel", "the", "tokens", "are", "on", ";", "that", "is", "count", "all", "tokens", "not", "just", "on", "-", "channel", "tokens", "." ]
def get(self, i): """ Return absolute token i; ignore which channel the tokens are on; that is, count all tokens not just on-channel tokens. """ return self.tokens[i]
[ "def", "get", "(", "self", ",", "i", ")", ":", "return", "self", ".", "tokens", "[", "i", "]" ]
https://github.com/ideawu/ssdb-rocks/blob/a3cbb322cafb2f493252829c608e2239df98c9ac/deps/cpy/antlr3/streams.py#L849-L855
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/_controls.py
python
ListView.ClearColumnImage
(*args, **kwargs)
return _controls_.ListView_ClearColumnImage(*args, **kwargs)
ClearColumnImage(self, int col)
ClearColumnImage(self, int col)
[ "ClearColumnImage", "(", "self", "int", "col", ")" ]
def ClearColumnImage(*args, **kwargs): """ClearColumnImage(self, int col)""" return _controls_.ListView_ClearColumnImage(*args, **kwargs)
[ "def", "ClearColumnImage", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_controls_", ".", "ListView_ClearColumnImage", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_controls.py#L4936-L4938
hpi-xnor/BMXNet-v2
af2b1859eafc5c721b1397cef02f946aaf2ce20d
docs/tutorial_utils/vision/cnn_visualization/gradcam.py
python
get_guided_grad_cam
(cam, imggrad)
return np.multiply(cam, imggrad)
Compute Guided Grad-CAM. Refer section 3 of https://arxiv.org/abs/1610.02391 for details
Compute Guided Grad-CAM. Refer section 3 of https://arxiv.org/abs/1610.02391 for details
[ "Compute", "Guided", "Grad", "-", "CAM", ".", "Refer", "section", "3", "of", "https", ":", "//", "arxiv", ".", "org", "/", "abs", "/", "1610", ".", "02391", "for", "details" ]
def get_guided_grad_cam(cam, imggrad): """Compute Guided Grad-CAM. Refer section 3 of https://arxiv.org/abs/1610.02391 for details""" return np.multiply(cam, imggrad)
[ "def", "get_guided_grad_cam", "(", "cam", ",", "imggrad", ")", ":", "return", "np", ".", "multiply", "(", "cam", ",", "imggrad", ")" ]
https://github.com/hpi-xnor/BMXNet-v2/blob/af2b1859eafc5c721b1397cef02f946aaf2ce20d/docs/tutorial_utils/vision/cnn_visualization/gradcam.py#L221-L223
spencer-project/spencer_people_tracking
09b256ba4bc22c5cae8a5ae88960de1a387cfd7f
tracking/people/spencer_tracking_metrics/src/spencer_tracking_metrics/pymot/rect.py
python
Rect.__init__
(self, entity)
Constructor from dict with keys width, height, x, y, dco and id
Constructor from dict with keys width, height, x, y, dco and id
[ "Constructor", "from", "dict", "with", "keys", "width", "height", "x", "y", "dco", "and", "id" ]
def __init__(self, entity): """Constructor from dict with keys width, height, x, y, dco and id""" self.x_ = entity["x"] self.y_ = entity["y"] # Use dco, if found self.dco_ = entity.get("dco",False) # Use id. assert "id" in entity self.id_= str(entity["id"])
[ "def", "__init__", "(", "self", ",", "entity", ")", ":", "self", ".", "x_", "=", "entity", "[", "\"x\"", "]", "self", ".", "y_", "=", "entity", "[", "\"y\"", "]", "# Use dco, if found", "self", ".", "dco_", "=", "entity", ".", "get", "(", "\"dco\"", ...
https://github.com/spencer-project/spencer_people_tracking/blob/09b256ba4bc22c5cae8a5ae88960de1a387cfd7f/tracking/people/spencer_tracking_metrics/src/spencer_tracking_metrics/pymot/rect.py#L6-L17
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/richtext.py
python
RichTextBuffer.GetHandlerFlags
(*args, **kwargs)
return _richtext.RichTextBuffer_GetHandlerFlags(*args, **kwargs)
GetHandlerFlags(self) -> int
GetHandlerFlags(self) -> int
[ "GetHandlerFlags", "(", "self", ")", "-", ">", "int" ]
def GetHandlerFlags(*args, **kwargs): """GetHandlerFlags(self) -> int""" return _richtext.RichTextBuffer_GetHandlerFlags(*args, **kwargs)
[ "def", "GetHandlerFlags", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_richtext", ".", "RichTextBuffer_GetHandlerFlags", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/richtext.py#L2265-L2267
wywu/LAB
4b6debd302ae109fd104d4dd04dccc3418ae7471
examples/pycaffe/tools.py
python
SimpleTransformer.set_scale
(self, scale)
Set the data scaling.
Set the data scaling.
[ "Set", "the", "data", "scaling", "." ]
def set_scale(self, scale): """ Set the data scaling. """ self.scale = scale
[ "def", "set_scale", "(", "self", ",", "scale", ")", ":", "self", ".", "scale", "=", "scale" ]
https://github.com/wywu/LAB/blob/4b6debd302ae109fd104d4dd04dccc3418ae7471/examples/pycaffe/tools.py#L21-L25
MVIG-SJTU/RMPE
5188c230ec800c12be7369c3619615bc9b020aa4
scripts/cpp_lint.py
python
RemoveMultiLineComments
(filename, lines, error)
Removes multiline (c-style) comments from lines.
Removes multiline (c-style) comments from lines.
[ "Removes", "multiline", "(", "c", "-", "style", ")", "comments", "from", "lines", "." ]
def RemoveMultiLineComments(filename, lines, error): """Removes multiline (c-style) comments from lines.""" lineix = 0 while lineix < len(lines): lineix_begin = FindNextMultiLineCommentStart(lines, lineix) if lineix_begin >= len(lines): return lineix_end = FindNextMultiLineCommentEnd(lines, lineix_begin) if lineix_end >= len(lines): error(filename, lineix_begin + 1, 'readability/multiline_comment', 5, 'Could not find end of multi-line comment') return RemoveMultiLineCommentsFromRange(lines, lineix_begin, lineix_end + 1) lineix = lineix_end + 1
[ "def", "RemoveMultiLineComments", "(", "filename", ",", "lines", ",", "error", ")", ":", "lineix", "=", "0", "while", "lineix", "<", "len", "(", "lines", ")", ":", "lineix_begin", "=", "FindNextMultiLineCommentStart", "(", "lines", ",", "lineix", ")", "if", ...
https://github.com/MVIG-SJTU/RMPE/blob/5188c230ec800c12be7369c3619615bc9b020aa4/scripts/cpp_lint.py#L1151-L1164
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/gsutil/third_party/boto/boto/elastictranscoder/layer1.py
python
ElasticTranscoderConnection.update_pipeline_notifications
(self, id=None, notifications=None)
return self.make_request('POST', uri, expected_status=200, data=json.dumps(params))
With the UpdatePipelineNotifications operation, you can update Amazon Simple Notification Service (Amazon SNS) notifications for a pipeline. When you update notifications for a pipeline, Elastic Transcoder returns the values that you specified in the request. :type id: string :param id: The identifier of the pipeline for which you want to change notification settings. :type notifications: dict :param notifications: The topic ARN for the Amazon Simple Notification Service (Amazon SNS) topic that you want to notify to report job status. To receive notifications, you must also subscribe to the new topic in the Amazon SNS console. + **Progressing**: The topic ARN for the Amazon Simple Notification Service (Amazon SNS) topic that you want to notify when Elastic Transcoder has started to process jobs that are added to this pipeline. This is the ARN that Amazon SNS returned when you created the topic. + **Completed**: The topic ARN for the Amazon SNS topic that you want to notify when Elastic Transcoder has finished processing a job. This is the ARN that Amazon SNS returned when you created the topic. + **Warning**: The topic ARN for the Amazon SNS topic that you want to notify when Elastic Transcoder encounters a warning condition. This is the ARN that Amazon SNS returned when you created the topic. + **Error**: The topic ARN for the Amazon SNS topic that you want to notify when Elastic Transcoder encounters an error condition. This is the ARN that Amazon SNS returned when you created the topic.
With the UpdatePipelineNotifications operation, you can update Amazon Simple Notification Service (Amazon SNS) notifications for a pipeline.
[ "With", "the", "UpdatePipelineNotifications", "operation", "you", "can", "update", "Amazon", "Simple", "Notification", "Service", "(", "Amazon", "SNS", ")", "notifications", "for", "a", "pipeline", "." ]
def update_pipeline_notifications(self, id=None, notifications=None): """ With the UpdatePipelineNotifications operation, you can update Amazon Simple Notification Service (Amazon SNS) notifications for a pipeline. When you update notifications for a pipeline, Elastic Transcoder returns the values that you specified in the request. :type id: string :param id: The identifier of the pipeline for which you want to change notification settings. :type notifications: dict :param notifications: The topic ARN for the Amazon Simple Notification Service (Amazon SNS) topic that you want to notify to report job status. To receive notifications, you must also subscribe to the new topic in the Amazon SNS console. + **Progressing**: The topic ARN for the Amazon Simple Notification Service (Amazon SNS) topic that you want to notify when Elastic Transcoder has started to process jobs that are added to this pipeline. This is the ARN that Amazon SNS returned when you created the topic. + **Completed**: The topic ARN for the Amazon SNS topic that you want to notify when Elastic Transcoder has finished processing a job. This is the ARN that Amazon SNS returned when you created the topic. + **Warning**: The topic ARN for the Amazon SNS topic that you want to notify when Elastic Transcoder encounters a warning condition. This is the ARN that Amazon SNS returned when you created the topic. + **Error**: The topic ARN for the Amazon SNS topic that you want to notify when Elastic Transcoder encounters an error condition. This is the ARN that Amazon SNS returned when you created the topic. """ uri = '/2012-09-25/pipelines/{0}/notifications'.format(id) params = {} if id is not None: params['Id'] = id if notifications is not None: params['Notifications'] = notifications return self.make_request('POST', uri, expected_status=200, data=json.dumps(params))
[ "def", "update_pipeline_notifications", "(", "self", ",", "id", "=", "None", ",", "notifications", "=", "None", ")", ":", "uri", "=", "'/2012-09-25/pipelines/{0}/notifications'", ".", "format", "(", "id", ")", "params", "=", "{", "}", "if", "id", "is", "not"...
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/boto/boto/elastictranscoder/layer1.py#L839-L884
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/python/debug/wrappers/framework.py
python
BaseDebugWrapperSession.__init__
(self, sess, thread_name_filter=None)
Constructor of `BaseDebugWrapperSession`. Args: sess: An (unwrapped) TensorFlow session instance. thread_name_filter: Regular-expression filter (whitelist) for name(s) of thread(s) on which the wrapper session will be active. This regular expression is used in a start-anchored fashion on the thread name, i.e., by applying the `match` method of the compiled pattern. The default `None` means that the wrapper session will be active on all threads. E.g., r"MainThread$", r"QueueRunnerThread.*". Raises: ValueError: On invalid `OnSessionInitAction` value. NotImplementedError: If a non-DirectSession sess object is received.
Constructor of `BaseDebugWrapperSession`.
[ "Constructor", "of", "BaseDebugWrapperSession", "." ]
def __init__(self, sess, thread_name_filter=None): """Constructor of `BaseDebugWrapperSession`. Args: sess: An (unwrapped) TensorFlow session instance. thread_name_filter: Regular-expression filter (whitelist) for name(s) of thread(s) on which the wrapper session will be active. This regular expression is used in a start-anchored fashion on the thread name, i.e., by applying the `match` method of the compiled pattern. The default `None` means that the wrapper session will be active on all threads. E.g., r"MainThread$", r"QueueRunnerThread.*". Raises: ValueError: On invalid `OnSessionInitAction` value. NotImplementedError: If a non-DirectSession sess object is received. """ _check_type(sess, session.BaseSession) # The session being wrapped. self._sess = sess self._thread_name_filter_pattern = (re.compile(thread_name_filter) if thread_name_filter else None) # Keeps track of number of run calls that have been performed on this # debug-wrapper session. self._run_call_count = 0 # Invoke on-session-init callback. response = self.on_session_init(OnSessionInitRequest(self._sess)) _check_type(response, OnSessionInitResponse) if response.action == OnSessionInitAction.PROCEED: pass elif response.action == OnSessionInitAction.REMOTE_INSTR_LOOP: # TODO(cais): Implement REMOTE_INSTR_LOOP raise NotImplementedError( "OnSessionInitAction REMOTE_INSTR_LOOP has not been " "implemented.") else: raise ValueError( "Invalid OnSessionInitAction value: %s" % response.action)
[ "def", "__init__", "(", "self", ",", "sess", ",", "thread_name_filter", "=", "None", ")", ":", "_check_type", "(", "sess", ",", "session", ".", "BaseSession", ")", "# The session being wrapped.", "self", ".", "_sess", "=", "sess", "self", ".", "_thread_name_fi...
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/python/debug/wrappers/framework.py#L338-L379
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/propgrid.py
python
PGProperty.InsertChild
(*args, **kwargs)
return _propgrid.PGProperty_InsertChild(*args, **kwargs)
InsertChild(self, int index, PGProperty childProperty) -> PGProperty
InsertChild(self, int index, PGProperty childProperty) -> PGProperty
[ "InsertChild", "(", "self", "int", "index", "PGProperty", "childProperty", ")", "-", ">", "PGProperty" ]
def InsertChild(*args, **kwargs): """InsertChild(self, int index, PGProperty childProperty) -> PGProperty""" return _propgrid.PGProperty_InsertChild(*args, **kwargs)
[ "def", "InsertChild", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_propgrid", ".", "PGProperty_InsertChild", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/propgrid.py#L575-L577
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/gsutil/third_party/rsa/rsa/_version133.py
python
ceil
(x)
return int(math.ceil(x))
ceil(x) -> int(math.ceil(x))
ceil(x) -> int(math.ceil(x))
[ "ceil", "(", "x", ")", "-", ">", "int", "(", "math", ".", "ceil", "(", "x", "))" ]
def ceil(x): """ceil(x) -> int(math.ceil(x))""" return int(math.ceil(x))
[ "def", "ceil", "(", "x", ")", ":", "return", "int", "(", "math", ".", "ceil", "(", "x", ")", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/rsa/rsa/_version133.py#L109-L112
adobe/chromium
cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7
tools/generate_stubs/generate_stubs.py
python
PosixStubWriter.CStyleIdentifier
(cls, identifier)
return string.capwords(re.sub(INVALID_C_IDENT_CHARS, '', identifier))
Generates a C style identifier. The module_name has all invalid identifier characters removed (anything that's not [_a-zA-Z0-9]) and is run through string.capwords to try and approximate camel case. Args: identifier: The string with the module name to turn to C-style. Returns: A string that can be used as part of a C identifier.
Generates a C style identifier.
[ "Generates", "a", "C", "style", "identifier", "." ]
def CStyleIdentifier(cls, identifier): """Generates a C style identifier. The module_name has all invalid identifier characters removed (anything that's not [_a-zA-Z0-9]) and is run through string.capwords to try and approximate camel case. Args: identifier: The string with the module name to turn to C-style. Returns: A string that can be used as part of a C identifier. """ return string.capwords(re.sub(INVALID_C_IDENT_CHARS, '', identifier))
[ "def", "CStyleIdentifier", "(", "cls", ",", "identifier", ")", ":", "return", "string", ".", "capwords", "(", "re", ".", "sub", "(", "INVALID_C_IDENT_CHARS", ",", "''", ",", "identifier", ")", ")" ]
https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/tools/generate_stubs/generate_stubs.py#L514-L527
llvm-mirror/lldb
d01083a850f577b85501a0902b52fd0930de72c7
utils/vim-lldb/python-vim-lldb/vim_signs.py
python
VimSign.define
(self, sign_text, highlight_colour)
return sign_name
Defines sign and highlight (if highlight_colour is not None).
Defines sign and highlight (if highlight_colour is not None).
[ "Defines", "sign", "and", "highlight", "(", "if", "highlight_colour", "is", "not", "None", ")", "." ]
def define(self, sign_text, highlight_colour): """ Defines sign and highlight (if highlight_colour is not None). """ sign_name = "sign%d" % VimSign.name_id if highlight_colour is None: vim.command("sign define %s text=%s" % (sign_name, sign_text)) else: self.highlight_name = "highlight%d" % VimSign.name_id vim.command( "highlight %s ctermbg=%s guibg=%s" % (self.highlight_name, highlight_colour, highlight_colour)) vim.command( "sign define %s text=%s linehl=%s texthl=%s" % (sign_name, sign_text, self.highlight_name, self.highlight_name)) VimSign.defined_signs[(sign_text, highlight_colour)] = sign_name VimSign.name_id += 1 return sign_name
[ "def", "define", "(", "self", ",", "sign_text", ",", "highlight_colour", ")", ":", "sign_name", "=", "\"sign%d\"", "%", "VimSign", ".", "name_id", "if", "highlight_colour", "is", "None", ":", "vim", ".", "command", "(", "\"sign define %s text=%s\"", "%", "(", ...
https://github.com/llvm-mirror/lldb/blob/d01083a850f577b85501a0902b52fd0930de72c7/utils/vim-lldb/python-vim-lldb/vim_signs.py#L36-L51
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/boosted_trees/examples/binary_mnist.py
python
_get_tfbt
(output_dir)
return estimator
Configures TF Boosted Trees estimator based on flags.
Configures TF Boosted Trees estimator based on flags.
[ "Configures", "TF", "Boosted", "Trees", "estimator", "based", "on", "flags", "." ]
def _get_tfbt(output_dir): """Configures TF Boosted Trees estimator based on flags.""" learner_config = learner_pb2.LearnerConfig() learner_config.learning_rate_tuner.fixed.learning_rate = FLAGS.learning_rate learner_config.regularization.l1 = 0.0 learner_config.regularization.l2 = FLAGS.l2 / FLAGS.examples_per_layer learner_config.constraints.max_tree_depth = FLAGS.depth growing_mode = learner_pb2.LearnerConfig.LAYER_BY_LAYER learner_config.growing_mode = growing_mode run_config = tf.contrib.learn.RunConfig(save_checkpoints_secs=300) # Create a TF Boosted trees estimator that can take in custom loss. estimator = GradientBoostedDecisionTreeClassifier( learner_config=learner_config, examples_per_layer=FLAGS.examples_per_layer, model_dir=output_dir, num_trees=FLAGS.num_trees, center_bias=False, config=run_config) return estimator
[ "def", "_get_tfbt", "(", "output_dir", ")", ":", "learner_config", "=", "learner_pb2", ".", "LearnerConfig", "(", ")", "learner_config", ".", "learning_rate_tuner", ".", "fixed", ".", "learning_rate", "=", "FLAGS", ".", "learning_rate", "learner_config", ".", "reg...
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/boosted_trees/examples/binary_mnist.py#L75-L96
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/_misc.py
python
ConfigBase.Set
(*args, **kwargs)
return _misc_.ConfigBase_Set(*args, **kwargs)
Set(ConfigBase config) -> ConfigBase Sets the global config object (the one returned by Get) and returns a reference to the previous global config object.
Set(ConfigBase config) -> ConfigBase
[ "Set", "(", "ConfigBase", "config", ")", "-", ">", "ConfigBase" ]
def Set(*args, **kwargs): """ Set(ConfigBase config) -> ConfigBase Sets the global config object (the one returned by Get) and returns a reference to the previous global config object. """ return _misc_.ConfigBase_Set(*args, **kwargs)
[ "def", "Set", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_misc_", ".", "ConfigBase_Set", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_misc.py#L3103-L3110
weolar/miniblink49
1c4678db0594a4abde23d3ebbcc7cd13c3170777
third_party/WebKit/Tools/Scripts/webkitpy/thirdparty/BeautifulSoup.py
python
PageElement.findPrevious
(self, name=None, attrs={}, text=None, **kwargs)
return self._findOne(self.findAllPrevious, name, attrs, text, **kwargs)
Returns the first item that matches the given criteria and appears before this Tag in the document.
Returns the first item that matches the given criteria and appears before this Tag in the document.
[ "Returns", "the", "first", "item", "that", "matches", "the", "given", "criteria", "and", "appears", "before", "this", "Tag", "in", "the", "document", "." ]
def findPrevious(self, name=None, attrs={}, text=None, **kwargs): """Returns the first item that matches the given criteria and appears before this Tag in the document.""" return self._findOne(self.findAllPrevious, name, attrs, text, **kwargs)
[ "def", "findPrevious", "(", "self", ",", "name", "=", "None", ",", "attrs", "=", "{", "}", ",", "text", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_findOne", "(", "self", ".", "findAllPrevious", ",", "name", ",", "attrs...
https://github.com/weolar/miniblink49/blob/1c4678db0594a4abde23d3ebbcc7cd13c3170777/third_party/WebKit/Tools/Scripts/webkitpy/thirdparty/BeautifulSoup.py#L278-L281
trilinos/Trilinos
6168be6dd51e35e1cd681e9c4b24433e709df140
packages/seacas/libraries/ioss/src/visualization/catalyst/phactori/phactori.py
python
PhactoriOperationSpecifics.GetListOfInputOperationNamesForThisOperationType
(self)
return retList
operations which depend on additional inputs besides the default single input need to override this method and return their dependencies as a list of names
operations which depend on additional inputs besides the default single input need to override this method and return their dependencies as a list of names
[ "operations", "which", "depend", "on", "additional", "inputs", "besides", "the", "default", "single", "input", "need", "to", "override", "this", "method", "and", "return", "their", "dependencies", "as", "a", "list", "of", "names" ]
def GetListOfInputOperationNamesForThisOperationType(self): """operations which depend on additional inputs besides the default single input need to override this method and return their dependencies as a list of names""" retList = [] return retList
[ "def", "GetListOfInputOperationNamesForThisOperationType", "(", "self", ")", ":", "retList", "=", "[", "]", "return", "retList" ]
https://github.com/trilinos/Trilinos/blob/6168be6dd51e35e1cd681e9c4b24433e709df140/packages/seacas/libraries/ioss/src/visualization/catalyst/phactori/phactori.py#L6312-L6317
KratosMultiphysics/Kratos
0000833054ed0503424eb28205d6508d9ca6cbbc
kratos/python_scripts/gid_output_process.py
python
GiDOutputProcess.ExecuteFinalize
(self)
Finalize files and free resources.
Finalize files and free resources.
[ "Finalize", "files", "and", "free", "resources", "." ]
def ExecuteFinalize(self): '''Finalize files and free resources.''' if self.multifile_flag == MultiFileFlag.SingleFile: self.__finalize_results() if self.point_output_process is not None: self.point_output_process.ExecuteFinalize() for freq,f in self.volume_list_files: f.close() for freq,f in self.cut_list_files: f.close() # Note: it is important to call the GidIO destructor, since it closes output files # Since Python's garbage colletion DOES NOT ensure that the destructor will be called, # I'm deallocating the GidIO instances explicitly. This is VERY BAD PRACTICE # and effectively breaks the class if called after this point, but we haven't found # a better solution yet (jcotela 12/V/2016) del self.body_io del self.cut_io
[ "def", "ExecuteFinalize", "(", "self", ")", ":", "if", "self", ".", "multifile_flag", "==", "MultiFileFlag", ".", "SingleFile", ":", "self", ".", "__finalize_results", "(", ")", "if", "self", ".", "point_output_process", "is", "not", "None", ":", "self", "."...
https://github.com/KratosMultiphysics/Kratos/blob/0000833054ed0503424eb28205d6508d9ca6cbbc/kratos/python_scripts/gid_output_process.py#L322-L342
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/winpython/wppm.py
python
Distribution.remove_directory
(self, path)
Try to remove directory -- on WindowsError, remove it later
Try to remove directory -- on WindowsError, remove it later
[ "Try", "to", "remove", "directory", "--", "on", "WindowsError", "remove", "it", "later" ]
def remove_directory(self, path): """Try to remove directory -- on WindowsError, remove it later""" try: shutil.rmtree(path) except WindowsError: self.to_be_removed.append(path)
[ "def", "remove_directory", "(", "self", ",", "path", ")", ":", "try", ":", "shutil", ".", "rmtree", "(", "path", ")", "except", "WindowsError", ":", "self", ".", "to_be_removed", ".", "append", "(", "path", ")" ]
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/winpython/wppm.py#L223-L228
Polidea/SiriusObfuscator
b0e590d8130e97856afe578869b83a209e2b19be
SymbolExtractorAndRenamer/cmark/bench/statistics.py
python
_sum
(data, start=0)
return T(total)
_sum(data [, start]) -> value Return a high-precision sum of the given numeric data. If optional argument ``start`` is given, it is added to the total. If ``data`` is empty, ``start`` (defaulting to 0) is returned. Examples -------- >>> _sum([3, 2.25, 4.5, -0.5, 1.0], 0.75) 11.0 Some sources of round-off error will be avoided: >>> _sum([1e50, 1, -1e50] * 1000) # Built-in sum returns zero. 1000.0 Fractions and Decimals are also supported: >>> from fractions import Fraction as F >>> _sum([F(2, 3), F(7, 5), F(1, 4), F(5, 6)]) Fraction(63, 20) >>> from decimal import Decimal as D >>> data = [D("0.1375"), D("0.2108"), D("0.3061"), D("0.0419")] >>> _sum(data) Decimal('0.6963') Mixed types are currently treated as an error, except that int is allowed.
_sum(data [, start]) -> value
[ "_sum", "(", "data", "[", "start", "]", ")", "-", ">", "value" ]
def _sum(data, start=0): """_sum(data [, start]) -> value Return a high-precision sum of the given numeric data. If optional argument ``start`` is given, it is added to the total. If ``data`` is empty, ``start`` (defaulting to 0) is returned. Examples -------- >>> _sum([3, 2.25, 4.5, -0.5, 1.0], 0.75) 11.0 Some sources of round-off error will be avoided: >>> _sum([1e50, 1, -1e50] * 1000) # Built-in sum returns zero. 1000.0 Fractions and Decimals are also supported: >>> from fractions import Fraction as F >>> _sum([F(2, 3), F(7, 5), F(1, 4), F(5, 6)]) Fraction(63, 20) >>> from decimal import Decimal as D >>> data = [D("0.1375"), D("0.2108"), D("0.3061"), D("0.0419")] >>> _sum(data) Decimal('0.6963') Mixed types are currently treated as an error, except that int is allowed. """ # We fail as soon as we reach a value that is not an int or the type of # the first value which is not an int. E.g. _sum([int, int, float, int]) # is okay, but sum([int, int, float, Fraction]) is not. allowed_types = set([int, type(start)]) n, d = _exact_ratio(start) partials = {d: n} # map {denominator: sum of numerators} # Micro-optimizations. exact_ratio = _exact_ratio partials_get = partials.get # Add numerators for each denominator. for x in data: _check_type(type(x), allowed_types) n, d = exact_ratio(x) partials[d] = partials_get(d, 0) + n # Find the expected result type. If allowed_types has only one item, it # will be int; if it has two, use the one which isn't int. assert len(allowed_types) in (1, 2) if len(allowed_types) == 1: assert allowed_types.pop() is int T = int else: T = (allowed_types - set([int])).pop() if None in partials: assert issubclass(T, (float, Decimal)) assert not math.isfinite(partials[None]) return T(partials[None]) total = Fraction() for d, n in sorted(partials.items()): total += Fraction(n, d) if issubclass(T, int): assert total.denominator == 1 return T(total.numerator) if issubclass(T, Decimal): return T(total.numerator)/total.denominator return T(total)
[ "def", "_sum", "(", "data", ",", "start", "=", "0", ")", ":", "# We fail as soon as we reach a value that is not an int or the type of", "# the first value which is not an int. E.g. _sum([int, int, float, int])", "# is okay, but sum([int, int, float, Fraction]) is not.", "allowed_types", ...
https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/cmark/bench/statistics.py#L117-L184
alibaba/MNN
c4d9566171d589c3ded23aa18ffb197016995a12
pymnn/pip_package/MNN/expr/__init__.py
python
greater
(x, y)
return _F.greater(x, y)
greater(x, y) Return the ``x > y``, element-wise. Parameters ---------- x : var_like, input value. y : var_like, input value. Returns ------- z : Var. The ``x > y`` of `x` and `y`, dtype is int32. Example: ------- >>> expr.greater([-9., 0.5], [1.2, -3.0]) var([0, 1])
greater(x, y) Return the ``x > y``, element-wise.
[ "greater", "(", "x", "y", ")", "Return", "the", "x", ">", "y", "element", "-", "wise", "." ]
def greater(x, y): ''' greater(x, y) Return the ``x > y``, element-wise. Parameters ---------- x : var_like, input value. y : var_like, input value. Returns ------- z : Var. The ``x > y`` of `x` and `y`, dtype is int32. Example: ------- >>> expr.greater([-9., 0.5], [1.2, -3.0]) var([0, 1]) ''' x = _to_var(x) y = _to_var(y) x, y = _match_dtype(x, y) return _F.greater(x, y)
[ "def", "greater", "(", "x", ",", "y", ")", ":", "x", "=", "_to_var", "(", "x", ")", "y", "=", "_to_var", "(", "y", ")", "x", ",", "y", "=", "_match_dtype", "(", "x", ",", "y", ")", "return", "_F", ".", "greater", "(", "x", ",", "y", ")" ]
https://github.com/alibaba/MNN/blob/c4d9566171d589c3ded23aa18ffb197016995a12/pymnn/pip_package/MNN/expr/__init__.py#L985-L1007
CanalTP/navitia
cb84ce9859070187e708818b058e6a7e0b7f891b
source/jormungandr/jormungandr/scenarios/helper_classes/helper_utils.py
python
_update_fallback_sections
(journey, fallback_dp, fallback_period_extremity, fallback_type, via_access_point)
Replace journey's fallback sections with the given fallback_dp. Note: the replacement is done in place of the journey
Replace journey's fallback sections with the given fallback_dp.
[ "Replace", "journey", "s", "fallback", "sections", "with", "the", "given", "fallback_dp", "." ]
def _update_fallback_sections(journey, fallback_dp, fallback_period_extremity, fallback_type, via_access_point): """ Replace journey's fallback sections with the given fallback_dp. Note: the replacement is done in place of the journey """ aligned_fallback = _align_fallback_direct_path_datetime(fallback_dp, fallback_period_extremity) fallback_sections = aligned_fallback.journeys[0].sections # update the 'id' which isn't set _rename_fallback_sections_ids(fallback_sections) if fallback_type == StreetNetworkPathType.BEGINNING_FALLBACK: section_to_replace = journey.sections[0] else: section_to_replace = journey.sections[-1] journey.sections.remove(section_to_replace) # We have to create the link between the fallback and the pt part manually here if fallback_type == StreetNetworkPathType.BEGINNING_FALLBACK: fallback_sections[-1].destination.CopyFrom(journey.sections[0].origin) else: fallback_sections[0].origin.CopyFrom(journey.sections[-1].destination) if ( isinstance(via_access_point, type_pb2.PtObject) and via_access_point.embedded_type == type_pb2.ACCESS_POINT ): if fallback_type == StreetNetworkPathType.BEGINNING_FALLBACK: fallback_sections[-1].vias.add().CopyFrom(via_access_point.access_point) else: fallback_sections[0].vias.add().CopyFrom(via_access_point.access_point) journey.sections.extend(fallback_sections) journey.sections.sort(key=cmp_to_key(SectionSorter()))
[ "def", "_update_fallback_sections", "(", "journey", ",", "fallback_dp", ",", "fallback_period_extremity", ",", "fallback_type", ",", "via_access_point", ")", ":", "aligned_fallback", "=", "_align_fallback_direct_path_datetime", "(", "fallback_dp", ",", "fallback_period_extrem...
https://github.com/CanalTP/navitia/blob/cb84ce9859070187e708818b058e6a7e0b7f891b/source/jormungandr/jormungandr/scenarios/helper_classes/helper_utils.py#L306-L341
wujian16/Cornell-MOE
df299d1be882d2af9796d7a68b3f9505cac7a53e
moe/optimal_learning/python/data_containers.py
python
HistoricalData.num_derivatives
(self)
return self._num_derivatives
Return the number of derivatives' observationsof a point in ``self.points_sampled``.
Return the number of derivatives' observationsof a point in ``self.points_sampled``.
[ "Return", "the", "number", "of", "derivatives", "observationsof", "a", "point", "in", "self", ".", "points_sampled", "." ]
def num_derivatives(self): """Return the number of derivatives' observationsof a point in ``self.points_sampled``.""" return self._num_derivatives
[ "def", "num_derivatives", "(", "self", ")", ":", "return", "self", ".", "_num_derivatives" ]
https://github.com/wujian16/Cornell-MOE/blob/df299d1be882d2af9796d7a68b3f9505cac7a53e/moe/optimal_learning/python/data_containers.py#L292-L294
Polidea/SiriusObfuscator
b0e590d8130e97856afe578869b83a209e2b19be
SymbolExtractorAndRenamer/clang/bindings/python/clang/cindex.py
python
Type.get_canonical
(self)
return conf.lib.clang_getCanonicalType(self)
Return the canonical type for a Type. Clang's type system explicitly models typedefs and all the ways a specific type can be represented. The canonical type is the underlying type with all the "sugar" removed. For example, if 'T' is a typedef for 'int', the canonical type for 'T' would be 'int'.
Return the canonical type for a Type.
[ "Return", "the", "canonical", "type", "for", "a", "Type", "." ]
def get_canonical(self): """ Return the canonical type for a Type. Clang's type system explicitly models typedefs and all the ways a specific type can be represented. The canonical type is the underlying type with all the "sugar" removed. For example, if 'T' is a typedef for 'int', the canonical type for 'T' would be 'int'. """ return conf.lib.clang_getCanonicalType(self)
[ "def", "get_canonical", "(", "self", ")", ":", "return", "conf", ".", "lib", ".", "clang_getCanonicalType", "(", "self", ")" ]
https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/clang/bindings/python/clang/cindex.py#L2026-L2036
Ubpa/RenderLab
71db49aa03de4fb258f9171691c8d570216e5e05
bin/NN_Trainer/util.py
python
Hyperbox.GenSpiltHyperbox
(self, spiltAxis)
return leftHyperbox, rightHyperbox, spiltVal
按轴 spiltAxis 分割超盒 @param spiltAxis: 分割轴,要求 spiltAxis in self.GetSpiltableAxis() @return leftHyperbox: 左超盒 rightHyperbox: 右超盒 spiltVal: 分割值
按轴 spiltAxis 分割超盒
[ "按轴", "spiltAxis", "分割超盒" ]
def GenSpiltHyperbox(self, spiltAxis): """ 按轴 spiltAxis 分割超盒 @param spiltAxis: 分割轴,要求 spiltAxis in self.GetSpiltableAxis() @return leftHyperbox: 左超盒 rightHyperbox: 右超盒 spiltVal: 分割值 """ if spiltAxis not in self.GetSpiltableAxis(): raise RuntimeError("spiltAxis not in self.GetSpiltableAxis()") hyperbox = self.__box spiltVal = (hyperbox[spiltAxis][1] - hyperbox[spiltAxis][0]) / 2 leftHyperbox = self.GenCopy() rightHyperbox = self.GenCopy() leftHyperbox.__box[spiltAxis][1] = spiltVal rightHyperbox.__box[spiltAxis][0] = spiltVal return leftHyperbox, rightHyperbox, spiltVal
[ "def", "GenSpiltHyperbox", "(", "self", ",", "spiltAxis", ")", ":", "if", "spiltAxis", "not", "in", "self", ".", "GetSpiltableAxis", "(", ")", ":", "raise", "RuntimeError", "(", "\"spiltAxis not in self.GetSpiltableAxis()\"", ")", "hyperbox", "=", "self", ".", "...
https://github.com/Ubpa/RenderLab/blob/71db49aa03de4fb258f9171691c8d570216e5e05/bin/NN_Trainer/util.py#L79-L103
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/distribute/values.py
python
DistributedVariable._get_on_device_or_primary
(self)
Returns value in same replica or device if possible, else the _primary.
Returns value in same replica or device if possible, else the _primary.
[ "Returns", "value", "in", "same", "replica", "or", "device", "if", "possible", "else", "the", "_primary", "." ]
def _get_on_device_or_primary(self): """Returns value in same replica or device if possible, else the _primary.""" if values_util.is_saving_non_distributed(): return self._primary replica_id = values_util.get_current_replica_id_as_int() if replica_id is None: # Try to find a value on the current device. current_device = device_util.canonicalize(device_util.current()) for i, value in enumerate(self._values): if device_util.canonicalize(value.device) == current_device: return self._get_replica(i) return self._get_replica(0) else: return self._get_replica(replica_id)
[ "def", "_get_on_device_or_primary", "(", "self", ")", ":", "if", "values_util", ".", "is_saving_non_distributed", "(", ")", ":", "return", "self", ".", "_primary", "replica_id", "=", "values_util", ".", "get_current_replica_id_as_int", "(", ")", "if", "replica_id", ...
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/distribute/values.py#L770-L783
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/distutils/command/install.py
python
install.create_path_file
(self)
Creates the .pth file
Creates the .pth file
[ "Creates", "the", ".", "pth", "file" ]
def create_path_file(self): """Creates the .pth file""" filename = os.path.join(self.install_libbase, self.path_file + ".pth") if self.install_path_file: self.execute(write_file, (filename, [self.extra_dirs]), "creating %s" % filename) else: self.warn("path file '%s' not created" % filename)
[ "def", "create_path_file", "(", "self", ")", ":", "filename", "=", "os", ".", "path", ".", "join", "(", "self", ".", "install_libbase", ",", "self", ".", "path_file", "+", "\".pth\"", ")", "if", "self", ".", "install_path_file", ":", "self", ".", "execut...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/distutils/command/install.py#L585-L594
natanielruiz/android-yolo
1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f
jni-build/jni/include/tensorflow/python/ops/tensor_array_ops.py
python
TensorArray.close
(self, name=None)
Close the current TensorArray.
Close the current TensorArray.
[ "Close", "the", "current", "TensorArray", "." ]
def close(self, name=None): """Close the current TensorArray.""" with ops.colocate_with(self._handle): return gen_data_flow_ops._tensor_array_close( handle=self._handle, name=name)
[ "def", "close", "(", "self", ",", "name", "=", "None", ")", ":", "with", "ops", ".", "colocate_with", "(", "self", ".", "_handle", ")", ":", "return", "gen_data_flow_ops", ".", "_tensor_array_close", "(", "handle", "=", "self", ".", "_handle", ",", "name...
https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/python/ops/tensor_array_ops.py#L369-L373
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/setuptools/py3/pkg_resources/_vendor/pyparsing.py
python
ParserElement.__add__
(self, other )
return And( [ self, other ] )
Implementation of + operator - returns C{L{And}}. Adding strings to a ParserElement converts them to L{Literal}s by default. Example:: greet = Word(alphas) + "," + Word(alphas) + "!" hello = "Hello, World!" print (hello, "->", greet.parseString(hello)) Prints:: Hello, World! -> ['Hello', ',', 'World', '!']
Implementation of + operator - returns C{L{And}}. Adding strings to a ParserElement converts them to L{Literal}s by default. Example:: greet = Word(alphas) + "," + Word(alphas) + "!" hello = "Hello, World!" print (hello, "->", greet.parseString(hello)) Prints:: Hello, World! -> ['Hello', ',', 'World', '!']
[ "Implementation", "of", "+", "operator", "-", "returns", "C", "{", "L", "{", "And", "}}", ".", "Adding", "strings", "to", "a", "ParserElement", "converts", "them", "to", "L", "{", "Literal", "}", "s", "by", "default", ".", "Example", "::", "greet", "="...
def __add__(self, other ): """ Implementation of + operator - returns C{L{And}}. Adding strings to a ParserElement converts them to L{Literal}s by default. Example:: greet = Word(alphas) + "," + Word(alphas) + "!" hello = "Hello, World!" print (hello, "->", greet.parseString(hello)) Prints:: Hello, World! -> ['Hello', ',', 'World', '!'] """ if isinstance( other, basestring ): other = ParserElement._literalStringClass( other ) if not isinstance( other, ParserElement ): warnings.warn("Cannot combine element of type %s with ParserElement" % type(other), SyntaxWarning, stacklevel=2) return None return And( [ self, other ] )
[ "def", "__add__", "(", "self", ",", "other", ")", ":", "if", "isinstance", "(", "other", ",", "basestring", ")", ":", "other", "=", "ParserElement", ".", "_literalStringClass", "(", "other", ")", "if", "not", "isinstance", "(", "other", ",", "ParserElement...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/setuptools/py3/pkg_resources/_vendor/pyparsing.py#L1821-L1839
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py3/pandas/core/computation/scope.py
python
Scope.has_resolvers
(self)
return bool(len(self.resolvers))
Return whether we have any extra scope. For example, DataFrames pass Their columns as resolvers during calls to ``DataFrame.eval()`` and ``DataFrame.query()``. Returns ------- hr : bool
Return whether we have any extra scope.
[ "Return", "whether", "we", "have", "any", "extra", "scope", "." ]
def has_resolvers(self) -> bool: """ Return whether we have any extra scope. For example, DataFrames pass Their columns as resolvers during calls to ``DataFrame.eval()`` and ``DataFrame.query()``. Returns ------- hr : bool """ return bool(len(self.resolvers))
[ "def", "has_resolvers", "(", "self", ")", "->", "bool", ":", "return", "bool", "(", "len", "(", "self", ".", "resolvers", ")", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/core/computation/scope.py#L163-L174
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/ftplib.py
python
FTP.set_pasv
(self, val)
Use passive or active mode for data transfers. With a false argument, use the normal PORT mode, With a true argument, use the PASV command.
Use passive or active mode for data transfers. With a false argument, use the normal PORT mode, With a true argument, use the PASV command.
[ "Use", "passive", "or", "active", "mode", "for", "data", "transfers", ".", "With", "a", "false", "argument", "use", "the", "normal", "PORT", "mode", "With", "a", "true", "argument", "use", "the", "PASV", "command", "." ]
def set_pasv(self, val): '''Use passive or active mode for data transfers. With a false argument, use the normal PORT mode, With a true argument, use the PASV command.''' self.passiveserver = val
[ "def", "set_pasv", "(", "self", ",", "val", ")", ":", "self", ".", "passiveserver", "=", "val" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/ftplib.py#L154-L158
microsoft/CNTK
e9396480025b9ca457d26b6f33dd07c474c6aa04
bindings/python/cntk/ops/sequence/__init__.py
python
past_value
(x, initial_state=None, time_step=1, name='')
return past_value(x, initial_state, time_step, name)
This function returns the past value w.r.t. ``x``. It is most often used when creating RNNs. The resulting tensor has the same shape as the input but is the previous logical sample. The ``time_step`` parameter is the number of steps to look into the past and is 1 by default. If there is no past value (i.e. the current sample is the first one in the tensor) then the ``initial_state`` value is returned. The initial state can be a constant (scalar or tensor), a learnable tensor or input data (which has a batch dimension, as needed for sequence-to-sequence models). Example: >>> # create example input: one sequence with 4 tensors of shape (3, 2) >>> from cntk.layers.typing import Tensor, Sequence >>> x = C.sequence.input_variable((3,2)) >>> x0 = np.reshape(np.arange(24,dtype=np.float32),(1,4,3,2)) >>> x0 array([[[[ 0., 1.], [ 2., 3.], [ 4., 5.]], <BLANKLINE> [[ 6., 7.], [ 8., 9.], [ 10., 11.]], <BLANKLINE> [[ 12., 13.], [ 14., 15.], [ 16., 17.]], <BLANKLINE> [[ 18., 19.], [ 20., 21.], [ 22., 23.]]]], dtype=float32) >>> # this demonstrates how past_value shifts the sequence by one, padding with initial_state >>> y = C.sequence.past_value(x) # initial_state is 0 by default >>> y.eval({x:x0}) [array([[[ 0., 0.], [ 0., 0.], [ 0., 0.]], <BLANKLINE> [[ 0., 1.], [ 2., 3.], [ 4., 5.]], <BLANKLINE> [[ 6., 7.], [ 8., 9.], [ 10., 11.]], <BLANKLINE> [[ 12., 13.], [ 14., 15.], [ 16., 17.]]], dtype=float32)] >>> # here, we pass a the initial_state as input data (e.g. sequence-to-sequence) >>> s = C.input_variable((3,2)) # not a sequence, e.g. a final encoder hidden state >>> s0 = np.reshape(np.arange(6,dtype=np.float32)/2,(1,3,2)) >>> s0 array([[[ 0. , 0.5], [ 1. , 1.5], [ 2. , 2.5]]], dtype=float32) >>> y = C.sequence.past_value(x, initial_state=s) >>> y.eval({x:x0, s:s0}) # same as the previous example except for the first time step [array([[[ 0. , 0.5], [ 1. , 1.5], [ 2. , 2.5]], <BLANKLINE> [[ 0. , 1. ], [ 2. , 3. ], [ 4. , 5. ]], <BLANKLINE> [[ 6. , 7. ], [ 8. , 9. ], [ 10. , 11. ]], <BLANKLINE> [[ 12. , 13. ], [ 14. , 15. ], [ 16. , 17. ]]], dtype=float32)] Args: x: the tensor (or its name) from which the past value is obtained initial_state: tensor or scalar representing the initial value to be used when the input tensor is shifted in time. time_step (int): the number of time steps to look into the past (default 1) name (str, optional): the name of the Function instance in the network Returns: :class:`~cntk.ops.functions.Function`
This function returns the past value w.r.t. ``x``. It is most often used when creating RNNs. The resulting tensor has the same shape as the input but is the previous logical sample. The ``time_step`` parameter is the number of steps to look into the past and is 1 by default. If there is no past value (i.e. the current sample is the first one in the tensor) then the ``initial_state`` value is returned.
[ "This", "function", "returns", "the", "past", "value", "w", ".", "r", ".", "t", ".", "x", ".", "It", "is", "most", "often", "used", "when", "creating", "RNNs", ".", "The", "resulting", "tensor", "has", "the", "same", "shape", "as", "the", "input", "b...
def past_value(x, initial_state=None, time_step=1, name=''): ''' This function returns the past value w.r.t. ``x``. It is most often used when creating RNNs. The resulting tensor has the same shape as the input but is the previous logical sample. The ``time_step`` parameter is the number of steps to look into the past and is 1 by default. If there is no past value (i.e. the current sample is the first one in the tensor) then the ``initial_state`` value is returned. The initial state can be a constant (scalar or tensor), a learnable tensor or input data (which has a batch dimension, as needed for sequence-to-sequence models). Example: >>> # create example input: one sequence with 4 tensors of shape (3, 2) >>> from cntk.layers.typing import Tensor, Sequence >>> x = C.sequence.input_variable((3,2)) >>> x0 = np.reshape(np.arange(24,dtype=np.float32),(1,4,3,2)) >>> x0 array([[[[ 0., 1.], [ 2., 3.], [ 4., 5.]], <BLANKLINE> [[ 6., 7.], [ 8., 9.], [ 10., 11.]], <BLANKLINE> [[ 12., 13.], [ 14., 15.], [ 16., 17.]], <BLANKLINE> [[ 18., 19.], [ 20., 21.], [ 22., 23.]]]], dtype=float32) >>> # this demonstrates how past_value shifts the sequence by one, padding with initial_state >>> y = C.sequence.past_value(x) # initial_state is 0 by default >>> y.eval({x:x0}) [array([[[ 0., 0.], [ 0., 0.], [ 0., 0.]], <BLANKLINE> [[ 0., 1.], [ 2., 3.], [ 4., 5.]], <BLANKLINE> [[ 6., 7.], [ 8., 9.], [ 10., 11.]], <BLANKLINE> [[ 12., 13.], [ 14., 15.], [ 16., 17.]]], dtype=float32)] >>> # here, we pass a the initial_state as input data (e.g. sequence-to-sequence) >>> s = C.input_variable((3,2)) # not a sequence, e.g. a final encoder hidden state >>> s0 = np.reshape(np.arange(6,dtype=np.float32)/2,(1,3,2)) >>> s0 array([[[ 0. , 0.5], [ 1. , 1.5], [ 2. , 2.5]]], dtype=float32) >>> y = C.sequence.past_value(x, initial_state=s) >>> y.eval({x:x0, s:s0}) # same as the previous example except for the first time step [array([[[ 0. , 0.5], [ 1. , 1.5], [ 2. , 2.5]], <BLANKLINE> [[ 0. , 1. ], [ 2. , 3. ], [ 4. , 5. ]], <BLANKLINE> [[ 6. , 7. ], [ 8. , 9. ], [ 10. , 11. ]], <BLANKLINE> [[ 12. , 13. ], [ 14. , 15. ], [ 16. , 17. ]]], dtype=float32)] Args: x: the tensor (or its name) from which the past value is obtained initial_state: tensor or scalar representing the initial value to be used when the input tensor is shifted in time. time_step (int): the number of time steps to look into the past (default 1) name (str, optional): the name of the Function instance in the network Returns: :class:`~cntk.ops.functions.Function` ''' from cntk.internal import sanitize_dtype_cntk from cntk.cntk_py import Constant, past_value if initial_state is None: initial_state = Constant.scalar(sanitize_dtype_cntk(x.dtype), 0.0) else: initial_state = sanitize_input(initial_state) x = sanitize_input(x) return past_value(x, initial_state, time_step, name)
[ "def", "past_value", "(", "x", ",", "initial_state", "=", "None", ",", "time_step", "=", "1", ",", "name", "=", "''", ")", ":", "from", "cntk", ".", "internal", "import", "sanitize_dtype_cntk", "from", "cntk", ".", "cntk_py", "import", "Constant", ",", "...
https://github.com/microsoft/CNTK/blob/e9396480025b9ca457d26b6f33dd07c474c6aa04/bindings/python/cntk/ops/sequence/__init__.py#L160-L257
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/lib-tk/ttk.py
python
Progressbar.step
(self, amount=None)
Increments the value option by amount. amount defaults to 1.0 if omitted.
Increments the value option by amount.
[ "Increments", "the", "value", "option", "by", "amount", "." ]
def step(self, amount=None): """Increments the value option by amount. amount defaults to 1.0 if omitted.""" self.tk.call(self._w, "step", amount)
[ "def", "step", "(", "self", ",", "amount", "=", "None", ")", ":", "self", ".", "tk", ".", "call", "(", "self", ".", "_w", ",", "\"step\"", ",", "amount", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/lib-tk/ttk.py#L1018-L1022
ppizarro/coursera
b39847928df4d9d5986b801085c025e8e9122b6a
stanford-algorithms1/programming6/2sum/2SUM.py
python
TwoSum_Naive
(lst, target)
return None
Naive 2-SUM algorithm. O(n^2) time.
Naive 2-SUM algorithm. O(n^2) time.
[ "Naive", "2", "-", "SUM", "algorithm", ".", "O", "(", "n^2", ")", "time", "." ]
def TwoSum_Naive(lst, target): ''' Naive 2-SUM algorithm. O(n^2) time. ''' for x in lst: for y in lst: if x != y and x+y == target: return (x, y) return None
[ "def", "TwoSum_Naive", "(", "lst", ",", "target", ")", ":", "for", "x", "in", "lst", ":", "for", "y", "in", "lst", ":", "if", "x", "!=", "y", "and", "x", "+", "y", "==", "target", ":", "return", "(", "x", ",", "y", ")", "return", "None" ]
https://github.com/ppizarro/coursera/blob/b39847928df4d9d5986b801085c025e8e9122b6a/stanford-algorithms1/programming6/2sum/2SUM.py#L21-L33
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_core.py
python
Image.ConvertToGreyscale
(*args)
return _core_.Image_ConvertToGreyscale(*args)
ConvertToGreyscale(self) -> Image ConvertToGreyscale(self, double lr, double lg, double lb) -> Image Convert to greyscale image. Uses the luminance component (Y) of the image. The luma value (YUV) is calculated using (R * lr) + (G * lg) + (B * lb), defaults to ITU-T BT.601
ConvertToGreyscale(self) -> Image ConvertToGreyscale(self, double lr, double lg, double lb) -> Image
[ "ConvertToGreyscale", "(", "self", ")", "-", ">", "Image", "ConvertToGreyscale", "(", "self", "double", "lr", "double", "lg", "double", "lb", ")", "-", ">", "Image" ]
def ConvertToGreyscale(*args): """ ConvertToGreyscale(self) -> Image ConvertToGreyscale(self, double lr, double lg, double lb) -> Image Convert to greyscale image. Uses the luminance component (Y) of the image. The luma value (YUV) is calculated using (R * lr) + (G * lg) + (B * lb), defaults to ITU-T BT.601 """ return _core_.Image_ConvertToGreyscale(*args)
[ "def", "ConvertToGreyscale", "(", "*", "args", ")", ":", "return", "_core_", ".", "Image_ConvertToGreyscale", "(", "*", "args", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_core.py#L3537-L3546
pyne/pyne
0c2714d7c0d1b5e20be6ae6527da2c660dd6b1b3
pyne/xs/data_source.py
python
EAFDataSource._load_group_structure
(self)
Loads the EAF energy bounds array, E_g, from nuc_data.
Loads the EAF energy bounds array, E_g, from nuc_data.
[ "Loads", "the", "EAF", "energy", "bounds", "array", "E_g", "from", "nuc_data", "." ]
def _load_group_structure(self): """Loads the EAF energy bounds array, E_g, from nuc_data.""" with tb.open_file(nuc_data, 'r') as f: E_g = np.array(f.root.neutron.eaf_xs.E_g) self.src_group_struct = E_g
[ "def", "_load_group_structure", "(", "self", ")", ":", "with", "tb", ".", "open_file", "(", "nuc_data", ",", "'r'", ")", "as", "f", ":", "E_g", "=", "np", ".", "array", "(", "f", ".", "root", ".", "neutron", ".", "eaf_xs", ".", "E_g", ")", "self", ...
https://github.com/pyne/pyne/blob/0c2714d7c0d1b5e20be6ae6527da2c660dd6b1b3/pyne/xs/data_source.py#L628-L632
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/_pyio.py
python
IOBase.truncate
(self, pos=None)
Truncate file to size bytes. Size defaults to the current IO position as reported by tell(). Return the new size.
Truncate file to size bytes.
[ "Truncate", "file", "to", "size", "bytes", "." ]
def truncate(self, pos=None): """Truncate file to size bytes. Size defaults to the current IO position as reported by tell(). Return the new size. """ self._unsupported("truncate")
[ "def", "truncate", "(", "self", ",", "pos", "=", "None", ")", ":", "self", ".", "_unsupported", "(", "\"truncate\"", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/_pyio.py#L343-L349
wujian16/Cornell-MOE
df299d1be882d2af9796d7a68b3f9505cac7a53e
moe/optimal_learning/python/cpp_wrappers/knowledge_gradient_mcmc.py
python
PosteriorMeanMCMC.set_current_point
(self, points_to_sample)
Set current_point to the specified point; ordering must match. :param points_to_sample: current_point at which to evaluate the objective function, ``f(x)`` :type points_to_sample: array of float64 with shape (problem_size)
Set current_point to the specified point; ordering must match. :param points_to_sample: current_point at which to evaluate the objective function, ``f(x)`` :type points_to_sample: array of float64 with shape (problem_size)
[ "Set", "current_point", "to", "the", "specified", "point", ";", "ordering", "must", "match", ".", ":", "param", "points_to_sample", ":", "current_point", "at", "which", "to", "evaluate", "the", "objective", "function", "f", "(", "x", ")", ":", "type", "point...
def set_current_point(self, points_to_sample): """Set current_point to the specified point; ordering must match. :param points_to_sample: current_point at which to evaluate the objective function, ``f(x)`` :type points_to_sample: array of float64 with shape (problem_size) """ self._points_to_sample = numpy.copy(numpy.atleast_2d(points_to_sample))
[ "def", "set_current_point", "(", "self", ",", "points_to_sample", ")", ":", "self", ".", "_points_to_sample", "=", "numpy", ".", "copy", "(", "numpy", ".", "atleast_2d", "(", "points_to_sample", ")", ")" ]
https://github.com/wujian16/Cornell-MOE/blob/df299d1be882d2af9796d7a68b3f9505cac7a53e/moe/optimal_learning/python/cpp_wrappers/knowledge_gradient_mcmc.py#L63-L68
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/lib2to3/fixer_util.py
python
does_tree_import
(package, name, node)
return bool(binding)
Returns true if name is imported from package at the top level of the tree which node belongs to. To cover the case of an import like 'import foo', use None for the package and 'foo' for the name.
Returns true if name is imported from package at the top level of the tree which node belongs to. To cover the case of an import like 'import foo', use None for the package and 'foo' for the name.
[ "Returns", "true", "if", "name", "is", "imported", "from", "package", "at", "the", "top", "level", "of", "the", "tree", "which", "node", "belongs", "to", ".", "To", "cover", "the", "case", "of", "an", "import", "like", "import", "foo", "use", "None", "...
def does_tree_import(package, name, node): """ Returns true if name is imported from package at the top level of the tree which node belongs to. To cover the case of an import like 'import foo', use None for the package and 'foo' for the name. """ binding = find_binding(name, find_root(node), package) return bool(binding)
[ "def", "does_tree_import", "(", "package", ",", "name", ",", "node", ")", ":", "binding", "=", "find_binding", "(", "name", ",", "find_root", "(", "node", ")", ",", "package", ")", "return", "bool", "(", "binding", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/lib2to3/fixer_util.py#L303-L309
generalized-intelligence/GAAS
29ab17d3e8a4ba18edef3a57c36d8db6329fac73
deprecated/algorithms/sfm/dataset.py
python
DataSet._undistorted_segmentation_file
(self, image)
return os.path.join(self._undistorted_segmentation_path(), image + '.png')
Path of undistorted version of a segmentation.
Path of undistorted version of a segmentation.
[ "Path", "of", "undistorted", "version", "of", "a", "segmentation", "." ]
def _undistorted_segmentation_file(self, image): """Path of undistorted version of a segmentation.""" return os.path.join(self._undistorted_segmentation_path(), image + '.png')
[ "def", "_undistorted_segmentation_file", "(", "self", ",", "image", ")", ":", "return", "os", ".", "path", ".", "join", "(", "self", ".", "_undistorted_segmentation_path", "(", ")", ",", "image", "+", "'.png'", ")" ]
https://github.com/generalized-intelligence/GAAS/blob/29ab17d3e8a4ba18edef3a57c36d8db6329fac73/deprecated/algorithms/sfm/dataset.py#L193-L195
wiseio/paratext
2e28660b48e61e7aa172129507206fcea6e57446
python/paratext/core.py
python
baseline_disk_to_mem
(filename, *args, **kwargs)
return count
This function copies the contents of a file into a collection of buffers. The buffers are then deallocated. This is useful for computing a baseline for performance metrics. It reads a file without any parsing, but the memory requirements grow with the size of the file. Parameters ---------- {0}
This function copies the contents of a file into a collection of buffers. The buffers are then deallocated. This is useful for computing a baseline for performance metrics. It reads a file without any parsing, but the memory requirements grow with the size of the file.
[ "This", "function", "copies", "the", "contents", "of", "a", "file", "into", "a", "collection", "of", "buffers", ".", "The", "buffers", "are", "then", "deallocated", ".", "This", "is", "useful", "for", "computing", "a", "baseline", "for", "performance", "metr...
def baseline_disk_to_mem(filename, *args, **kwargs): """ This function copies the contents of a file into a collection of buffers. The buffers are then deallocated. This is useful for computing a baseline for performance metrics. It reads a file without any parsing, but the memory requirements grow with the size of the file. Parameters ---------- {0} """ params = _get_params(*args, **kwargs) mc = pti.MemCopyBaseline(); count = mc.load(_make_posix_filename(filename), params) return count
[ "def", "baseline_disk_to_mem", "(", "filename", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "params", "=", "_get_params", "(", "*", "args", ",", "*", "*", "kwargs", ")", "mc", "=", "pti", ".", "MemCopyBaseline", "(", ")", "count", "=", "mc",...
https://github.com/wiseio/paratext/blob/2e28660b48e61e7aa172129507206fcea6e57446/python/paratext/core.py#L457-L471
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_core.py
python
BoxSizer.GetOrientation
(*args, **kwargs)
return _core_.BoxSizer_GetOrientation(*args, **kwargs)
GetOrientation(self) -> int Returns the current orientation of the sizer.
GetOrientation(self) -> int
[ "GetOrientation", "(", "self", ")", "-", ">", "int" ]
def GetOrientation(*args, **kwargs): """ GetOrientation(self) -> int Returns the current orientation of the sizer. """ return _core_.BoxSizer_GetOrientation(*args, **kwargs)
[ "def", "GetOrientation", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "BoxSizer_GetOrientation", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_core.py#L15093-L15099
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/telemetry/telemetry/android/shared_android_state.py
python
SharedAndroidState.TearDownState
(self)
Tear down anything created in the __init__ method that is not needed. Currently, there is no clean-up needed from SharedAndroidState.__init__.
Tear down anything created in the __init__ method that is not needed.
[ "Tear", "down", "anything", "created", "in", "the", "__init__", "method", "that", "is", "not", "needed", "." ]
def TearDownState(self): """Tear down anything created in the __init__ method that is not needed. Currently, there is no clean-up needed from SharedAndroidState.__init__. """ pass
[ "def", "TearDownState", "(", "self", ")", ":", "pass" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/telemetry/telemetry/android/shared_android_state.py#L73-L78
mongodb/mongo
d8ff665343ad29cf286ee2cf4a1960d29371937b
buildscripts/clang_format.py
python
format_func
(clang_format)
Format files command entry point.
Format files command entry point.
[ "Format", "files", "command", "entry", "point", "." ]
def format_func(clang_format): """Format files command entry point.""" files = git.get_files_to_check([], is_interesting_file) _format_files(clang_format, files)
[ "def", "format_func", "(", "clang_format", ")", ":", "files", "=", "git", ".", "get_files_to_check", "(", "[", "]", ",", "is_interesting_file", ")", "_format_files", "(", "clang_format", ",", "files", ")" ]
https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/buildscripts/clang_format.py#L394-L398
cvxpy/cvxpy
5165b4fb750dfd237de8659383ef24b4b2e33aaf
cvxpy/atoms/affine/unary_operators.py
python
NegExpression.sign_from_args
(self)
return (self.args[0].is_nonpos(), self.args[0].is_nonneg())
Returns sign (is positive, is negative) of the expression.
Returns sign (is positive, is negative) of the expression.
[ "Returns", "sign", "(", "is", "positive", "is", "negative", ")", "of", "the", "expression", "." ]
def sign_from_args(self) -> Tuple[bool, bool]: """Returns sign (is positive, is negative) of the expression. """ return (self.args[0].is_nonpos(), self.args[0].is_nonneg())
[ "def", "sign_from_args", "(", "self", ")", "->", "Tuple", "[", "bool", ",", "bool", "]", ":", "return", "(", "self", ".", "args", "[", "0", "]", ".", "is_nonpos", "(", ")", ",", "self", ".", "args", "[", "0", "]", ".", "is_nonneg", "(", ")", ")...
https://github.com/cvxpy/cvxpy/blob/5165b4fb750dfd237de8659383ef24b4b2e33aaf/cvxpy/atoms/affine/unary_operators.py#L52-L55
Polidea/SiriusObfuscator
b0e590d8130e97856afe578869b83a209e2b19be
SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py
python
SBBroadcaster.EventTypeHasListeners
(self, *args)
return _lldb.SBBroadcaster_EventTypeHasListeners(self, *args)
EventTypeHasListeners(self, uint32_t event_type) -> bool
EventTypeHasListeners(self, uint32_t event_type) -> bool
[ "EventTypeHasListeners", "(", "self", "uint32_t", "event_type", ")", "-", ">", "bool" ]
def EventTypeHasListeners(self, *args): """EventTypeHasListeners(self, uint32_t event_type) -> bool""" return _lldb.SBBroadcaster_EventTypeHasListeners(self, *args)
[ "def", "EventTypeHasListeners", "(", "self", ",", "*", "args", ")", ":", "return", "_lldb", ".", "SBBroadcaster_EventTypeHasListeners", "(", "self", ",", "*", "args", ")" ]
https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py#L1966-L1968
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
scripts/Inelastic/Direct/RunDescriptor.py
python
RunDescriptor._split_ws_name
(self,ws_name)
Method to split existing workspace name into parts, in such a way that _build_name would restore the same name
Method to split existing workspace name into parts, in such a way that _build_name would restore the same name
[ "Method", "to", "split", "existing", "workspace", "name", "into", "parts", "in", "such", "a", "way", "that", "_build_name", "would", "restore", "the", "same", "name" ]
def _split_ws_name(self,ws_name): """Method to split existing workspace name into parts, in such a way that _build_name would restore the same name """ # Remove suffix name = self.rremove(ws_name,self._ws_suffix) if self._run_list: summed = RunDescriptor._holder.sum_runs sumExt = self._run_list.sum_ext(summed) else: sumExt = '' if len(sumExt) > 0: name = self.rremove(ws_name,sumExt) # remove _prop_name: name = name.replace(self._prop_name,'',1) try: part_ind = re.search('#(.+?)#', name).group(0) name = name.replace(part_ind,'',1) except AttributeError: part_ind = '' if self._run_number: instr_name = self._instr_name() name = name.replace(instr_name,'',1) # Hell knows how to redefine these warnings or if they are valid or not #pylint: disable=W0141 #pylint: disable=W0110 self._ws_cname = part_ind + ''.join(re.findall(r'\D+', name)) else: #pylint: disable=attribute-defined-outside-init self._ws_cname = part_ind + name
[ "def", "_split_ws_name", "(", "self", ",", "ws_name", ")", ":", "# Remove suffix", "name", "=", "self", ".", "rremove", "(", "ws_name", ",", "self", ".", "_ws_suffix", ")", "if", "self", ".", "_run_list", ":", "summed", "=", "RunDescriptor", ".", "_holder"...
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/scripts/Inelastic/Direct/RunDescriptor.py#L1351-L1382
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/PIL/ImageFile.py
python
Parser.close
(self)
return self.image
(Consumer) Close the stream. :returns: An image object. :exception IOError: If the parser failed to parse the image file either because it cannot be identified or cannot be decoded.
(Consumer) Close the stream.
[ "(", "Consumer", ")", "Close", "the", "stream", "." ]
def close(self): """ (Consumer) Close the stream. :returns: An image object. :exception IOError: If the parser failed to parse the image file either because it cannot be identified or cannot be decoded. """ # finish decoding if self.decoder: # get rid of what's left in the buffers self.feed(b"") self.data = self.decoder = None if not self.finished: raise OSError("image was incomplete") if not self.image: raise OSError("cannot parse this image") if self.data: # incremental parsing not possible; reopen the file # not that we have all data with io.BytesIO(self.data) as fp: try: self.image = Image.open(fp) finally: self.image.load() return self.image
[ "def", "close", "(", "self", ")", ":", "# finish decoding", "if", "self", ".", "decoder", ":", "# get rid of what's left in the buffers", "self", ".", "feed", "(", "b\"\"", ")", "self", ".", "data", "=", "self", ".", "decoder", "=", "None", "if", "not", "s...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/PIL/ImageFile.py#L442-L468
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/numpy/py3/numpy/distutils/misc_util.py
python
is_local_src_dir
(directory)
return os.path.isdir(new_dir)
Return true if directory is local directory.
Return true if directory is local directory.
[ "Return", "true", "if", "directory", "is", "local", "directory", "." ]
def is_local_src_dir(directory): """Return true if directory is local directory. """ if not is_string(directory): return False abs_dir = os.path.abspath(directory) c = os.path.commonprefix([os.getcwd(), abs_dir]) new_dir = abs_dir[len(c):].split(os.sep) if new_dir and not new_dir[0]: new_dir = new_dir[1:] if new_dir and new_dir[0]=='build': return False new_dir = os.sep.join(new_dir) return os.path.isdir(new_dir)
[ "def", "is_local_src_dir", "(", "directory", ")", ":", "if", "not", "is_string", "(", "directory", ")", ":", "return", "False", "abs_dir", "=", "os", ".", "path", ".", "abspath", "(", "directory", ")", "c", "=", "os", ".", "path", ".", "commonprefix", ...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py3/numpy/distutils/misc_util.py#L558-L571
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/nn_ops.py
python
_convert_padding
(padding)
return padding, explicit_paddings
Converts Python padding to C++ padding for ops which take EXPLICIT padding. Args: padding: the `padding` argument for a Python op which supports EXPLICIT padding. Returns: (padding, explicit_paddings) pair, which should be passed as attributes to a C++ op. Raises: ValueError: If padding is invalid.
Converts Python padding to C++ padding for ops which take EXPLICIT padding.
[ "Converts", "Python", "padding", "to", "C", "++", "padding", "for", "ops", "which", "take", "EXPLICIT", "padding", "." ]
def _convert_padding(padding): """Converts Python padding to C++ padding for ops which take EXPLICIT padding. Args: padding: the `padding` argument for a Python op which supports EXPLICIT padding. Returns: (padding, explicit_paddings) pair, which should be passed as attributes to a C++ op. Raises: ValueError: If padding is invalid. """ explicit_paddings = [] if padding == "EXPLICIT": # Give a better error message if EXPLICIT is passed. raise ValueError('"EXPLICIT" is not a valid value for the padding ' "parameter. To use explicit padding, the padding " "parameter must be a list.") if isinstance(padding, (list, tuple)): for i, dim_paddings in enumerate(padding): if not isinstance(dim_paddings, (list, tuple)): raise ValueError("When padding is a list, each element of padding must " "be a list/tuple of size 2. Element with index %d of " "padding is not a list/tuple" % i) if len(dim_paddings) != 2: raise ValueError("When padding is a list, each element of padding must " "be a list/tuple of size 2. Element with index %d of " "padding has size %d" % (i, len(dim_paddings))) explicit_paddings.extend(dim_paddings) if len(padding) != 4: raise ValueError("When padding is a list, it must be of size 4. Got " "padding of size: %d" % len(padding)) padding = "EXPLICIT" return padding, explicit_paddings
[ "def", "_convert_padding", "(", "padding", ")", ":", "explicit_paddings", "=", "[", "]", "if", "padding", "==", "\"EXPLICIT\"", ":", "# Give a better error message if EXPLICIT is passed.", "raise", "ValueError", "(", "'\"EXPLICIT\" is not a valid value for the padding '", "\"...
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/nn_ops.py#L1549-L1584
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/flatmenu.py
python
FlatMenuBar.AddTool
(self, toolId, label="", bitmap1=wx.NullBitmap, bitmap2=wx.NullBitmap, kind=wx.ITEM_NORMAL, shortHelp="", longHelp="")
Adds a tool to the toolbar. :param integer `toolId`: an integer by which the tool may be identified in subsequent operations; :param string `label`: the tool label string; :param integer `kind`: may be ``wx.ITEM_NORMAL`` for a normal button (default), ``wx.ITEM_CHECK`` for a checkable tool (such tool stays pressed after it had been toggled) or ``wx.ITEM_RADIO`` for a checkable tool which makes part of a radio group of tools each of which is automatically unchecked whenever another button in the group is checked; :param `bitmap1`: the primary tool bitmap, an instance of :class:`Bitmap`; :param `bitmap2`: the bitmap used when the tool is disabled. If it is equal to :class:`NullBitmap`, the disabled bitmap is automatically generated by greing out the normal one; :param string `shortHelp`: a string used for the tools tooltip; :param string `longHelp`: this string is shown in the :class:`StatusBar` (if any) of the parent frame when the mouse pointer is inside the tool.
Adds a tool to the toolbar. :param integer `toolId`: an integer by which the tool may be identified in subsequent operations; :param string `label`: the tool label string; :param integer `kind`: may be ``wx.ITEM_NORMAL`` for a normal button (default), ``wx.ITEM_CHECK`` for a checkable tool (such tool stays pressed after it had been toggled) or ``wx.ITEM_RADIO`` for a checkable tool which makes part of a radio group of tools each of which is automatically unchecked whenever another button in the group is checked; :param `bitmap1`: the primary tool bitmap, an instance of :class:`Bitmap`; :param `bitmap2`: the bitmap used when the tool is disabled. If it is equal to :class:`NullBitmap`, the disabled bitmap is automatically generated by greing out the normal one; :param string `shortHelp`: a string used for the tools tooltip; :param string `longHelp`: this string is shown in the :class:`StatusBar` (if any) of the parent frame when the mouse pointer is inside the tool.
[ "Adds", "a", "tool", "to", "the", "toolbar", ".", ":", "param", "integer", "toolId", ":", "an", "integer", "by", "which", "the", "tool", "may", "be", "identified", "in", "subsequent", "operations", ";", ":", "param", "string", "label", ":", "the", "tool"...
def AddTool(self, toolId, label="", bitmap1=wx.NullBitmap, bitmap2=wx.NullBitmap, kind=wx.ITEM_NORMAL, shortHelp="", longHelp=""): """ Adds a tool to the toolbar. :param integer `toolId`: an integer by which the tool may be identified in subsequent operations; :param string `label`: the tool label string; :param integer `kind`: may be ``wx.ITEM_NORMAL`` for a normal button (default), ``wx.ITEM_CHECK`` for a checkable tool (such tool stays pressed after it had been toggled) or ``wx.ITEM_RADIO`` for a checkable tool which makes part of a radio group of tools each of which is automatically unchecked whenever another button in the group is checked; :param `bitmap1`: the primary tool bitmap, an instance of :class:`Bitmap`; :param `bitmap2`: the bitmap used when the tool is disabled. If it is equal to :class:`NullBitmap`, the disabled bitmap is automatically generated by greing out the normal one; :param string `shortHelp`: a string used for the tools tooltip; :param string `longHelp`: this string is shown in the :class:`StatusBar` (if any) of the parent frame when the mouse pointer is inside the tool. """ self._tbButtons.append(ToolBarItem(FlatToolbarItem(bitmap1, toolId, label, bitmap2, kind, shortHelp, longHelp), wx.Rect(), ControlNormal))
[ "def", "AddTool", "(", "self", ",", "toolId", ",", "label", "=", "\"\"", ",", "bitmap1", "=", "wx", ".", "NullBitmap", ",", "bitmap2", "=", "wx", ".", "NullBitmap", ",", "kind", "=", "wx", ".", "ITEM_NORMAL", ",", "shortHelp", "=", "\"\"", ",", "long...
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/flatmenu.py#L3671-L3693
deepmind/open_spiel
4ca53bea32bb2875c7385d215424048ae92f78c8
open_spiel/python/mfg/algorithms/policy_value.py
python
PolicyValue.evaluate
(self)
Evaluate the value over states of self._policy.
Evaluate the value over states of self._policy.
[ "Evaluate", "the", "value", "over", "states", "of", "self", ".", "_policy", "." ]
def evaluate(self): """Evaluate the value over states of self._policy.""" for state in self._root_states: self.eval_state(state)
[ "def", "evaluate", "(", "self", ")", ":", "for", "state", "in", "self", ".", "_root_states", ":", "self", ".", "eval_state", "(", "state", ")" ]
https://github.com/deepmind/open_spiel/blob/4ca53bea32bb2875c7385d215424048ae92f78c8/open_spiel/python/mfg/algorithms/policy_value.py#L96-L99
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/klampt/control/robotinterfaceutils.py
python
make_from_file
(fn : str, robotModel : RobotModel, *args,**kwargs)
return maker(robotModel,*args,**kwargs)
Create a RobotInterfaceBase from a Python file or module containing the ``make()`` function. args and kwargs will be passed to ``make``. Example:: iface = make_from_file('klampt.control.simrobotcontroller', robot)
Create a RobotInterfaceBase from a Python file or module containing the ``make()`` function.
[ "Create", "a", "RobotInterfaceBase", "from", "a", "Python", "file", "or", "module", "containing", "the", "make", "()", "function", "." ]
def make_from_file(fn : str, robotModel : RobotModel, *args,**kwargs) -> RobotInterfaceBase: """Create a RobotInterfaceBase from a Python file or module containing the ``make()`` function. args and kwargs will be passed to ``make``. Example:: iface = make_from_file('klampt.control.simrobotcontroller', robot) """ import importlib if fn.endswith('py') or fn.endswith('pyc'): import os import sys path,base = os.path.split(fn) mod_name,file_ext = os.path.splitext(base) sys.path.append(os.path.abspath(path)) mod = importlib.import_module(mod_name,base) sys.path.pop(-1) else: mod = importlib.import_module(fn) try: maker = mod.make except AttributeError: print("Module",mod.__name__,"must have a make() method") raise return maker(robotModel,*args,**kwargs)
[ "def", "make_from_file", "(", "fn", ":", "str", ",", "robotModel", ":", "RobotModel", ",", "*", "args", ",", "*", "*", "kwargs", ")", "->", "RobotInterfaceBase", ":", "import", "importlib", "if", "fn", ".", "endswith", "(", "'py'", ")", "or", "fn", "."...
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/control/robotinterfaceutils.py#L262-L288
Ifsttar/I-Simpa
2283385f4cac769a92e265edabb9c79cb6c42d03
currentRelease/SystemScript/graphy/backends/google_chart_api/encoders.py
python
BaseChartEncoder.Url
(self, width, height, use_html_entities=False)
return util.EncodeUrl(self.url_base, params, self.escape_url, use_html_entities)
Get the URL for our graph. Args: use_html_entities: If True, reserved HTML characters (&, <, >, ") in the URL are replaced with HTML entities (&amp;, &lt;, etc.). Default is False.
Get the URL for our graph.
[ "Get", "the", "URL", "for", "our", "graph", "." ]
def Url(self, width, height, use_html_entities=False): """Get the URL for our graph. Args: use_html_entities: If True, reserved HTML characters (&, <, >, ") in the URL are replaced with HTML entities (&amp;, &lt;, etc.). Default is False. """ self._width = width self._height = height params = self._Params(self.chart) return util.EncodeUrl(self.url_base, params, self.escape_url, use_html_entities)
[ "def", "Url", "(", "self", ",", "width", ",", "height", ",", "use_html_entities", "=", "False", ")", ":", "self", ".", "_width", "=", "width", "self", ".", "_height", "=", "height", "params", "=", "self", ".", "_Params", "(", "self", ".", "chart", ")...
https://github.com/Ifsttar/I-Simpa/blob/2283385f4cac769a92e265edabb9c79cb6c42d03/currentRelease/SystemScript/graphy/backends/google_chart_api/encoders.py#L54-L65
hughperkins/tf-coriander
970d3df6c11400ad68405f22b0c42a52374e94ca
tensorflow/contrib/distributions/python/ops/shape.py
python
_DistributionShape._introspect_ndims
(self, ndims)
return None, math_ops.equal(ndims, 0)
Helper to establish some properties of input ndims args.
Helper to establish some properties of input ndims args.
[ "Helper", "to", "establish", "some", "properties", "of", "input", "ndims", "args", "." ]
def _introspect_ndims(self, ndims): """Helper to establish some properties of input ndims args.""" if self._is_all_constant_helper(ndims): return (tensor_util.constant_value(ndims), tensor_util.constant_value(ndims) == 0) return None, math_ops.equal(ndims, 0)
[ "def", "_introspect_ndims", "(", "self", ",", "ndims", ")", ":", "if", "self", ".", "_is_all_constant_helper", "(", "ndims", ")", ":", "return", "(", "tensor_util", ".", "constant_value", "(", "ndims", ")", ",", "tensor_util", ".", "constant_value", "(", "nd...
https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/contrib/distributions/python/ops/shape.py#L464-L469
facebook/openr
ed38bdfd6bf290084bfab4821b59f83e7b59315d
openr/py/openr/cli/clis/prefix_mgr.py
python
AdvertisedRoutesCli.rejected_on_area
( cli_opts: bunch.Bunch, area: str, prefix: List[str] # noqa: B902 )
Show routes rejected by area policy on advertisement
Show routes rejected by area policy on advertisement
[ "Show", "routes", "rejected", "by", "area", "policy", "on", "advertisement" ]
def rejected_on_area( cli_opts: bunch.Bunch, area: str, prefix: List[str] # noqa: B902 ) -> None: """ Show routes rejected by area policy on advertisement """ opts = cli_opts.advertised_routes_options prefix_mgr.AreaAdvertisedRoutesCmd(cli_opts).run( area, ctrl_types.RouteFilterType.REJECTED_ON_ADVERTISE, prefix, opts.prefix_type, opts.json, opts.detail, )
[ "def", "rejected_on_area", "(", "cli_opts", ":", "bunch", ".", "Bunch", ",", "area", ":", "str", ",", "prefix", ":", "List", "[", "str", "]", "# noqa: B902", ")", "->", "None", ":", "opts", "=", "cli_opts", ".", "advertised_routes_options", "prefix_mgr", "...
https://github.com/facebook/openr/blob/ed38bdfd6bf290084bfab4821b59f83e7b59315d/openr/py/openr/cli/clis/prefix_mgr.py#L192-L207
apple/turicreate
cce55aa5311300e3ce6af93cb45ba791fd1bdf49
deps/src/libxml2-2.9.1/python/libxml2.py
python
xmlDoc.xpathNewContext
(self)
return __tmp
Create a new xmlXPathContext
Create a new xmlXPathContext
[ "Create", "a", "new", "xmlXPathContext" ]
def xpathNewContext(self): """Create a new xmlXPathContext """ ret = libxml2mod.xmlXPathNewContext(self._o) if ret is None:raise xpathError('xmlXPathNewContext() failed') __tmp = xpathContext(_obj=ret) return __tmp
[ "def", "xpathNewContext", "(", "self", ")", ":", "ret", "=", "libxml2mod", ".", "xmlXPathNewContext", "(", "self", ".", "_o", ")", "if", "ret", "is", "None", ":", "raise", "xpathError", "(", "'xmlXPathNewContext() failed'", ")", "__tmp", "=", "xpathContext", ...
https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/deps/src/libxml2-2.9.1/python/libxml2.py#L4869-L4874
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_misc.py
python
LogDebug
(*args, **kwargs)
return _misc_.LogDebug(*args, **kwargs)
LogDebug(String msg)
LogDebug(String msg)
[ "LogDebug", "(", "String", "msg", ")" ]
def LogDebug(*args, **kwargs): """LogDebug(String msg)""" return _misc_.LogDebug(*args, **kwargs)
[ "def", "LogDebug", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_misc_", ".", "LogDebug", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_misc.py#L1867-L1869
trailofbits/sienna-locomotive
09bc1a0bea7d7a33089422c62e0d3c715ecb7ce0
sl2/gui/__main__.py
python
MainWindow.handle_new_crash
(self, thread, run_id)
Updates the crash counter and pauses other threads if specified
Updates the crash counter and pauses other threads if specified
[ "Updates", "the", "crash", "counter", "and", "pauses", "other", "threads", "if", "specified" ]
def handle_new_crash(self, thread, run_id): """ Updates the crash counter and pauses other threads if specified """ self.crashes_model.update() self.crashes_table.resizeColumnsToContents() self.stats_widget.update() self.crash_counter.increment() crash = db.Crash.factory(run_id, get_target_slug(config.config)) if not crash: return None self.crashes.append(crash) if not thread.should_fuzz: self.pause_all_threads() # self.triage_output.append(str(crash)) self.crashes.append(crash)
[ "def", "handle_new_crash", "(", "self", ",", "thread", ",", "run_id", ")", ":", "self", ".", "crashes_model", ".", "update", "(", ")", "self", ".", "crashes_table", ".", "resizeColumnsToContents", "(", ")", "self", ".", "stats_widget", ".", "update", "(", ...
https://github.com/trailofbits/sienna-locomotive/blob/09bc1a0bea7d7a33089422c62e0d3c715ecb7ce0/sl2/gui/__main__.py#L426-L439
Z3Prover/z3
d745d03afdfdf638d66093e2bfbacaf87187f35b
src/api/python/z3/z3.py
python
Bool
(name, ctx=None)
return BoolRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), BoolSort(ctx).ast), ctx)
Return a Boolean constant named `name`. If `ctx=None`, then the global context is used. >>> p = Bool('p') >>> q = Bool('q') >>> And(p, q) And(p, q)
Return a Boolean constant named `name`. If `ctx=None`, then the global context is used.
[ "Return", "a", "Boolean", "constant", "named", "name", ".", "If", "ctx", "=", "None", "then", "the", "global", "context", "is", "used", "." ]
def Bool(name, ctx=None): """Return a Boolean constant named `name`. If `ctx=None`, then the global context is used. >>> p = Bool('p') >>> q = Bool('q') >>> And(p, q) And(p, q) """ ctx = _get_ctx(ctx) return BoolRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), BoolSort(ctx).ast), ctx)
[ "def", "Bool", "(", "name", ",", "ctx", "=", "None", ")", ":", "ctx", "=", "_get_ctx", "(", "ctx", ")", "return", "BoolRef", "(", "Z3_mk_const", "(", "ctx", ".", "ref", "(", ")", ",", "to_symbol", "(", "name", ",", "ctx", ")", ",", "BoolSort", "(...
https://github.com/Z3Prover/z3/blob/d745d03afdfdf638d66093e2bfbacaf87187f35b/src/api/python/z3/z3.py#L1696-L1705
facebook/watchman
0917460c71b000b96be9b9575d77f06f2f6053bb
build/fbcode_builder/getdeps/cargo.py
python
CargoBuilder._resolve_crate_to_path
(crate, git_conf)
Tries to find <crate> in git_conf["inst_dir"] by searching a [package] keyword followed by name = "<crate>".
Tries to find <crate> in git_conf["inst_dir"] by searching a [package] keyword followed by name = "<crate>".
[ "Tries", "to", "find", "<crate", ">", "in", "git_conf", "[", "inst_dir", "]", "by", "searching", "a", "[", "package", "]", "keyword", "followed", "by", "name", "=", "<crate", ">", "." ]
def _resolve_crate_to_path(crate, git_conf): """ Tries to find <crate> in git_conf["inst_dir"] by searching a [package] keyword followed by name = "<crate>". """ source_dir = git_conf["source_dir"] search_pattern = '[package]\nname = "{}"'.format(crate) for root, _, files in os.walk(source_dir): for fname in files: if fname == "Cargo.toml": with open(os.path.join(root, fname), "r") as f: if search_pattern in f.read(): return root raise Exception("Failed to found crate {} in path {}".format(crate, source_dir))
[ "def", "_resolve_crate_to_path", "(", "crate", ",", "git_conf", ")", ":", "source_dir", "=", "git_conf", "[", "\"source_dir\"", "]", "search_pattern", "=", "'[package]\\nname = \"{}\"'", ".", "format", "(", "crate", ")", "for", "root", ",", "_", ",", "files", ...
https://github.com/facebook/watchman/blob/0917460c71b000b96be9b9575d77f06f2f6053bb/build/fbcode_builder/getdeps/cargo.py#L300-L315
snap-stanford/snap-python
d53c51b0a26aa7e3e7400b014cdf728948fde80a
setup/snap.py
python
TNEANet.NodeAttrIsStrDeleted
(self, *args)
return _snap.TNEANet_NodeAttrIsStrDeleted(self, *args)
NodeAttrIsStrDeleted(TNEANet self, int const & NId, TStrIntPrH::TIter const & NodeHI) -> bool Parameters: NId: int const & NodeHI: TStrIntPrH::TIter const &
NodeAttrIsStrDeleted(TNEANet self, int const & NId, TStrIntPrH::TIter const & NodeHI) -> bool
[ "NodeAttrIsStrDeleted", "(", "TNEANet", "self", "int", "const", "&", "NId", "TStrIntPrH", "::", "TIter", "const", "&", "NodeHI", ")", "-", ">", "bool" ]
def NodeAttrIsStrDeleted(self, *args): """ NodeAttrIsStrDeleted(TNEANet self, int const & NId, TStrIntPrH::TIter const & NodeHI) -> bool Parameters: NId: int const & NodeHI: TStrIntPrH::TIter const & """ return _snap.TNEANet_NodeAttrIsStrDeleted(self, *args)
[ "def", "NodeAttrIsStrDeleted", "(", "self", ",", "*", "args", ")", ":", "return", "_snap", ".", "TNEANet_NodeAttrIsStrDeleted", "(", "self", ",", "*", "args", ")" ]
https://github.com/snap-stanford/snap-python/blob/d53c51b0a26aa7e3e7400b014cdf728948fde80a/setup/snap.py#L22428-L22437
openvinotoolkit/openvino
dedcbeafa8b84cccdc55ca64b8da516682b381c7
tools/mo/openvino/tools/mo/front/tf/extractors/utils.py
python
collect_tf_attrs
(attrs)
return ret_attrs
Function generates map for attributes and parsing functions param: attrs - TF proto message with attributes return: mapping attributes and parsing functions ready for use in update_node_stat function
Function generates map for attributes and parsing functions param: attrs - TF proto message with attributes return: mapping attributes and parsing functions ready for use in update_node_stat function
[ "Function", "generates", "map", "for", "attributes", "and", "parsing", "functions", "param", ":", "attrs", "-", "TF", "proto", "message", "with", "attributes", "return", ":", "mapping", "attributes", "and", "parsing", "functions", "ready", "for", "use", "in", ...
def collect_tf_attrs(attrs): """ Function generates map for attributes and parsing functions param: attrs - TF proto message with attributes return: mapping attributes and parsing functions ready for use in update_node_stat function """ ret_attrs = {} type_parsers = { 's': lambda x: x.s, 'i': lambda x: x.i, 'f': lambda x: x.f, 'b': lambda x: x.b, 'type': lambda x: tf_dtype_extractor(x.type), 'shape': lambda x: tf_tensor_shape(x.shape), 'list': lambda x: x.list } for a in attrs: t = check_attr_type(attrs[a]) a_l = attrs[a] while t == 'list': a_l = type_parsers[t](attrs[a]) t = check_attr_type(a_l) ret_attrs[a] = type_parsers[t](a_l) return ret_attrs
[ "def", "collect_tf_attrs", "(", "attrs", ")", ":", "ret_attrs", "=", "{", "}", "type_parsers", "=", "{", "'s'", ":", "lambda", "x", ":", "x", ".", "s", ",", "'i'", ":", "lambda", "x", ":", "x", ".", "i", ",", "'f'", ":", "lambda", "x", ":", "x"...
https://github.com/openvinotoolkit/openvino/blob/dedcbeafa8b84cccdc55ca64b8da516682b381c7/tools/mo/openvino/tools/mo/front/tf/extractors/utils.py#L135-L161
pmq20/node-packer
12c46c6e44fbc14d9ee645ebd17d5296b324f7e0
lts/tools/inspector_protocol/jinja2/lexer.py
python
count_newlines
(value)
return len(newline_re.findall(value))
Count the number of newline characters in the string. This is useful for extensions that filter a stream.
Count the number of newline characters in the string. This is useful for extensions that filter a stream.
[ "Count", "the", "number", "of", "newline", "characters", "in", "the", "string", ".", "This", "is", "useful", "for", "extensions", "that", "filter", "a", "stream", "." ]
def count_newlines(value): """Count the number of newline characters in the string. This is useful for extensions that filter a stream. """ return len(newline_re.findall(value))
[ "def", "count_newlines", "(", "value", ")", ":", "return", "len", "(", "newline_re", ".", "findall", "(", "value", ")", ")" ]
https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/lts/tools/inspector_protocol/jinja2/lexer.py#L189-L193
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python/src/Lib/fractions.py
python
Fraction._sub
(a, b)
return Fraction(a.numerator * b.denominator - b.numerator * a.denominator, a.denominator * b.denominator)
a - b
a - b
[ "a", "-", "b" ]
def _sub(a, b): """a - b""" return Fraction(a.numerator * b.denominator - b.numerator * a.denominator, a.denominator * b.denominator)
[ "def", "_sub", "(", "a", ",", "b", ")", ":", "return", "Fraction", "(", "a", ".", "numerator", "*", "b", ".", "denominator", "-", "b", ".", "numerator", "*", "a", ".", "denominator", ",", "a", ".", "denominator", "*", "b", ".", "denominator", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/fractions.py#L395-L399
MVIG-SJTU/RMPE
5188c230ec800c12be7369c3619615bc9b020aa4
scripts/cpp_lint.py
python
PrintUsage
(message)
Prints a brief usage string and exits, optionally with an error message. Args: message: The optional error message.
Prints a brief usage string and exits, optionally with an error message.
[ "Prints", "a", "brief", "usage", "string", "and", "exits", "optionally", "with", "an", "error", "message", "." ]
def PrintUsage(message): """Prints a brief usage string and exits, optionally with an error message. Args: message: The optional error message. """ sys.stderr.write(_USAGE) if message: sys.exit('\nFATAL ERROR: ' + message) else: sys.exit(1)
[ "def", "PrintUsage", "(", "message", ")", ":", "sys", ".", "stderr", ".", "write", "(", "_USAGE", ")", "if", "message", ":", "sys", ".", "exit", "(", "'\\nFATAL ERROR: '", "+", "message", ")", "else", ":", "sys", ".", "exit", "(", "1", ")" ]
https://github.com/MVIG-SJTU/RMPE/blob/5188c230ec800c12be7369c3619615bc9b020aa4/scripts/cpp_lint.py#L4761-L4771
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/targets/linalg.py
python
matrix_rank_impl
(a, tol=None)
return _get_matrix_rank_impl(a, tol)
Computes rank for matrices and vectors. The only issue that may arise is that because numpy uses double precision lapack calls whereas numba uses type specific lapack calls, some singular values may differ and therefore counting the number of them above a tolerance may lead to different counts, and therefore rank, in some cases.
Computes rank for matrices and vectors. The only issue that may arise is that because numpy uses double precision lapack calls whereas numba uses type specific lapack calls, some singular values may differ and therefore counting the number of them above a tolerance may lead to different counts, and therefore rank, in some cases.
[ "Computes", "rank", "for", "matrices", "and", "vectors", ".", "The", "only", "issue", "that", "may", "arise", "is", "that", "because", "numpy", "uses", "double", "precision", "lapack", "calls", "whereas", "numba", "uses", "type", "specific", "lapack", "calls",...
def matrix_rank_impl(a, tol=None): """ Computes rank for matrices and vectors. The only issue that may arise is that because numpy uses double precision lapack calls whereas numba uses type specific lapack calls, some singular values may differ and therefore counting the number of them above a tolerance may lead to different counts, and therefore rank, in some cases. """ ensure_lapack() _check_linalg_1_or_2d_matrix(a, "matrix_rank") def _2d_matrix_rank_impl(a, tol): # handle the tol==None case separately for type inference to work if tol in (None, types.none): nb_type = getattr(a.dtype, "underlying_float", a.dtype) np_type = np_support.as_dtype(nb_type) eps_val = np.finfo(np_type).eps def _2d_tol_none_impl(a, tol=None): s = _compute_singular_values(a) # replicate numpy default tolerance calculation r = a.shape[0] c = a.shape[1] l = max(r, c) t = s[0] * l * eps_val return _get_rank_from_singular_values(s, t) return _2d_tol_none_impl else: def _2d_tol_not_none_impl(a, tol=None): s = _compute_singular_values(a) return _get_rank_from_singular_values(s, tol) return _2d_tol_not_none_impl def _get_matrix_rank_impl(a, tol): ndim = a.ndim if ndim == 1: # NOTE: Technically, the numpy implementation could be argued as # incorrect for the case of a vector (1D matrix). If a tolerance # is provided and a vector with a singular value below tolerance is # encountered this should report a rank of zero, the numpy # implementation does not do this and instead elects to report that # if any value in the vector is nonzero then the rank is 1. # An example would be [0, 1e-15, 0, 2e-15] which numpy reports as # rank 1 invariant of `tol`. The singular value for this vector is # obviously sqrt(5)*1e-15 and so a tol of e.g. sqrt(6)*1e-15 should # lead to a reported rank of 0 whereas a tol of 1e-15 should lead # to a reported rank of 1, numpy reports 1 regardless. # The code below replicates the numpy behaviour. def _1d_matrix_rank_impl(a, tol=None): for k in range(len(a)): if a[k] != 0.: return 1 return 0 return _1d_matrix_rank_impl elif ndim == 2: return _2d_matrix_rank_impl(a, tol) else: assert 0 # unreachable return _get_matrix_rank_impl(a, tol)
[ "def", "matrix_rank_impl", "(", "a", ",", "tol", "=", "None", ")", ":", "ensure_lapack", "(", ")", "_check_linalg_1_or_2d_matrix", "(", "a", ",", "\"matrix_rank\"", ")", "def", "_2d_matrix_rank_impl", "(", "a", ",", "tol", ")", ":", "# handle the tol==None case ...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/targets/linalg.py#L2434-L2496
stellar-deprecated/stellard
67eabb2217bdfa9a6ea317f62338fb6bca458c90
src/protobuf/python/mox.py
python
MockMethod.AndRaise
(self, exception)
Set the exception to raise when this method is called. Args: # exception: the exception to raise when this method is called. exception: Exception
Set the exception to raise when this method is called.
[ "Set", "the", "exception", "to", "raise", "when", "this", "method", "is", "called", "." ]
def AndRaise(self, exception): """Set the exception to raise when this method is called. Args: # exception: the exception to raise when this method is called. exception: Exception """ self._exception = exception
[ "def", "AndRaise", "(", "self", ",", "exception", ")", ":", "self", ".", "_exception", "=", "exception" ]
https://github.com/stellar-deprecated/stellard/blob/67eabb2217bdfa9a6ea317f62338fb6bca458c90/src/protobuf/python/mox.py#L728-L736
mongodb/mongo
d8ff665343ad29cf286ee2cf4a1960d29371937b
src/third_party/scons-3.1.2/scons-local-3.1.2/SCons/Tool/pdflatex.py
python
generate
(env)
Add Builders and construction variables for pdflatex to an Environment.
Add Builders and construction variables for pdflatex to an Environment.
[ "Add", "Builders", "and", "construction", "variables", "for", "pdflatex", "to", "an", "Environment", "." ]
def generate(env): """Add Builders and construction variables for pdflatex to an Environment.""" global PDFLaTeXAction if PDFLaTeXAction is None: PDFLaTeXAction = SCons.Action.Action('$PDFLATEXCOM', '$PDFLATEXCOMSTR') global PDFLaTeXAuxAction if PDFLaTeXAuxAction is None: PDFLaTeXAuxAction = SCons.Action.Action(PDFLaTeXAuxFunction, strfunction=SCons.Tool.tex.TeXLaTeXStrFunction) env.AppendUnique(LATEXSUFFIXES=SCons.Tool.LaTeXSuffixes) from . import pdf pdf.generate(env) bld = env['BUILDERS']['PDF'] bld.add_action('.ltx', PDFLaTeXAuxAction) bld.add_action('.latex', PDFLaTeXAuxAction) bld.add_emitter('.ltx', SCons.Tool.tex.tex_pdf_emitter) bld.add_emitter('.latex', SCons.Tool.tex.tex_pdf_emitter) SCons.Tool.tex.generate_common(env)
[ "def", "generate", "(", "env", ")", ":", "global", "PDFLaTeXAction", "if", "PDFLaTeXAction", "is", "None", ":", "PDFLaTeXAction", "=", "SCons", ".", "Action", ".", "Action", "(", "'$PDFLATEXCOM'", ",", "'$PDFLATEXCOMSTR'", ")", "global", "PDFLaTeXAuxAction", "if...
https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/src/third_party/scons-3.1.2/scons-local-3.1.2/SCons/Tool/pdflatex.py#L52-L74
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/richtext.py
python
RichTextObject.DeleteRange
(*args, **kwargs)
return _richtext.RichTextObject_DeleteRange(*args, **kwargs)
DeleteRange(self, RichTextRange range) -> bool
DeleteRange(self, RichTextRange range) -> bool
[ "DeleteRange", "(", "self", "RichTextRange", "range", ")", "-", ">", "bool" ]
def DeleteRange(*args, **kwargs): """DeleteRange(self, RichTextRange range) -> bool""" return _richtext.RichTextObject_DeleteRange(*args, **kwargs)
[ "def", "DeleteRange", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_richtext", ".", "RichTextObject_DeleteRange", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/richtext.py#L1214-L1216
H-uru/Plasma
c2140ea046e82e9c199e257a7f2e7edb42602871
Scripts/Python/xSimpleImager.py
python
xSimpleImager.OnNotify
(self,state,id,events)
They've entered into the imager's region... inform them thru the KI
They've entered into the imager's region... inform them thru the KI
[ "They", "ve", "entered", "into", "the", "imager", "s", "region", "...", "inform", "them", "thru", "the", "KI" ]
def OnNotify(self,state,id,events): "They've entered into the imager's region... inform them thru the KI" global CurrentDisplayedElementID global RegionMembers #~ PtDebugPrint("xSimpleImager: Notify event state=%f,id=%d,events=" % (state,id),events) # is this our activator notifying us? if id == ImagerRegion.id: if PtWasLocallyNotified(self.key): ageMgr = ptVault() if PtIsInternalRelease() or (not ImagerMembersOnly.value or ageMgr.amOwnerOfCurrentAge()): if id == ImagerRegion.id: for event in events: if event[0] == kCollisionEvent: kiLevel = PtDetermineKILevel() if (kiLevel < kNormalKI): return if ImagerPelletUpload.value: messagetoki = str(ImagerName.value) + "<p>" else: messagetoki = ImagerName.value if event[1]: PtDebugPrint("xSimpleImager: add imager %s" % (ImagerName.value),level=kDebugDumpLevel) PtSendKIMessage(kAddPlayerDevice,messagetoki) RegionMembers = RegionMembers + 1 if (RegionMembers == 1): ImagerButtonResp.run(self.key,state='buttonOn') else: PtDebugPrint("xSimpleImager: remove imager %s" % (ImagerName.value),level=kDebugDumpLevel) PtSendKIMessage(kRemovePlayerDevice,messagetoki) RegionMembers = RegionMembers - 1 if (RegionMembers == -1): RegionMembers = 0 if (RegionMembers == 0): ImagerButtonResp.run(self.key,state='buttonOff') else: # else it must be a notification back to ourselves... # ...telling us to display a certain element for event in events: if event[0] == kVariableEvent: if event[1][:7] == "dispID=": newID = int(event[1][7:]) if newID != CurrentDisplayedElementID: CurrentDisplayedElementID = newID self.IShowCurrentContent() elif event[1][:7] == "Update=": newID = int(event[1][7:]) if not self.sceneobject.isLocallyOwned(): PtForceVaultNodeUpdate(newID) self.IShowCurrentContent() if newID == CurrentDisplayedElementID: self.IShowCurrentContent() elif event[1][:9] == "Uploaded=": newID = int(event[1][9:]) if newID == CurrentDisplayedElementID: self.IShowCurrentContent() elif event[1][:7] == "Upload=": deviceName = event[1][7:] nodeId = int(event[3]) if deviceName == ImagerName.value: ageVault = ptAgeVault() folder = ageVault.getDeviceInbox(ImagerName.value) if folder and PtWasLocallyNotified(self.key): folder.linkToNode(nodeId) selfnotify = ptNotify(self.key) selfnotify.clearReceivers() selfnotify.addReceiver(self.key) selfnotify.netPropagate(True) selfnotify.netForce(True) selfnotify.setActivate(1.0) sname = f"Uploaded={nodeId}" selfnotify.addVarNumber(sname, 1.0) selfnotify.send()
[ "def", "OnNotify", "(", "self", ",", "state", ",", "id", ",", "events", ")", ":", "global", "CurrentDisplayedElementID", "global", "RegionMembers", "#~ PtDebugPrint(\"xSimpleImager: Notify event state=%f,id=%d,events=\" % (state,id),events)", "# is this our activator notifying us?"...
https://github.com/H-uru/Plasma/blob/c2140ea046e82e9c199e257a7f2e7edb42602871/Scripts/Python/xSimpleImager.py#L270-L345
htcondor/htcondor
4829724575176d1d6c936e4693dfd78a728569b0
src/blahp/src/scripts/pbs_status.py
python
log
(msg)
A very lightweight log - not meant to be used in production, but helps when debugging scale tests
A very lightweight log - not meant to be used in production, but helps when debugging scale tests
[ "A", "very", "lightweight", "log", "-", "not", "meant", "to", "be", "used", "in", "production", "but", "helps", "when", "debugging", "scale", "tests" ]
def log(msg): """ A very lightweight log - not meant to be used in production, but helps when debugging scale tests """ print(time.strftime("%x %X"), os.getpid(), msg, file=sys.stderr)
[ "def", "log", "(", "msg", ")", ":", "print", "(", "time", ".", "strftime", "(", "\"%x %X\"", ")", ",", "os", ".", "getpid", "(", ")", ",", "msg", ",", "file", "=", "sys", ".", "stderr", ")" ]
https://github.com/htcondor/htcondor/blob/4829724575176d1d6c936e4693dfd78a728569b0/src/blahp/src/scripts/pbs_status.py#L57-L62
D-X-Y/caffe-faster-rcnn
eb50c97ff48f3df115d0e85fe0a32b0c7e2aa4cb
scripts/cpp_lint.py
python
_CppLintState.SetVerboseLevel
(self, level)
return last_verbose_level
Sets the module's verbosity, and returns the previous setting.
Sets the module's verbosity, and returns the previous setting.
[ "Sets", "the", "module", "s", "verbosity", "and", "returns", "the", "previous", "setting", "." ]
def SetVerboseLevel(self, level): """Sets the module's verbosity, and returns the previous setting.""" last_verbose_level = self.verbose_level self.verbose_level = level return last_verbose_level
[ "def", "SetVerboseLevel", "(", "self", ",", "level", ")", ":", "last_verbose_level", "=", "self", ".", "verbose_level", "self", ".", "verbose_level", "=", "level", "return", "last_verbose_level" ]
https://github.com/D-X-Y/caffe-faster-rcnn/blob/eb50c97ff48f3df115d0e85fe0a32b0c7e2aa4cb/scripts/cpp_lint.py#L711-L715
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemFramework/v1/AWS/common-code/lib/urllib3/response.py
python
HTTPResponse._init_length
(self, request_method)
return length
Set initial length value for Response content if available.
Set initial length value for Response content if available.
[ "Set", "initial", "length", "value", "for", "Response", "content", "if", "available", "." ]
def _init_length(self, request_method): """ Set initial length value for Response content if available. """ length = self.headers.get("content-length") if length is not None: if self.chunked: # This Response will fail with an IncompleteRead if it can't be # received as chunked. This method falls back to attempt reading # the response before raising an exception. log.warning( "Received response with both Content-Length and " "Transfer-Encoding set. This is expressly forbidden " "by RFC 7230 sec 3.3.2. Ignoring Content-Length and " "attempting to process response as Transfer-Encoding: " "chunked." ) return None try: # RFC 7230 section 3.3.2 specifies multiple content lengths can # be sent in a single Content-Length header # (e.g. Content-Length: 42, 42). This line ensures the values # are all valid ints and that as long as the `set` length is 1, # all values are the same. Otherwise, the header is invalid. lengths = set([int(val) for val in length.split(",")]) if len(lengths) > 1: raise InvalidHeader( "Content-Length contained multiple " "unmatching values (%s)" % length ) length = lengths.pop() except ValueError: length = None else: if length < 0: length = None # Convert status to int for comparison # In some cases, httplib returns a status of "_UNKNOWN" try: status = int(self.status) except ValueError: status = 0 # Check for responses that shouldn't include a body if status in (204, 304) or 100 <= status < 200 or request_method == "HEAD": length = 0 return length
[ "def", "_init_length", "(", "self", ",", "request_method", ")", ":", "length", "=", "self", ".", "headers", ".", "get", "(", "\"content-length\"", ")", "if", "length", "is", "not", "None", ":", "if", "self", ".", "chunked", ":", "# This Response will fail wi...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/AWS/common-code/lib/urllib3/response.py#L304-L354
hughperkins/tf-coriander
970d3df6c11400ad68405f22b0c42a52374e94ca
tensorflow/contrib/learn/python/learn/estimators/estimator.py
python
Estimator.__init__
(self, model_fn=None, model_dir=None, config=None, params=None, feature_engineering_fn=None)
Constructs an Estimator instance. Args: model_fn: Model function, takes features and targets tensors or dicts of tensors and returns predictions and loss tensors. Supports next three signatures for the function: * `(features, targets) -> (predictions, loss, train_op)` * `(features, targets, mode) -> (predictions, loss, train_op)` * `(features, targets, mode, params) -> (predictions, loss, train_op)` Where * `features` are single `Tensor` or `dict` of `Tensor`s (depending on data passed to `fit`), * `targets` are `Tensor` or `dict` of `Tensor`s (for multi-head models). If mode is `ModeKeys.INFER`, `targets=None` will be passed. If the `model_fn`'s signature does not accept `mode`, the `model_fn` must still be able to handle `targets=None`. * `mode` represents if this training, evaluation or prediction. See `ModeKeys`. * `params` is a `dict` of hyperparameters. Will receive what is passed to Estimator in `params` parameter. This allows to configure Estimators from hyper parameter tunning. model_dir: Directory to save model parameters, graph and etc. This can also be used to load checkpoints from the directory into a estimator to continue training a previously saved model. config: Configuration object. params: `dict` of hyper parameters that will be passed into `model_fn`. Keys are names of parameters, values are basic python types. feature_engineering_fn: Feature engineering function. Takes features and targets which are the output of `input_fn` and returns features and targets which will be fed into `model_fn`. Please check `model_fn` for a definition of features and targets. Raises: ValueError: parameters of `model_fn` don't match `params`.
Constructs an Estimator instance.
[ "Constructs", "an", "Estimator", "instance", "." ]
def __init__(self, model_fn=None, model_dir=None, config=None, params=None, feature_engineering_fn=None): """Constructs an Estimator instance. Args: model_fn: Model function, takes features and targets tensors or dicts of tensors and returns predictions and loss tensors. Supports next three signatures for the function: * `(features, targets) -> (predictions, loss, train_op)` * `(features, targets, mode) -> (predictions, loss, train_op)` * `(features, targets, mode, params) -> (predictions, loss, train_op)` Where * `features` are single `Tensor` or `dict` of `Tensor`s (depending on data passed to `fit`), * `targets` are `Tensor` or `dict` of `Tensor`s (for multi-head models). If mode is `ModeKeys.INFER`, `targets=None` will be passed. If the `model_fn`'s signature does not accept `mode`, the `model_fn` must still be able to handle `targets=None`. * `mode` represents if this training, evaluation or prediction. See `ModeKeys`. * `params` is a `dict` of hyperparameters. Will receive what is passed to Estimator in `params` parameter. This allows to configure Estimators from hyper parameter tunning. model_dir: Directory to save model parameters, graph and etc. This can also be used to load checkpoints from the directory into a estimator to continue training a previously saved model. config: Configuration object. params: `dict` of hyper parameters that will be passed into `model_fn`. Keys are names of parameters, values are basic python types. feature_engineering_fn: Feature engineering function. Takes features and targets which are the output of `input_fn` and returns features and targets which will be fed into `model_fn`. Please check `model_fn` for a definition of features and targets. Raises: ValueError: parameters of `model_fn` don't match `params`. """ super(Estimator, self).__init__(model_dir=model_dir, config=config) if model_fn is not None: # Check number of arguments of the given function matches requirements. model_fn_args = _get_arguments(model_fn) if params is not None and 'params' not in model_fn_args: raise ValueError('Estimator\'s model_fn (%s) has less than 4 ' 'arguments, but not None params (%s) are passed.' % (model_fn, params)) if params is None and 'params' in model_fn_args: logging.warning('Estimator\'s model_fn (%s) has includes params ' 'argument, but params are not passed to Estimator.', model_fn) self._model_fn = model_fn self.params = params self._feature_engineering_fn = ( feature_engineering_fn or _identity_feature_engineering_fn)
[ "def", "__init__", "(", "self", ",", "model_fn", "=", "None", ",", "model_dir", "=", "None", ",", "config", "=", "None", ",", "params", "=", "None", ",", "feature_engineering_fn", "=", "None", ")", ":", "super", "(", "Estimator", ",", "self", ")", ".",...
https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/contrib/learn/python/learn/estimators/estimator.py#L876-L938
xlgames-inc/XLE
cdd8682367d9e9fdbdda9f79d72bb5b1499cec46
Foreign/FreeType/src/tools/docmaker/tohtml.py
python
HtmlFormatter.make_html_items
( self, items )
return string.join( lines, '\n' )
Convert a field's content into HTML.
Convert a field's content into HTML.
[ "Convert", "a", "field", "s", "content", "into", "HTML", "." ]
def make_html_items( self, items ): """Convert a field's content into HTML.""" lines = [] for item in items: if item.lines: lines.append( self.make_html_code( item.lines ) ) else: lines.append( self.make_html_para( item.words ) ) return string.join( lines, '\n' )
[ "def", "make_html_items", "(", "self", ",", "items", ")", ":", "lines", "=", "[", "]", "for", "item", "in", "items", ":", "if", "item", ".", "lines", ":", "lines", ".", "append", "(", "self", ".", "make_html_code", "(", "item", ".", "lines", ")", "...
https://github.com/xlgames-inc/XLE/blob/cdd8682367d9e9fdbdda9f79d72bb5b1499cec46/Foreign/FreeType/src/tools/docmaker/tohtml.py#L373-L382
fifengine/fifengine
4b62c42e85bec19893cef8e63e6855927cff2c47
engine/python/fife/extensions/serializers/xml_loader_tools.py
python
root_subfile
(masterfile, subfile)
return pathstr
Returns new path for given subfile (path), which is rooted against masterfile E.g. if masterfile is ./../foo/bar.xml and subfile is ./../foo2/subfoo.xml, returned path is ../foo2/subfoo.xml NOTE: masterfile is expected to be *file*, not directory. subfile can be either
Returns new path for given subfile (path), which is rooted against masterfile E.g. if masterfile is ./../foo/bar.xml and subfile is ./../foo2/subfoo.xml, returned path is ../foo2/subfoo.xml NOTE: masterfile is expected to be *file*, not directory. subfile can be either
[ "Returns", "new", "path", "for", "given", "subfile", "(", "path", ")", "which", "is", "rooted", "against", "masterfile", "E", ".", "g", ".", "if", "masterfile", "is", ".", "/", "..", "/", "foo", "/", "bar", ".", "xml", "and", "subfile", "is", ".", ...
def root_subfile(masterfile, subfile): """ Returns new path for given subfile (path), which is rooted against masterfile E.g. if masterfile is ./../foo/bar.xml and subfile is ./../foo2/subfoo.xml, returned path is ../foo2/subfoo.xml NOTE: masterfile is expected to be *file*, not directory. subfile can be either """ s = '/' masterfile = norm_path(os.path.abspath(masterfile)) subfile = norm_path(os.path.abspath(subfile)) master_fragments = masterfile.split(s) sub_fragments = subfile.split(s) master_leftovers = [] sub_leftovers = [] for i in range(len(master_fragments)): try: if master_fragments[i] == sub_fragments[i]: master_leftovers = master_fragments[i+1:] sub_leftovers = sub_fragments[i+1:] except IndexError: break pathstr = '' for f in master_leftovers[:-1]: pathstr += '..' + s pathstr += s.join(sub_leftovers) return pathstr
[ "def", "root_subfile", "(", "masterfile", ",", "subfile", ")", ":", "s", "=", "'/'", "masterfile", "=", "norm_path", "(", "os", ".", "path", ".", "abspath", "(", "masterfile", ")", ")", "subfile", "=", "norm_path", "(", "os", ".", "path", ".", "abspath...
https://github.com/fifengine/fifengine/blob/4b62c42e85bec19893cef8e63e6855927cff2c47/engine/python/fife/extensions/serializers/xml_loader_tools.py#L67-L97
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/coverage/coverage/annotate.py
python
AnnotateReporter.report
(self, morfs, directory=None)
Run the report. See `coverage.report()` for arguments.
Run the report.
[ "Run", "the", "report", "." ]
def report(self, morfs, directory=None): """Run the report. See `coverage.report()` for arguments. """ self.report_files(self.annotate_file, morfs, directory)
[ "def", "report", "(", "self", ",", "morfs", ",", "directory", "=", "None", ")", ":", "self", ".", "report_files", "(", "self", ".", "annotate_file", ",", "morfs", ",", "directory", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/coverage/coverage/annotate.py#L46-L52
vtraag/louvain-igraph
124ea1be49ee74eec2eaca8006599d7fc5560db6
src/louvain/functions.py
python
find_partition_temporal
(graphs, partition_type, interslice_weight=1, slice_attr='slice', vertex_id_attr='id', edge_type_attr='type', weight_attr='weight', seed=None, **kwargs)
return membership_time_slices, improvement
Detect communities for temporal graphs. Each graph is considered to represent a time slice and does not necessarily need to be defined on the same set of vertices. Nodes in two consecutive slices are identified on the basis of the ``vertex_id_attr``, i.e. if two nodes in two consecutive slices have an identical value of the ``vertex_id_attr`` they are coupled. The ``vertex_id_attr`` should hence be unique in each slice. The nodes are then coupled with a weight of ``interslice_weight`` which is set in the edge attribute ``weight_attr``. No weight is set if the ``interslice_weight`` is None (i.e. corresponding in practice with a weight of 1). See :func:`time_slices_to_layers` for a more detailed explanation. Parameters ---------- graphs : list of :class:`ig.Graph` List of :class:`louvain.VertexPartition` layers to optimise. partition_type : type of :class:`VertexPartition.MutableVertexPartition` The type of partition to use for optimisation (identical for all graphs). interslice_weight : float The weight of the coupling between two consecutive time slices. slice_attr : string The vertex attribute to use for indicating the slice of a node. vertex_id_attr : string The vertex to use to identify nodes. edge_type_attr : string The edge attribute to use for indicating the type of link (`interslice` or `intraslice`). weight_attr : string The edge attribute used to indicate the weight. seed : int Seed for the random number generator. By default uses a random seed if nothing is specified. **kwargs Remaining keyword arguments, passed on to constructor of ``partition_type``. Returns ------- list of membership list containing for each slice the membership vector. float Improvement in quality of combined partitions, see :func:`Optimiser.optimise_partition_multiplex`. See Also -------- :func:`time_slices_to_layers` :func:`slices_to_layers` Examples -------- >>> n = 100 >>> G_1 = ig.Graph.Lattice([n], 1) >>> G_1.vs['id'] = range(n) >>> G_2 = ig.Graph.Lattice([n], 1) >>> G_2.vs['id'] = range(n) >>> membership, improvement = louvain.find_partition_temporal([G_1, G_2], ... louvain.ModularityVertexPartition, ... interslice_weight=1)
Detect communities for temporal graphs.
[ "Detect", "communities", "for", "temporal", "graphs", "." ]
def find_partition_temporal(graphs, partition_type, interslice_weight=1, slice_attr='slice', vertex_id_attr='id', edge_type_attr='type', weight_attr='weight', seed=None, **kwargs): """ Detect communities for temporal graphs. Each graph is considered to represent a time slice and does not necessarily need to be defined on the same set of vertices. Nodes in two consecutive slices are identified on the basis of the ``vertex_id_attr``, i.e. if two nodes in two consecutive slices have an identical value of the ``vertex_id_attr`` they are coupled. The ``vertex_id_attr`` should hence be unique in each slice. The nodes are then coupled with a weight of ``interslice_weight`` which is set in the edge attribute ``weight_attr``. No weight is set if the ``interslice_weight`` is None (i.e. corresponding in practice with a weight of 1). See :func:`time_slices_to_layers` for a more detailed explanation. Parameters ---------- graphs : list of :class:`ig.Graph` List of :class:`louvain.VertexPartition` layers to optimise. partition_type : type of :class:`VertexPartition.MutableVertexPartition` The type of partition to use for optimisation (identical for all graphs). interslice_weight : float The weight of the coupling between two consecutive time slices. slice_attr : string The vertex attribute to use for indicating the slice of a node. vertex_id_attr : string The vertex to use to identify nodes. edge_type_attr : string The edge attribute to use for indicating the type of link (`interslice` or `intraslice`). weight_attr : string The edge attribute used to indicate the weight. seed : int Seed for the random number generator. By default uses a random seed if nothing is specified. **kwargs Remaining keyword arguments, passed on to constructor of ``partition_type``. Returns ------- list of membership list containing for each slice the membership vector. float Improvement in quality of combined partitions, see :func:`Optimiser.optimise_partition_multiplex`. See Also -------- :func:`time_slices_to_layers` :func:`slices_to_layers` Examples -------- >>> n = 100 >>> G_1 = ig.Graph.Lattice([n], 1) >>> G_1.vs['id'] = range(n) >>> G_2 = ig.Graph.Lattice([n], 1) >>> G_2.vs['id'] = range(n) >>> membership, improvement = louvain.find_partition_temporal([G_1, G_2], ... louvain.ModularityVertexPartition, ... interslice_weight=1) """ # Create layers G_layers, G_interslice, G = time_slices_to_layers(graphs, interslice_weight, slice_attr=slice_attr, vertex_id_attr=vertex_id_attr, edge_type_attr=edge_type_attr, weight_attr=weight_attr) # Optimise partitions arg_dict = {} if 'node_sizes' in partition_type.__init__.__code__.co_varnames: arg_dict['node_sizes'] = 'node_size' if 'weights' in partition_type.__init__.__code__.co_varnames: arg_dict['weights'] = 'weight' arg_dict.update(kwargs) partitions = [] for H in G_layers: arg_dict['graph'] = H partitions.append(partition_type(**arg_dict)) # We can always take the same interslice partition, as this should have no # cost in the optimisation. partition_interslice = CPMVertexPartition(G_interslice, resolution_parameter=0, node_sizes='node_size', weights=weight_attr) optimiser = Optimiser() if (not seed is None): optimiser.set_rng_seed(seed) improvement = optimiser.optimise_partition_multiplex(partitions + [partition_interslice]) # Transform results back into original form. membership = {(v[slice_attr], v[vertex_id_attr]): m for v, m in zip(G.vs, partitions[0].membership)} membership_time_slices = [] for slice_idx, H in enumerate(graphs): membership_slice = [membership[(slice_idx, v[vertex_id_attr])] for v in H.vs] membership_time_slices.append(list(membership_slice)) return membership_time_slices, improvement
[ "def", "find_partition_temporal", "(", "graphs", ",", "partition_type", ",", "interslice_weight", "=", "1", ",", "slice_attr", "=", "'slice'", ",", "vertex_id_attr", "=", "'id'", ",", "edge_type_attr", "=", "'type'", ",", "weight_attr", "=", "'weight'", ",", "se...
https://github.com/vtraag/louvain-igraph/blob/124ea1be49ee74eec2eaca8006599d7fc5560db6/src/louvain/functions.py#L144-L260
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py2/pandas/core/internals/blocks.py
python
Block._try_coerce_args
(self, values, other)
return values, other
provide coercion to our input arguments
provide coercion to our input arguments
[ "provide", "coercion", "to", "our", "input", "arguments" ]
def _try_coerce_args(self, values, other): """ provide coercion to our input arguments """ if np.any(notna(other)) and not self._can_hold_element(other): # coercion issues # let higher levels handle raise TypeError("cannot convert {} to an {}".format( type(other).__name__, type(self).__name__.lower().replace('Block', ''))) return values, other
[ "def", "_try_coerce_args", "(", "self", ",", "values", ",", "other", ")", ":", "if", "np", ".", "any", "(", "notna", "(", "other", ")", ")", "and", "not", "self", ".", "_can_hold_element", "(", "other", ")", ":", "# coercion issues", "# let higher levels h...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py2/pandas/core/internals/blocks.py#L709-L719
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/weights_broadcast_ops.py
python
assert_broadcastable
(weights, values)
Asserts `weights` can be broadcast to `values`. In `tf.losses` and `tf.metrics`, we support limited weight broadcasting. We let weights be either scalar, or the same rank as the target values, with each dimension either 1, or the same as the corresponding values dimension. Args: weights: `Tensor` of weights. values: `Tensor` of values to which weights are applied. Returns: `Operation` raising `InvalidArgumentError` if `weights` has incorrect shape. `no_op` if static checks determine `weights` has correct shape. Raises: ValueError: If static checks determine `weights` has incorrect shape.
Asserts `weights` can be broadcast to `values`.
[ "Asserts", "weights", "can", "be", "broadcast", "to", "values", "." ]
def assert_broadcastable(weights, values): """Asserts `weights` can be broadcast to `values`. In `tf.losses` and `tf.metrics`, we support limited weight broadcasting. We let weights be either scalar, or the same rank as the target values, with each dimension either 1, or the same as the corresponding values dimension. Args: weights: `Tensor` of weights. values: `Tensor` of values to which weights are applied. Returns: `Operation` raising `InvalidArgumentError` if `weights` has incorrect shape. `no_op` if static checks determine `weights` has correct shape. Raises: ValueError: If static checks determine `weights` has incorrect shape. """ with ops.name_scope(None, "assert_broadcastable", (weights, values)) as scope: with ops.name_scope(None, "weights", (weights,)) as weights_scope: weights = ops.convert_to_tensor(weights, name=weights_scope) weights_shape = array_ops.shape(weights, name="shape") weights_rank = array_ops.rank(weights, name="rank") weights_rank_static = tensor_util.constant_value(weights_rank) with ops.name_scope(None, "values", (values,)) as values_scope: values = ops.convert_to_tensor(values, name=values_scope) values_shape = array_ops.shape(values, name="shape") values_rank = array_ops.rank(values, name="rank") values_rank_static = tensor_util.constant_value(values_rank) # Try static checks. if weights_rank_static is not None and values_rank_static is not None: if weights_rank_static == 0: return control_flow_ops.no_op(name="static_scalar_check_success") if weights_rank_static != values_rank_static: raise ValueError( "%s values.rank=%s. weights.rank=%s." " values.shape=%s. weights.shape=%s." % ( _ASSERT_BROADCASTABLE_ERROR_PREFIX, values_rank_static, weights_rank_static, values.shape, weights.shape)) weights_shape_static = tensor_util.constant_value(weights_shape) values_shape_static = tensor_util.constant_value(values_shape) if weights_shape_static is not None and values_shape_static is not None: # Sanity check, this should always be true since we checked rank above. ndims = len(values_shape_static) assert ndims == len(weights_shape_static) for i in range(ndims): if weights_shape_static[i] not in (1, values_shape_static[i]): raise ValueError( "%s Mismatch at dim %s. values.shape=%s weights.shape=%s." % ( _ASSERT_BROADCASTABLE_ERROR_PREFIX, i, values_shape_static, weights_shape_static)) return control_flow_ops.no_op(name="static_dims_check_success") # Dynamic checks. is_scalar = math_ops.equal(0, weights_rank, name="is_scalar") data = ( _ASSERT_BROADCASTABLE_ERROR_PREFIX, "weights.shape=", weights.name, weights_shape, "values.shape=", values.name, values_shape, "is_scalar=", is_scalar, ) is_valid_shape = control_flow_ops.cond( is_scalar, lambda: is_scalar, lambda: _has_valid_nonscalar_shape( # pylint: disable=g-long-lambda weights_rank, weights_shape, values_rank, values_shape), name="is_valid_shape") return control_flow_ops.Assert(is_valid_shape, data, name=scope)
[ "def", "assert_broadcastable", "(", "weights", ",", "values", ")", ":", "with", "ops", ".", "name_scope", "(", "None", ",", "\"assert_broadcastable\"", ",", "(", "weights", ",", "values", ")", ")", "as", "scope", ":", "with", "ops", ".", "name_scope", "(",...
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/weights_broadcast_ops.py#L63-L133
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/pkg_resources/__init__.py
python
register_loader_type
(loader_type, provider_factory)
Register `provider_factory` to make providers for `loader_type` `loader_type` is the type or class of a PEP 302 ``module.__loader__``, and `provider_factory` is a function that, passed a *module* object, returns an ``IResourceProvider`` for that module.
Register `provider_factory` to make providers for `loader_type`
[ "Register", "provider_factory", "to", "make", "providers", "for", "loader_type" ]
def register_loader_type(loader_type, provider_factory): """Register `provider_factory` to make providers for `loader_type` `loader_type` is the type or class of a PEP 302 ``module.__loader__``, and `provider_factory` is a function that, passed a *module* object, returns an ``IResourceProvider`` for that module. """ _provider_factories[loader_type] = provider_factory
[ "def", "register_loader_type", "(", "loader_type", ",", "provider_factory", ")", ":", "_provider_factories", "[", "loader_type", "]", "=", "provider_factory" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/pkg_resources/__init__.py#L344-L351
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/tempfile.py
python
_candidate_tempdir_list
()
return dirlist
Generate a list of candidate temporary directories which _get_default_tempdir will try.
Generate a list of candidate temporary directories which _get_default_tempdir will try.
[ "Generate", "a", "list", "of", "candidate", "temporary", "directories", "which", "_get_default_tempdir", "will", "try", "." ]
def _candidate_tempdir_list(): """Generate a list of candidate temporary directories which _get_default_tempdir will try.""" dirlist = [] # First, try the environment. for envname in 'TMPDIR', 'TEMP', 'TMP': dirname = _os.getenv(envname) if dirname: dirlist.append(dirname) # Failing that, try OS-specific locations. if _os.name == 'nt': dirlist.extend([ _os.path.expanduser(r'~\AppData\Local\Temp'), _os.path.expandvars(r'%SYSTEMROOT%\Temp'), r'c:\temp', r'c:\tmp', r'\temp', r'\tmp' ]) else: dirlist.extend([ '/tmp', '/var/tmp', '/usr/tmp' ]) # As a last resort, the current directory. try: dirlist.append(_os.getcwd()) except (AttributeError, OSError): dirlist.append(_os.curdir) return dirlist
[ "def", "_candidate_tempdir_list", "(", ")", ":", "dirlist", "=", "[", "]", "# First, try the environment.", "for", "envname", "in", "'TMPDIR'", ",", "'TEMP'", ",", "'TMP'", ":", "dirname", "=", "_os", ".", "getenv", "(", "envname", ")", "if", "dirname", ":",...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/tempfile.py#L159-L184
gv22ga/dlib-face-recognition-android
42d6305cbd85833f2b85bb79b70ab9ab004153c9
tools/lint/cpplint.py
python
GetLineWidth
(line)
Determines the width of the line in column positions. Args: line: A string, which may be a Unicode string. Returns: The width of the line in column positions, accounting for Unicode combining characters and wide characters.
Determines the width of the line in column positions. Args: line: A string, which may be a Unicode string. Returns: The width of the line in column positions, accounting for Unicode combining characters and wide characters.
[ "Determines", "the", "width", "of", "the", "line", "in", "column", "positions", ".", "Args", ":", "line", ":", "A", "string", "which", "may", "be", "a", "Unicode", "string", ".", "Returns", ":", "The", "width", "of", "the", "line", "in", "column", "pos...
def GetLineWidth(line): """Determines the width of the line in column positions. Args: line: A string, which may be a Unicode string. Returns: The width of the line in column positions, accounting for Unicode combining characters and wide characters. """ if isinstance(line, unicode): width = 0 for uc in unicodedata.normalize('NFC', line): if unicodedata.east_asian_width(uc) in ('W', 'F'): width += 2 elif not unicodedata.combining(uc): width += 1 return width else: return len(line)
[ "def", "GetLineWidth", "(", "line", ")", ":", "if", "isinstance", "(", "line", ",", "unicode", ")", ":", "width", "=", "0", "for", "uc", "in", "unicodedata", ".", "normalize", "(", "'NFC'", ",", "line", ")", ":", "if", "unicodedata", ".", "east_asian_w...
https://github.com/gv22ga/dlib-face-recognition-android/blob/42d6305cbd85833f2b85bb79b70ab9ab004153c9/tools/lint/cpplint.py#L4047-L4064
pmq20/node-packer
12c46c6e44fbc14d9ee645ebd17d5296b324f7e0
lts/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/xcode_emulation.py
python
XcodeArchsDefault.ActiveArchs
(self, archs, valid_archs, sdkroot)
return expanded_archs
Expands variables references in ARCHS, and filter by VALID_ARCHS if it is defined (if not set, Xcode accept any value in ARCHS, otherwise, only values present in VALID_ARCHS are kept).
Expands variables references in ARCHS, and filter by VALID_ARCHS if it is defined (if not set, Xcode accept any value in ARCHS, otherwise, only values present in VALID_ARCHS are kept).
[ "Expands", "variables", "references", "in", "ARCHS", "and", "filter", "by", "VALID_ARCHS", "if", "it", "is", "defined", "(", "if", "not", "set", "Xcode", "accept", "any", "value", "in", "ARCHS", "otherwise", "only", "values", "present", "in", "VALID_ARCHS", ...
def ActiveArchs(self, archs, valid_archs, sdkroot): """Expands variables references in ARCHS, and filter by VALID_ARCHS if it is defined (if not set, Xcode accept any value in ARCHS, otherwise, only values present in VALID_ARCHS are kept).""" expanded_archs = self._ExpandArchs(archs or self._default, sdkroot or '') if valid_archs: filtered_archs = [] for arch in expanded_archs: if arch in valid_archs: filtered_archs.append(arch) expanded_archs = filtered_archs return expanded_archs
[ "def", "ActiveArchs", "(", "self", ",", "archs", ",", "valid_archs", ",", "sdkroot", ")", ":", "expanded_archs", "=", "self", ".", "_ExpandArchs", "(", "archs", "or", "self", ".", "_default", ",", "sdkroot", "or", "''", ")", "if", "valid_archs", ":", "fi...
https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/lts/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/xcode_emulation.py#L85-L96
trilinos/Trilinos
6168be6dd51e35e1cd681e9c4b24433e709df140
packages/seacas/scripts/exodus2.in.py
python
basename
(file_name)
return base_name
Extract base name from file_name. basename("test.e") -> "test"
Extract base name from file_name. basename("test.e") -> "test"
[ "Extract", "base", "name", "from", "file_name", ".", "basename", "(", "test", ".", "e", ")", "-", ">", "test" ]
def basename(file_name): """ Extract base name from file_name. basename("test.e") -> "test" """ fileParts = file_name.split(".") base_name = ".".join(fileParts[:-1]) return base_name
[ "def", "basename", "(", "file_name", ")", ":", "fileParts", "=", "file_name", ".", "split", "(", "\".\"", ")", "base_name", "=", "\".\"", ".", "join", "(", "fileParts", "[", ":", "-", "1", "]", ")", "return", "base_name" ]
https://github.com/trilinos/Trilinos/blob/6168be6dd51e35e1cd681e9c4b24433e709df140/packages/seacas/scripts/exodus2.in.py#L45-L52
snap-stanford/snap-python
d53c51b0a26aa7e3e7400b014cdf728948fde80a
setup/snap.py
python
TStr.PutFExt
(*args)
return _snap.TStr_PutFExt(*args)
PutFExt(TStr FNm, TStr FExt) -> TStr Parameters: FNm: TStr const & FExt: TStr const &
PutFExt(TStr FNm, TStr FExt) -> TStr
[ "PutFExt", "(", "TStr", "FNm", "TStr", "FExt", ")", "-", ">", "TStr" ]
def PutFExt(*args): """ PutFExt(TStr FNm, TStr FExt) -> TStr Parameters: FNm: TStr const & FExt: TStr const & """ return _snap.TStr_PutFExt(*args)
[ "def", "PutFExt", "(", "*", "args", ")", ":", "return", "_snap", ".", "TStr_PutFExt", "(", "*", "args", ")" ]
https://github.com/snap-stanford/snap-python/blob/d53c51b0a26aa7e3e7400b014cdf728948fde80a/setup/snap.py#L10848-L10857
GoSSIP-SJTU/Armariris
ad5d868482956b2194a77b39c8d543c7c2318200
tools/clang/bindings/python/clang/cindex.py
python
FileInclusion.is_input_file
(self)
return self.depth == 0
True if the included file is the input file.
True if the included file is the input file.
[ "True", "if", "the", "included", "file", "is", "the", "input", "file", "." ]
def is_input_file(self): """True if the included file is the input file.""" return self.depth == 0
[ "def", "is_input_file", "(", "self", ")", ":", "return", "self", ".", "depth", "==", "0" ]
https://github.com/GoSSIP-SJTU/Armariris/blob/ad5d868482956b2194a77b39c8d543c7c2318200/tools/clang/bindings/python/clang/cindex.py#L2717-L2719
RobotLocomotion/drake
0e18a34604c45ed65bc9018a54f7610f91cdad5b
common/proto/call_python_client.py
python
CallPythonClient.handle_messages
(self, max_count=None, record=True, execute=True)
return (count, msgs)
Handle all messages sent (e.g., through IPython). @param max_count Maximum number of messages to handle. @param record Record all messages and return them. @param execute Execute the given message upon receiving it. @return (count, msgs) where `count` is how many messages were processed (e.g. 0 if no more messages left). and `msgs` are either the messages themselves for playback. and (b) the messages themselves for playback (if record==True), otherwise an empty list.
Handle all messages sent (e.g., through IPython).
[ "Handle", "all", "messages", "sent", "(", "e", ".", "g", ".", "through", "IPython", ")", "." ]
def handle_messages(self, max_count=None, record=True, execute=True): """Handle all messages sent (e.g., through IPython). @param max_count Maximum number of messages to handle. @param record Record all messages and return them. @param execute Execute the given message upon receiving it. @return (count, msgs) where `count` is how many messages were processed (e.g. 0 if no more messages left). and `msgs` are either the messages themselves for playback. and (b) the messages themselves for playback (if record==True), otherwise an empty list. """ assert record or execute, "Not doing anything useful?" count = 0 msgs = [] for msg in self._read_next_message(): if execute: self._execute_message(msg) count += 1 if record: msgs.append(msg) if max_count is not None and count >= max_count: break return (count, msgs)
[ "def", "handle_messages", "(", "self", ",", "max_count", "=", "None", ",", "record", "=", "True", ",", "execute", "=", "True", ")", ":", "assert", "record", "or", "execute", ",", "\"Not doing anything useful?\"", "count", "=", "0", "msgs", "=", "[", "]", ...
https://github.com/RobotLocomotion/drake/blob/0e18a34604c45ed65bc9018a54f7610f91cdad5b/common/proto/call_python_client.py#L486-L508
BlzFans/wke
b0fa21158312e40c5fbd84682d643022b6c34a93
cygwin/lib/python2.6/distutils/ccompiler.py
python
CCompiler.set_runtime_library_dirs
(self, dirs)
Set the list of directories to search for shared libraries at runtime to 'dirs' (a list of strings). This does not affect any standard search path that the runtime linker may search by default.
Set the list of directories to search for shared libraries at runtime to 'dirs' (a list of strings). This does not affect any standard search path that the runtime linker may search by default.
[ "Set", "the", "list", "of", "directories", "to", "search", "for", "shared", "libraries", "at", "runtime", "to", "dirs", "(", "a", "list", "of", "strings", ")", ".", "This", "does", "not", "affect", "any", "standard", "search", "path", "that", "the", "run...
def set_runtime_library_dirs (self, dirs): """Set the list of directories to search for shared libraries at runtime to 'dirs' (a list of strings). This does not affect any standard search path that the runtime linker may search by default. """ self.runtime_library_dirs = copy (dirs)
[ "def", "set_runtime_library_dirs", "(", "self", ",", "dirs", ")", ":", "self", ".", "runtime_library_dirs", "=", "copy", "(", "dirs", ")" ]
https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/distutils/ccompiler.py#L308-L314
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/collections.py
python
OrderedDict.__eq__
(self, other)
return dict.__eq__(self, other)
od.__eq__(y) <==> od==y. Comparison to another OD is order-sensitive while comparison to a regular mapping is order-insensitive.
od.__eq__(y) <==> od==y. Comparison to another OD is order-sensitive while comparison to a regular mapping is order-insensitive.
[ "od", ".", "__eq__", "(", "y", ")", "<", "==", ">", "od", "==", "y", ".", "Comparison", "to", "another", "OD", "is", "order", "-", "sensitive", "while", "comparison", "to", "a", "regular", "mapping", "is", "order", "-", "insensitive", "." ]
def __eq__(self, other): '''od.__eq__(y) <==> od==y. Comparison to another OD is order-sensitive while comparison to a regular mapping is order-insensitive. ''' if isinstance(other, OrderedDict): return dict.__eq__(self, other) and all(_imap(_eq, self, other)) return dict.__eq__(self, other)
[ "def", "__eq__", "(", "self", ",", "other", ")", ":", "if", "isinstance", "(", "other", ",", "OrderedDict", ")", ":", "return", "dict", ".", "__eq__", "(", "self", ",", "other", ")", "and", "all", "(", "_imap", "(", "_eq", ",", "self", ",", "other"...
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/collections.py#L202-L209
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/tools/Editra/src/eclib/pstatbar.py
python
ProgressStatusBar.GetGauge
(self)
return self.prog
Return the wx.Gauge used by this window @return: wx.Gauge
Return the wx.Gauge used by this window @return: wx.Gauge
[ "Return", "the", "wx", ".", "Gauge", "used", "by", "this", "window", "@return", ":", "wx", ".", "Gauge" ]
def GetGauge(self): """Return the wx.Gauge used by this window @return: wx.Gauge """ return self.prog
[ "def", "GetGauge", "(", "self", ")", ":", "return", "self", ".", "prog" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/eclib/pstatbar.py#L136-L141
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemFramework/v1/AWS/resource-manager-code/lib/jsonschema/validators.py
python
RefResolver.resolve_from_url
(self, url)
return self.resolve_fragment(document, fragment)
Resolve the given remote URL.
Resolve the given remote URL.
[ "Resolve", "the", "given", "remote", "URL", "." ]
def resolve_from_url(self, url): """ Resolve the given remote URL. """ url, fragment = urldefrag(url) try: document = self.store[url] except KeyError: try: document = self.resolve_remote(url) except Exception as exc: raise exceptions.RefResolutionError(exc) return self.resolve_fragment(document, fragment)
[ "def", "resolve_from_url", "(", "self", ",", "url", ")", ":", "url", ",", "fragment", "=", "urldefrag", "(", "url", ")", "try", ":", "document", "=", "self", ".", "store", "[", "url", "]", "except", "KeyError", ":", "try", ":", "document", "=", "self...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/AWS/resource-manager-code/lib/jsonschema/validators.py#L768-L781
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_vendor/urllib3/contrib/securetransport.py
python
_read_callback
(connection_id, data_buffer, data_length_pointer)
SecureTransport read callback. This is called by ST to request that data be returned from the socket.
SecureTransport read callback. This is called by ST to request that data be returned from the socket.
[ "SecureTransport", "read", "callback", ".", "This", "is", "called", "by", "ST", "to", "request", "that", "data", "be", "returned", "from", "the", "socket", "." ]
def _read_callback(connection_id, data_buffer, data_length_pointer): """ SecureTransport read callback. This is called by ST to request that data be returned from the socket. """ wrapped_socket = None try: wrapped_socket = _connection_refs.get(connection_id) if wrapped_socket is None: return SecurityConst.errSSLInternal base_socket = wrapped_socket.socket requested_length = data_length_pointer[0] timeout = wrapped_socket.gettimeout() error = None read_count = 0 try: while read_count < requested_length: if timeout is None or timeout >= 0: if not util.wait_for_read(base_socket, timeout): raise socket.error(errno.EAGAIN, "timed out") remaining = requested_length - read_count buffer = (ctypes.c_char * remaining).from_address( data_buffer + read_count ) chunk_size = base_socket.recv_into(buffer, remaining) read_count += chunk_size if not chunk_size: if not read_count: return SecurityConst.errSSLClosedGraceful break except (socket.error) as e: error = e.errno if error is not None and error != errno.EAGAIN: data_length_pointer[0] = read_count if error == errno.ECONNRESET or error == errno.EPIPE: return SecurityConst.errSSLClosedAbort raise data_length_pointer[0] = read_count if read_count != requested_length: return SecurityConst.errSSLWouldBlock return 0 except Exception as e: if wrapped_socket is not None: wrapped_socket._exception = e return SecurityConst.errSSLInternal
[ "def", "_read_callback", "(", "connection_id", ",", "data_buffer", ",", "data_length_pointer", ")", ":", "wrapped_socket", "=", "None", "try", ":", "wrapped_socket", "=", "_connection_refs", ".", "get", "(", "connection_id", ")", "if", "wrapped_socket", "is", "Non...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_vendor/urllib3/contrib/securetransport.py#L211-L263
miyosuda/TensorFlowAndroidMNIST
7b5a4603d2780a8a2834575706e9001977524007
jni-build/jni/include/tensorflow/contrib/distributions/python/ops/operator_pd_vdvt_update.py
python
OperatorPDSqrtVDVTUpdate.get_shape
(self)
return self._operator.get_shape()
Static `TensorShape` of entire operator. If this operator represents the batch matrix `A` with `A.shape = [N1,...,Nn, k, k]`, then this returns `TensorShape([N1,...,Nn, k, k])` Returns: `TensorShape`, statically determined, may be undefined.
Static `TensorShape` of entire operator.
[ "Static", "TensorShape", "of", "entire", "operator", "." ]
def get_shape(self): """Static `TensorShape` of entire operator. If this operator represents the batch matrix `A` with `A.shape = [N1,...,Nn, k, k]`, then this returns `TensorShape([N1,...,Nn, k, k])` Returns: `TensorShape`, statically determined, may be undefined. """ return self._operator.get_shape()
[ "def", "get_shape", "(", "self", ")", ":", "return", "self", ".", "_operator", ".", "get_shape", "(", ")" ]
https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/contrib/distributions/python/ops/operator_pd_vdvt_update.py#L272-L282