nwo
stringlengths
5
106
sha
stringlengths
40
40
path
stringlengths
4
174
language
stringclasses
1 value
identifier
stringlengths
1
140
parameters
stringlengths
0
87.7k
argument_list
stringclasses
1 value
return_statement
stringlengths
0
426k
docstring
stringlengths
0
64.3k
docstring_summary
stringlengths
0
26.3k
docstring_tokens
list
function
stringlengths
18
4.83M
function_tokens
list
url
stringlengths
83
304
researchmm/tasn
5dba8ccc096cedc63913730eeea14a9647911129
tasn-mxnet/3rdparty/tvm/topi/python/topi/nn/depthwise_conv2d.py
python
depthwise_conv2d_nchw
(Input, Filter, stride, padding, out_dtype=None)
return Output
Depthwise convolution nchw forward operator. Parameters ---------- Input : tvm.Tensor 4-D with shape [batch, in_channel, in_height, in_width] Filter : tvm.Tensor 4-D with shape [in_channel, channel_multiplier, filter_height, filter_width] stride : tuple of two ints The spatial stride along height and width padding : int or str Padding size, or ['VALID', 'SAME'] out_dtype: str, optional Output data type Returns ------- Output : tvm.Tensor 4-D with shape [batch, out_channel, out_height, out_width]
Depthwise convolution nchw forward operator.
[ "Depthwise", "convolution", "nchw", "forward", "operator", "." ]
def depthwise_conv2d_nchw(Input, Filter, stride, padding, out_dtype=None): """Depthwise convolution nchw forward operator. Parameters ---------- Input : tvm.Tensor 4-D with shape [batch, in_channel, in_height, in_width] Filter : tvm.Tensor 4-D with shape [in_channel, channel_multiplier, filter_height, filter_width] stride : tuple of two ints The spatial stride along height and width padding : int or str Padding size, or ['VALID', 'SAME'] out_dtype: str, optional Output data type Returns ------- Output : tvm.Tensor 4-D with shape [batch, out_channel, out_height, out_width] """ out_dtype = Input.dtype if out_dtype is None else out_dtype batch, in_channel, in_height, in_width = Input.shape filter_channel, channel_multiplier, filter_height, filter_width = Filter.shape if isinstance(stride, int): stride_h = stride_w = stride else: stride_h, stride_w = stride pad_top, pad_left, pad_down, pad_right = get_pad_tuple( padding, (filter_height, filter_width)) out_channel = simplify(in_channel * channel_multiplier) out_height = simplify((in_height - filter_height + pad_top + pad_down) // stride_h + 1) out_width = simplify((in_width - filter_width + pad_left + pad_right) // stride_w + 1) # padding stage pad_before = [0, 0, pad_top, pad_left] pad_after = [0, 0, pad_down, pad_right] PaddedInput = pad(Input, pad_before, pad_after, name="PaddedInput") # depthconv stage di = tvm.reduce_axis((0, filter_height), name='di') dj = tvm.reduce_axis((0, filter_width), name='dj') Output = tvm.compute( (batch, out_channel, out_height, out_width), lambda b, c, i, j: tvm.sum( (PaddedInput[b, c/channel_multiplier, i*stride_h+di, j*stride_w+dj].astype(out_dtype) * Filter[c/channel_multiplier, c%channel_multiplier, di, dj].astype(out_dtype)), axis=[di, dj]), name='DepthwiseConv2d', tag="depthwise_conv2d_nchw") return Output
[ "def", "depthwise_conv2d_nchw", "(", "Input", ",", "Filter", ",", "stride", ",", "padding", ",", "out_dtype", "=", "None", ")", ":", "out_dtype", "=", "Input", ".", "dtype", "if", "out_dtype", "is", "None", "else", "out_dtype", "batch", ",", "in_channel", ...
https://github.com/researchmm/tasn/blob/5dba8ccc096cedc63913730eeea14a9647911129/tasn-mxnet/3rdparty/tvm/topi/python/topi/nn/depthwise_conv2d.py#L13-L67
tensorflow/tensor2tensor
2a33b152d7835af66a6d20afe7961751047e28dd
tensor2tensor/data_generators/dialog_abstract.py
python
DialogAbstract.download_data
(self, train_mode)
Download data from official sources. Args: train_mode: string, whether we are in train, dev or test mode
Download data from official sources.
[ "Download", "data", "from", "official", "sources", "." ]
def download_data(self, train_mode): """Download data from official sources. Args: train_mode: string, whether we are in train, dev or test mode """ # Open the url and download the data with progress bars. data_stream = requests.get(self._url, stream=True) with open(self._zipped_data, 'wb') as f: for chunk in data_stream.iter_content(1024): if chunk: f.write(chunk) f.flush() # Next step is extracting the data. print('problem_log: Extracting data to ' + self._zipped_data + '.') self.extract_data(train_mode)
[ "def", "download_data", "(", "self", ",", "train_mode", ")", ":", "# Open the url and download the data with progress bars.", "data_stream", "=", "requests", ".", "get", "(", "self", ".", "_url", ",", "stream", "=", "True", ")", "with", "open", "(", "self", ".",...
https://github.com/tensorflow/tensor2tensor/blob/2a33b152d7835af66a6d20afe7961751047e28dd/tensor2tensor/data_generators/dialog_abstract.py#L205-L222
HoloClean/holoclean
d4f5929a8e4d92d4f41eb058c04c96cdcb0af767
repair/featurize/featurized_dataset.py
python
FeaturizedDataset.get_infer_data
(self)
return X_infer, mask_infer, infer_idx
Retrieves the samples to be inferred i.e. DK cells.
Retrieves the samples to be inferred i.e. DK cells.
[ "Retrieves", "the", "samples", "to", "be", "inferred", "i", ".", "e", ".", "DK", "cells", "." ]
def get_infer_data(self): """ Retrieves the samples to be inferred i.e. DK cells. """ # only infer on those that are DK cells infer_idx = (self.is_clean == 0).nonzero()[:, 0] X_infer = self.tensor.index_select(0, infer_idx) mask_infer = self.var_class_mask.index_select(0, infer_idx) return X_infer, mask_infer, infer_idx
[ "def", "get_infer_data", "(", "self", ")", ":", "# only infer on those that are DK cells", "infer_idx", "=", "(", "self", ".", "is_clean", "==", "0", ")", ".", "nonzero", "(", ")", "[", ":", ",", "0", "]", "X_infer", "=", "self", ".", "tensor", ".", "ind...
https://github.com/HoloClean/holoclean/blob/d4f5929a8e4d92d4f41eb058c04c96cdcb0af767/repair/featurize/featurized_dataset.py#L139-L147
Parsl/parsl
af2535341152b2640fdd1a3b73b891992bf1b3ea
parsl/executors/base.py
python
ParslExecutor.set_bad_state_and_fail_all
(self, exception: Exception)
Allows external error handlers to mark this executor as irrecoverably bad and cause all tasks submitted to it now and in the future to fail. The executor is responsible for checking :method:bad_state_is_set() in the :method:submit() method and raising the appropriate exception, which is available through :method:executor_exception().
Allows external error handlers to mark this executor as irrecoverably bad and cause all tasks submitted to it now and in the future to fail. The executor is responsible for checking :method:bad_state_is_set() in the :method:submit() method and raising the appropriate exception, which is available through :method:executor_exception().
[ "Allows", "external", "error", "handlers", "to", "mark", "this", "executor", "as", "irrecoverably", "bad", "and", "cause", "all", "tasks", "submitted", "to", "it", "now", "and", "in", "the", "future", "to", "fail", ".", "The", "executor", "is", "responsible"...
def set_bad_state_and_fail_all(self, exception: Exception): """Allows external error handlers to mark this executor as irrecoverably bad and cause all tasks submitted to it now and in the future to fail. The executor is responsible for checking :method:bad_state_is_set() in the :method:submit() method and raising the appropriate exception, which is available through :method:executor_exception(). """ pass
[ "def", "set_bad_state_and_fail_all", "(", "self", ",", "exception", ":", "Exception", ")", ":", "pass" ]
https://github.com/Parsl/parsl/blob/af2535341152b2640fdd1a3b73b891992bf1b3ea/parsl/executors/base.py#L185-L191
golismero/golismero
7d605b937e241f51c1ca4f47b20f755eeefb9d76
golismero/main/orchestrator.py
python
Orchestrator.__control_c_handler
(self, signum, frame)
Signal handler to catch Control-C interrupts.
Signal handler to catch Control-C interrupts.
[ "Signal", "handler", "to", "catch", "Control", "-", "C", "interrupts", "." ]
def __control_c_handler(self, signum, frame): """ Signal handler to catch Control-C interrupts. """ try: # Tell the user the message has been sent. Console.display("User cancel requested, stopping all audits...") # Send a stop message to the Orchestrator. message = Message(message_type = MessageType.MSG_TYPE_CONTROL, message_code = MessageCode.MSG_CONTROL_STOP, message_info = False, priority = MessagePriority.MSG_PRIORITY_HIGH) try: self.messageManager.put(message) except: print_exc() exit(1) finally: # Only do this once, the next time just PANIC. signal(SIGINT, self.__panic_control_c_handler)
[ "def", "__control_c_handler", "(", "self", ",", "signum", ",", "frame", ")", ":", "try", ":", "# Tell the user the message has been sent.", "Console", ".", "display", "(", "\"User cancel requested, stopping all audits...\"", ")", "# Send a stop message to the Orchestrator.", ...
https://github.com/golismero/golismero/blob/7d605b937e241f51c1ca4f47b20f755eeefb9d76/golismero/main/orchestrator.py#L253-L277
FederatedAI/FATE
32540492623568ecd1afcb367360133616e02fa3
python/federatedml/secureprotol/spdz/tensor/fixedpoint_numpy.py
python
PaillierFixedPointTensor.__radd__
(self, other)
return self.__add__(other)
[]
def __radd__(self, other): return self.__add__(other)
[ "def", "__radd__", "(", "self", ",", "other", ")", ":", "return", "self", ".", "__add__", "(", "other", ")" ]
https://github.com/FederatedAI/FATE/blob/32540492623568ecd1afcb367360133616e02fa3/python/federatedml/secureprotol/spdz/tensor/fixedpoint_numpy.py#L302-L303
KalleHallden/AutoTimer
2d954216700c4930baa154e28dbddc34609af7ce
env/lib/python2.7/site-packages/pip/_vendor/pkg_resources/__init__.py
python
WorkingSet.subscribe
(self, callback, existing=True)
Invoke `callback` for all distributions If `existing=True` (default), call on all existing ones, as well.
Invoke `callback` for all distributions
[ "Invoke", "callback", "for", "all", "distributions" ]
def subscribe(self, callback, existing=True): """Invoke `callback` for all distributions If `existing=True` (default), call on all existing ones, as well. """ if callback in self.callbacks: return self.callbacks.append(callback) if not existing: return for dist in self: callback(dist)
[ "def", "subscribe", "(", "self", ",", "callback", ",", "existing", "=", "True", ")", ":", "if", "callback", "in", "self", ".", "callbacks", ":", "return", "self", ".", "callbacks", ".", "append", "(", "callback", ")", "if", "not", "existing", ":", "ret...
https://github.com/KalleHallden/AutoTimer/blob/2d954216700c4930baa154e28dbddc34609af7ce/env/lib/python2.7/site-packages/pip/_vendor/pkg_resources/__init__.py#L907-L919
googlefonts/gftools
8ad55dd4d7e38729524329c79f236476f1576e67
Lib/gftools/packager.py
python
_shallow_clone_git
(target_dir, git_url, branch_or_tag='main')
return subprocess.run(['git', 'clone', '--depth', '1', '--bare' , '-b', branch_or_tag, git_url , target_dir], check=True , stdout=subprocess.PIPE)
getting this as a shallow copy, because for some files we want to search in the filesystem. branch_or_tag: as used in `git clone -b` NOTE: libgit2 and hence pygit2 doesn't support shallow clones yet, but that's the most lightweight way to get the whole directory structure.
getting this as a shallow copy, because for some files we want to search in the filesystem.
[ "getting", "this", "as", "a", "shallow", "copy", "because", "for", "some", "files", "we", "want", "to", "search", "in", "the", "filesystem", "." ]
def _shallow_clone_git(target_dir, git_url, branch_or_tag='main'): """ getting this as a shallow copy, because for some files we want to search in the filesystem. branch_or_tag: as used in `git clone -b` NOTE: libgit2 and hence pygit2 doesn't support shallow clones yet, but that's the most lightweight way to get the whole directory structure. """ # I don't understand why git clone doesn't take this more explicit form. # But, I recommended it in the docs, so here's a little fix. if branch_or_tag.startswith('tags/'): branch_or_tag = branch_or_tag[len('tags/'):] return subprocess.run(['git', 'clone', '--depth', '1', '--bare' , '-b', branch_or_tag, git_url , target_dir], check=True , stdout=subprocess.PIPE)
[ "def", "_shallow_clone_git", "(", "target_dir", ",", "git_url", ",", "branch_or_tag", "=", "'main'", ")", ":", "# I don't understand why git clone doesn't take this more explicit form.", "# But, I recommended it in the docs, so here's a little fix.", "if", "branch_or_tag", ".", "st...
https://github.com/googlefonts/gftools/blob/8ad55dd4d7e38729524329c79f236476f1576e67/Lib/gftools/packager.py#L219-L239
lightforever/mlcomp
c78fdb77ec9c4ec8ff11beea50b90cab20903ad9
mlcomp/contrib/dataset/classify.py
python
ImageDataset.preprocess_row
(self, row: dict)
[]
def preprocess_row(self, row: dict): row['image'] = join(self.img_folder, row['image'])
[ "def", "preprocess_row", "(", "self", ",", "row", ":", "dict", ")", ":", "row", "[", "'image'", "]", "=", "join", "(", "self", ".", "img_folder", ",", "row", "[", "'image'", "]", ")" ]
https://github.com/lightforever/mlcomp/blob/c78fdb77ec9c4ec8ff11beea50b90cab20903ad9/mlcomp/contrib/dataset/classify.py#L76-L77
sahana/eden
1696fa50e90ce967df69f66b571af45356cc18da
controllers/project.py
python
task
()
return project_task_controller()
RESTful CRUD controller
RESTful CRUD controller
[ "RESTful", "CRUD", "controller" ]
def task(): """ RESTful CRUD controller """ from s3db.project import project_task_controller return project_task_controller()
[ "def", "task", "(", ")", ":", "from", "s3db", ".", "project", "import", "project_task_controller", "return", "project_task_controller", "(", ")" ]
https://github.com/sahana/eden/blob/1696fa50e90ce967df69f66b571af45356cc18da/controllers/project.py#L1020-L1024
playframework/play1
0ecac3bc2421ae2dbec27a368bf671eda1c9cba5
python/Lib/mailbox.py
python
Babyl._generate_toc
(self)
Generate key-to-(start, stop) table of contents.
Generate key-to-(start, stop) table of contents.
[ "Generate", "key", "-", "to", "-", "(", "start", "stop", ")", "table", "of", "contents", "." ]
def _generate_toc(self): """Generate key-to-(start, stop) table of contents.""" starts, stops = [], [] self._file.seek(0) next_pos = 0 label_lists = [] while True: line_pos = next_pos line = self._file.readline() next_pos = self._file.tell() if line == '\037\014' + os.linesep: if len(stops) < len(starts): stops.append(line_pos - len(os.linesep)) starts.append(next_pos) labels = [label.strip() for label in self._file.readline()[1:].split(',') if label.strip() != ''] label_lists.append(labels) elif line == '\037' or line == '\037' + os.linesep: if len(stops) < len(starts): stops.append(line_pos - len(os.linesep)) elif line == '': stops.append(line_pos - len(os.linesep)) break self._toc = dict(enumerate(zip(starts, stops))) self._labels = dict(enumerate(label_lists)) self._next_key = len(self._toc) self._file.seek(0, 2) self._file_length = self._file.tell()
[ "def", "_generate_toc", "(", "self", ")", ":", "starts", ",", "stops", "=", "[", "]", ",", "[", "]", "self", ".", "_file", ".", "seek", "(", "0", ")", "next_pos", "=", "0", "label_lists", "=", "[", "]", "while", "True", ":", "line_pos", "=", "nex...
https://github.com/playframework/play1/blob/0ecac3bc2421ae2dbec27a368bf671eda1c9cba5/python/Lib/mailbox.py#L1316-L1344
HaoZhang95/Python24
b897224b8a0e6a5734f408df8c24846a98c553bf
00Python/venv/Lib/site-packages/pip-10.0.1-py3.7.egg/pip/_vendor/urllib3/contrib/_securetransport/low_level.py
python
_cf_data_from_bytes
(bytestring)
return CoreFoundation.CFDataCreate( CoreFoundation.kCFAllocatorDefault, bytestring, len(bytestring) )
Given a bytestring, create a CFData object from it. This CFData object must be CFReleased by the caller.
Given a bytestring, create a CFData object from it. This CFData object must be CFReleased by the caller.
[ "Given", "a", "bytestring", "create", "a", "CFData", "object", "from", "it", ".", "This", "CFData", "object", "must", "be", "CFReleased", "by", "the", "caller", "." ]
def _cf_data_from_bytes(bytestring): """ Given a bytestring, create a CFData object from it. This CFData object must be CFReleased by the caller. """ return CoreFoundation.CFDataCreate( CoreFoundation.kCFAllocatorDefault, bytestring, len(bytestring) )
[ "def", "_cf_data_from_bytes", "(", "bytestring", ")", ":", "return", "CoreFoundation", ".", "CFDataCreate", "(", "CoreFoundation", ".", "kCFAllocatorDefault", ",", "bytestring", ",", "len", "(", "bytestring", ")", ")" ]
https://github.com/HaoZhang95/Python24/blob/b897224b8a0e6a5734f408df8c24846a98c553bf/00Python/venv/Lib/site-packages/pip-10.0.1-py3.7.egg/pip/_vendor/urllib3/contrib/_securetransport/low_level.py#L27-L34
Cadene/tensorflow-model-zoo.torch
990b10ffc22d4c8eacb2a502f20415b4f70c74c2
models/research/slim/nets/mobilenet_v1.py
python
mobilenet_v1
(inputs, num_classes=1000, dropout_keep_prob=0.999, is_training=True, min_depth=8, depth_multiplier=1.0, conv_defs=None, prediction_fn=tf.contrib.layers.softmax, spatial_squeeze=True, reuse=None, scope='MobilenetV1', global_pool=False)
return logits, end_points
Mobilenet v1 model for classification. Args: inputs: a tensor of shape [batch_size, height, width, channels]. num_classes: number of predicted classes. If 0 or None, the logits layer is omitted and the input features to the logits layer (before dropout) are returned instead. dropout_keep_prob: the percentage of activation values that are retained. is_training: whether is training or not. min_depth: Minimum depth value (number of channels) for all convolution ops. Enforced when depth_multiplier < 1, and not an active constraint when depth_multiplier >= 1. depth_multiplier: Float multiplier for the depth (number of channels) for all convolution ops. The value must be greater than zero. Typical usage will be to set this value in (0, 1) to reduce the number of parameters or computation cost of the model. conv_defs: A list of ConvDef namedtuples specifying the net architecture. prediction_fn: a function to get predictions out of logits. spatial_squeeze: if True, logits is of shape is [B, C], if false logits is of shape [B, 1, 1, C], where B is batch_size and C is number of classes. reuse: whether or not the network and its variables should be reused. To be able to reuse 'scope' must be given. scope: Optional variable_scope. global_pool: Optional boolean flag to control the avgpooling before the logits layer. If false or unset, pooling is done with a fixed window that reduces default-sized inputs to 1x1, while larger inputs lead to larger outputs. If true, any input size is pooled down to 1x1. Returns: net: a 2D Tensor with the logits (pre-softmax activations) if num_classes is a non-zero integer, or the non-dropped-out input to the logits layer if num_classes is 0 or None. end_points: a dictionary from components of the network to the corresponding activation. Raises: ValueError: Input rank is invalid.
Mobilenet v1 model for classification.
[ "Mobilenet", "v1", "model", "for", "classification", "." ]
def mobilenet_v1(inputs, num_classes=1000, dropout_keep_prob=0.999, is_training=True, min_depth=8, depth_multiplier=1.0, conv_defs=None, prediction_fn=tf.contrib.layers.softmax, spatial_squeeze=True, reuse=None, scope='MobilenetV1', global_pool=False): """Mobilenet v1 model for classification. Args: inputs: a tensor of shape [batch_size, height, width, channels]. num_classes: number of predicted classes. If 0 or None, the logits layer is omitted and the input features to the logits layer (before dropout) are returned instead. dropout_keep_prob: the percentage of activation values that are retained. is_training: whether is training or not. min_depth: Minimum depth value (number of channels) for all convolution ops. Enforced when depth_multiplier < 1, and not an active constraint when depth_multiplier >= 1. depth_multiplier: Float multiplier for the depth (number of channels) for all convolution ops. The value must be greater than zero. Typical usage will be to set this value in (0, 1) to reduce the number of parameters or computation cost of the model. conv_defs: A list of ConvDef namedtuples specifying the net architecture. prediction_fn: a function to get predictions out of logits. spatial_squeeze: if True, logits is of shape is [B, C], if false logits is of shape [B, 1, 1, C], where B is batch_size and C is number of classes. reuse: whether or not the network and its variables should be reused. To be able to reuse 'scope' must be given. scope: Optional variable_scope. global_pool: Optional boolean flag to control the avgpooling before the logits layer. If false or unset, pooling is done with a fixed window that reduces default-sized inputs to 1x1, while larger inputs lead to larger outputs. If true, any input size is pooled down to 1x1. Returns: net: a 2D Tensor with the logits (pre-softmax activations) if num_classes is a non-zero integer, or the non-dropped-out input to the logits layer if num_classes is 0 or None. end_points: a dictionary from components of the network to the corresponding activation. Raises: ValueError: Input rank is invalid. """ input_shape = inputs.get_shape().as_list() if len(input_shape) != 4: raise ValueError('Invalid input tensor rank, expected 4, was: %d' % len(input_shape)) with tf.variable_scope(scope, 'MobilenetV1', [inputs], reuse=reuse) as scope: with slim.arg_scope([slim.batch_norm, slim.dropout], is_training=is_training): net, end_points = mobilenet_v1_base(inputs, scope=scope, min_depth=min_depth, depth_multiplier=depth_multiplier, conv_defs=conv_defs) with tf.variable_scope('Logits'): if global_pool: # Global average pooling. net = tf.reduce_mean(net, [1, 2], keep_dims=True, name='global_pool') end_points['global_pool'] = net else: # Pooling with a fixed kernel size. kernel_size = _reduced_kernel_size_for_small_input(net, [7, 7]) net = slim.avg_pool2d(net, kernel_size, padding='VALID', scope='AvgPool_1a') end_points['AvgPool_1a'] = net if not num_classes: return net, end_points # 1 x 1 x 1024 net = slim.dropout(net, keep_prob=dropout_keep_prob, scope='Dropout_1b') logits = slim.conv2d(net, num_classes, [1, 1], activation_fn=None, normalizer_fn=None, scope='Conv2d_1c_1x1') if spatial_squeeze: logits = tf.squeeze(logits, [1, 2], name='SpatialSqueeze') end_points['Logits'] = logits if prediction_fn: end_points['Predictions'] = prediction_fn(logits, scope='Predictions') return logits, end_points
[ "def", "mobilenet_v1", "(", "inputs", ",", "num_classes", "=", "1000", ",", "dropout_keep_prob", "=", "0.999", ",", "is_training", "=", "True", ",", "min_depth", "=", "8", ",", "depth_multiplier", "=", "1.0", ",", "conv_defs", "=", "None", ",", "prediction_f...
https://github.com/Cadene/tensorflow-model-zoo.torch/blob/990b10ffc22d4c8eacb2a502f20415b4f70c74c2/models/research/slim/nets/mobilenet_v1.py#L269-L353
python-discord/bot
26c5587ac13e5414361bb6e7ada42983b81014d2
bot/utils/message_cache.py
python
MessageCache.append
(self, message: Message)
Add the received message to the cache, depending on the order of messages defined by `newest_first`.
Add the received message to the cache, depending on the order of messages defined by `newest_first`.
[ "Add", "the", "received", "message", "to", "the", "cache", "depending", "on", "the", "order", "of", "messages", "defined", "by", "newest_first", "." ]
def append(self, message: Message) -> None: """Add the received message to the cache, depending on the order of messages defined by `newest_first`.""" if self.newest_first: self._appendleft(message) else: self._appendright(message)
[ "def", "append", "(", "self", ",", "message", ":", "Message", ")", "->", "None", ":", "if", "self", ".", "newest_first", ":", "self", ".", "_appendleft", "(", "message", ")", "else", ":", "self", ".", "_appendright", "(", "message", ")" ]
https://github.com/python-discord/bot/blob/26c5587ac13e5414361bb6e7ada42983b81014d2/bot/utils/message_cache.py#L37-L42
cyverse/atmosphere
4a3e522f1f7b58abd9fa944c10b7455dc5cddac1
service/argo/rest_api.py
python
ArgoAPIClient.run_workflow
(self, wf_json)
return json_resp
Endpoint for running a workflow Args: wf_json (dict): workflow definition as JSON object Returns: dict: response text as JSON object
Endpoint for running a workflow
[ "Endpoint", "for", "running", "a", "workflow" ]
def run_workflow(self, wf_json): """ Endpoint for running a workflow Args: wf_json (dict): workflow definition as JSON object Returns: dict: response text as JSON object """ api_url = "/api/v1/workflows/" + self._namespace json_data = {} json_data["namespace"] = self._namespace json_data["serverDryRun"] = False json_data["workflow"] = wf_json json_resp = self._req("post", api_url, json_data=json_data) return json_resp
[ "def", "run_workflow", "(", "self", ",", "wf_json", ")", ":", "api_url", "=", "\"/api/v1/workflows/\"", "+", "self", ".", "_namespace", "json_data", "=", "{", "}", "json_data", "[", "\"namespace\"", "]", "=", "self", ".", "_namespace", "json_data", "[", "\"s...
https://github.com/cyverse/atmosphere/blob/4a3e522f1f7b58abd9fa944c10b7455dc5cddac1/service/argo/rest_api.py#L74-L93
meduza-corp/interstellar
40a801ccd7856491726f5a126621d9318cabe2e1
gsutil/third_party/boto/boto/sqs/connection.py
python
SQSConnection.delete_message
(self, queue, message)
return self.get_status('DeleteMessage', params, queue.id)
Delete a message from a queue. :type queue: A :class:`boto.sqs.queue.Queue` object :param queue: The Queue from which messages are read. :type message: A :class:`boto.sqs.message.Message` object :param message: The Message to be deleted :rtype: bool :return: True if successful, False otherwise.
Delete a message from a queue.
[ "Delete", "a", "message", "from", "a", "queue", "." ]
def delete_message(self, queue, message): """ Delete a message from a queue. :type queue: A :class:`boto.sqs.queue.Queue` object :param queue: The Queue from which messages are read. :type message: A :class:`boto.sqs.message.Message` object :param message: The Message to be deleted :rtype: bool :return: True if successful, False otherwise. """ params = {'ReceiptHandle' : message.receipt_handle} return self.get_status('DeleteMessage', params, queue.id)
[ "def", "delete_message", "(", "self", ",", "queue", ",", "message", ")", ":", "params", "=", "{", "'ReceiptHandle'", ":", "message", ".", "receipt_handle", "}", "return", "self", ".", "get_status", "(", "'DeleteMessage'", ",", "params", ",", "queue", ".", ...
https://github.com/meduza-corp/interstellar/blob/40a801ccd7856491726f5a126621d9318cabe2e1/gsutil/third_party/boto/boto/sqs/connection.py#L203-L217
liuyubobobo/Play-with-Linear-Algebra
e86175adb908b03756618fbeeeadb448a3551321
13-Eigenvalues-and-Eigenvectors/06-Eigenvalues-and-Eigenvectors-in-numpy/playLA/Matrix.py
python
Matrix.dot
(self, another)
返回矩阵乘法的结果
返回矩阵乘法的结果
[ "返回矩阵乘法的结果" ]
def dot(self, another): """返回矩阵乘法的结果""" if isinstance(another, Vector): # 矩阵和向量的乘法 assert self.col_num() == len(another), \ "Error in Matrix-Vector Multiplication." return Vector([self.row_vector(i).dot(another) for i in range(self.row_num())]) if isinstance(another, Matrix): # 矩阵和矩阵的乘法 assert self.col_num() == another.row_num(), \ "Error in Matrix-Matrix Multiplication." return Matrix([[self.row_vector(i).dot(another.col_vector(j)) for j in range(another.col_num())] for i in range(self.row_num())])
[ "def", "dot", "(", "self", ",", "another", ")", ":", "if", "isinstance", "(", "another", ",", "Vector", ")", ":", "# 矩阵和向量的乘法", "assert", "self", ".", "col_num", "(", ")", "==", "len", "(", "another", ")", ",", "\"Error in Matrix-Vector Multiplication.\"", ...
https://github.com/liuyubobobo/Play-with-Linear-Algebra/blob/e86175adb908b03756618fbeeeadb448a3551321/13-Eigenvalues-and-Eigenvectors/06-Eigenvalues-and-Eigenvectors-in-numpy/playLA/Matrix.py#L44-L57
deluge-torrent/deluge
2316088f5c0dd6cb044d9d4832fa7d56dcc79cdc
deluge/ui/console/cmdline/command.py
python
Commander.parse_command
(self, cmd_line)
return options
Parse a console command and process with argparse. Args: cmd_line (str): Console command. Returns: argparse.Namespace: The parsed command.
Parse a console command and process with argparse.
[ "Parse", "a", "console", "command", "and", "process", "with", "argparse", "." ]
def parse_command(self, cmd_line): """Parse a console command and process with argparse. Args: cmd_line (str): Console command. Returns: argparse.Namespace: The parsed command. """ if not cmd_line: return cmd, _, line = cmd_line.partition(' ') try: parser = self._commands[cmd].create_parser() except KeyError: self.write('{!error!}Unknown command: %s' % cmd) return try: args = [cmd] + self._commands[cmd].split(line) except ValueError as ex: self.write('{!error!}Error parsing command: %s' % ex) return # Do a little hack here to print 'command --help' properly parser._print_help = parser.print_help def print_help(f=None): if self.interactive: self.write(parser.format_help()) else: parser._print_help(f) parser.print_help = print_help # Only these commands can be run when not connected to a daemon not_connected_cmds = ['help', 'connect', 'quit'] aliases = [] for c in not_connected_cmds: aliases.extend(self._commands[c].aliases) not_connected_cmds.extend(aliases) if not client.connected() and cmd not in not_connected_cmds: self.write( '{!error!}Not connected to a daemon, please use the connect command first.' ) return try: options = parser.parse_args(args=args) options.command = cmd except TypeError as ex: self.write('{!error!}Error parsing options: %s' % ex) import traceback self.write('%s' % traceback.format_exc()) return except OptionParserError as ex: import traceback log.warning('Error parsing command "%s": %s', args, ex) self.write('{!error!} %s' % ex) parser.print_help() return if getattr(parser, '_exit', False): return return options
[ "def", "parse_command", "(", "self", ",", "cmd_line", ")", ":", "if", "not", "cmd_line", ":", "return", "cmd", ",", "_", ",", "line", "=", "cmd_line", ".", "partition", "(", "' '", ")", "try", ":", "parser", "=", "self", ".", "_commands", "[", "cmd",...
https://github.com/deluge-torrent/deluge/blob/2316088f5c0dd6cb044d9d4832fa7d56dcc79cdc/deluge/ui/console/cmdline/command.py#L51-L119
postlund/hass-atv-beta
0ce01623eabc6a11b84a79deaf25cec0359056ea
custom_components/apple_tv/config_flow.py
python
AppleTVConfigFlow.async_step_zeroconf
( self, discovery_info: zeroconf.ZeroconfServiceInfo )
return await self.async_find_device_wrapper(self.async_found_zeroconf_device)
Handle device found via zeroconf.
Handle device found via zeroconf.
[ "Handle", "device", "found", "via", "zeroconf", "." ]
async def async_step_zeroconf( self, discovery_info: zeroconf.ZeroconfServiceInfo ) -> data_entry_flow.FlowResult: """Handle device found via zeroconf.""" host = discovery_info.host self._async_abort_entries_match({CONF_ADDRESS: host}) service_type = discovery_info.type[:-1] # Remove leading . name = discovery_info.name.replace(f".{service_type}.", "") properties = discovery_info.properties # Extract unique identifier from service unique_id = get_unique_id(service_type, name, properties) if unique_id is None: return self.async_abort(reason="unknown") if existing_unique_id := self._entry_unique_id_from_identifers({unique_id}): await self.async_set_unique_id(existing_unique_id) self._abort_if_unique_id_configured(updates={CONF_ADDRESS: host}) self._async_abort_entries_match({CONF_ADDRESS: host}) await self._async_aggregate_discoveries(host, unique_id) # Scan for the device in order to extract _all_ unique identifiers assigned to # it. Not doing it like this will yield multiple config flows for the same # device, one per protocol, which is undesired. self.scan_filter = host return await self.async_find_device_wrapper(self.async_found_zeroconf_device)
[ "async", "def", "async_step_zeroconf", "(", "self", ",", "discovery_info", ":", "zeroconf", ".", "ZeroconfServiceInfo", ")", "->", "data_entry_flow", ".", "FlowResult", ":", "host", "=", "discovery_info", ".", "host", "self", ".", "_async_abort_entries_match", "(", ...
https://github.com/postlund/hass-atv-beta/blob/0ce01623eabc6a11b84a79deaf25cec0359056ea/custom_components/apple_tv/config_flow.py#L163-L188
giantbranch/python-hacker-code
addbc8c73e7e6fb9e4fcadcec022fa1d3da4b96d
我手敲的代码(中文注释)/chapter11/immlib/pefile.py
python
COFF.get_qword_at_rva
(self, rva)
Return the quad-word value at the given RVA. Returns None if the value can't be read, i.e. the RVA can't be mapped to a file offset.
Return the quad-word value at the given RVA. Returns None if the value can't be read, i.e. the RVA can't be mapped to a file offset.
[ "Return", "the", "quad", "-", "word", "value", "at", "the", "given", "RVA", ".", "Returns", "None", "if", "the", "value", "can", "t", "be", "read", "i", ".", "e", ".", "the", "RVA", "can", "t", "be", "mapped", "to", "a", "file", "offset", "." ]
def get_qword_at_rva(self, rva): """Return the quad-word value at the given RVA. Returns None if the value can't be read, i.e. the RVA can't be mapped to a file offset. """ try: return self.get_qword_from_data(self.get_data(rva)[:8], 0) except PEFormatError: return None
[ "def", "get_qword_at_rva", "(", "self", ",", "rva", ")", ":", "try", ":", "return", "self", ".", "get_qword_from_data", "(", "self", ".", "get_data", "(", "rva", ")", "[", ":", "8", "]", ",", "0", ")", "except", "PEFormatError", ":", "return", "None" ]
https://github.com/giantbranch/python-hacker-code/blob/addbc8c73e7e6fb9e4fcadcec022fa1d3da4b96d/我手敲的代码(中文注释)/chapter11/immlib/pefile.py#L3652-L3662
TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
5bb97d7e3ffd913abddb4cfa7d78a1b4c868890e
tensorflow_dl_models/research/capsules/models/layers/variables.py
python
bias_variable
(shape, verbose=False)
return biases
Creates a CPU variable with constant initialization. Adds summaries. Args: shape: list, the shape of the variable. verbose: if set add histograms. Returns: Bias variable tensor with shape=shape.
Creates a CPU variable with constant initialization. Adds summaries.
[ "Creates", "a", "CPU", "variable", "with", "constant", "initialization", ".", "Adds", "summaries", "." ]
def bias_variable(shape, verbose=False): """Creates a CPU variable with constant initialization. Adds summaries. Args: shape: list, the shape of the variable. verbose: if set add histograms. Returns: Bias variable tensor with shape=shape. """ with tf.device('/cpu:0'): with tf.name_scope('biases'): biases = tf.get_variable( 'biases', shape, initializer=tf.constant_initializer(0.1), dtype=tf.float32) variable_summaries(biases, verbose) return biases
[ "def", "bias_variable", "(", "shape", ",", "verbose", "=", "False", ")", ":", "with", "tf", ".", "device", "(", "'/cpu:0'", ")", ":", "with", "tf", ".", "name_scope", "(", "'biases'", ")", ":", "biases", "=", "tf", ".", "get_variable", "(", "'biases'",...
https://github.com/TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials/blob/5bb97d7e3ffd913abddb4cfa7d78a1b4c868890e/tensorflow_dl_models/research/capsules/models/layers/variables.py#L52-L70
pytorch/fairseq
1575f30dd0a9f7b3c499db0b4767aa4e9f79056c
fairseq/logging/progress_bar.py
python
TensorboardProgressBarWrapper.log
(self, stats, tag=None, step=None)
Log intermediate stats to tensorboard.
Log intermediate stats to tensorboard.
[ "Log", "intermediate", "stats", "to", "tensorboard", "." ]
def log(self, stats, tag=None, step=None): """Log intermediate stats to tensorboard.""" self._log_to_tensorboard(stats, tag, step) self.wrapped_bar.log(stats, tag=tag, step=step)
[ "def", "log", "(", "self", ",", "stats", ",", "tag", "=", "None", ",", "step", "=", "None", ")", ":", "self", ".", "_log_to_tensorboard", "(", "stats", ",", "tag", ",", "step", ")", "self", ".", "wrapped_bar", ".", "log", "(", "stats", ",", "tag", ...
https://github.com/pytorch/fairseq/blob/1575f30dd0a9f7b3c499db0b4767aa4e9f79056c/fairseq/logging/progress_bar.py#L355-L358
vivisect/vivisect
37b0b655d8dedfcf322e86b0f144b096e48d547e
envi/config.py
python
EnviConfig.getOptionDoc
(self, optname)
return self.cfgdocs.get(optname)
Retrieve docs about the given option if present. Example: doc = config.getOptionDoc('woot') if doc is not None: print('woot: %s' % doc)
Retrieve docs about the given option if present.
[ "Retrieve", "docs", "about", "the", "given", "option", "if", "present", "." ]
def getOptionDoc(self, optname): ''' Retrieve docs about the given option if present. Example: doc = config.getOptionDoc('woot') if doc is not None: print('woot: %s' % doc) ''' return self.cfgdocs.get(optname)
[ "def", "getOptionDoc", "(", "self", ",", "optname", ")", ":", "return", "self", ".", "cfgdocs", ".", "get", "(", "optname", ")" ]
https://github.com/vivisect/vivisect/blob/37b0b655d8dedfcf322e86b0f144b096e48d547e/envi/config.py#L70-L79
reingart/pyafipws
3141894e82d538e297a85b8bc960016a3a871fbe
wsfexv1.py
python
WSFEXv1.GetParamTipoExpo
(self, sep="|")
Recuperador de valores referenciales de códigos de Tipo de exportación
Recuperador de valores referenciales de códigos de Tipo de exportación
[ "Recuperador", "de", "valores", "referenciales", "de", "códigos", "de", "Tipo", "de", "exportación" ]
def GetParamTipoExpo(self, sep="|"): "Recuperador de valores referenciales de códigos de Tipo de exportación" ret = self.client.FEXGetPARAM_Tipo_Expo( Auth={ "Token": self.Token, "Sign": self.Sign, "Cuit": self.Cuit, } ) result = ret["FEXGetPARAM_Tipo_ExpoResult"] self.__analizar_errores(result) ret = [] for u in result["FEXResultGet"]: u = u["ClsFEXResponse_Tex"] try: r = { "codigo": u.get("Tex_Id"), "ds": u.get("Tex_Ds"), "vig_desde": u.get("Tex_vig_desde"), "vig_hasta": u.get("Tex_vig_hasta"), } except Exception as e: print(e) ret.append(r) if sep: return [ ("\t%(codigo)s\t%(ds)s\t%(vig_desde)s\t%(vig_hasta)s\t" % it).replace( "\t", sep ) for it in ret ] else: return ret
[ "def", "GetParamTipoExpo", "(", "self", ",", "sep", "=", "\"|\"", ")", ":", "ret", "=", "self", ".", "client", ".", "FEXGetPARAM_Tipo_Expo", "(", "Auth", "=", "{", "\"Token\"", ":", "self", ".", "Token", ",", "\"Sign\"", ":", "self", ".", "Sign", ",", ...
https://github.com/reingart/pyafipws/blob/3141894e82d538e297a85b8bc960016a3a871fbe/wsfexv1.py#L581-L615
enthought/mayavi
2103a273568b8f0bd62328801aafbd6252543ae8
mayavi/plugins/mayavi_workbench_application.py
python
MayaviWorkbenchApplication._about_dialog_default
(self)
return about_dialog
Trait initializer.
Trait initializer.
[ "Trait", "initializer", "." ]
def _about_dialog_default(self): """ Trait initializer. """ from mayavi import api from vtk import vtkVersion vtk_version = vtkVersion().GetVTKVersion() about_dialog = AboutDialog( parent = self.workbench.active_window.control, image = ImageResource('m2_about.jpg', search_path=[IMG_DIR]), additions = ['Authors: Prabhu Ramachandran', 'and Gael Varoquaux', '', 'Mayavi version %s \t - \t VTK version %s' % (api.__version__, vtk_version)], ) return about_dialog
[ "def", "_about_dialog_default", "(", "self", ")", ":", "from", "mayavi", "import", "api", "from", "vtk", "import", "vtkVersion", "vtk_version", "=", "vtkVersion", "(", ")", ".", "GetVTKVersion", "(", ")", "about_dialog", "=", "AboutDialog", "(", "parent", "=",...
https://github.com/enthought/mayavi/blob/2103a273568b8f0bd62328801aafbd6252543ae8/mayavi/plugins/mayavi_workbench_application.py#L97-L113
houtianze/bypy
10fd0f18378174a775a05a366cc20ba6609f96c6
.vscode/.ropeproject/config.py
python
project_opened
(project)
This function is called after opening the project
This function is called after opening the project
[ "This", "function", "is", "called", "after", "opening", "the", "project" ]
def project_opened(project): """This function is called after opening the project"""
[ "def", "project_opened", "(", "project", ")", ":" ]
https://github.com/houtianze/bypy/blob/10fd0f18378174a775a05a366cc20ba6609f96c6/.vscode/.ropeproject/config.py#L98-L99
tenpy/tenpy
bbdd3dbbdb511948eb0e6ba7ff619ac6ca657fff
tenpy/networks/mpo.py
python
MPOEnvironment.full_contraction
(self, i0)
return res
Calculate the energy by a full contraction of the network. The full contraction of the environments gives the value ``<bra|H|ket> / (norm(|bra>)*norm(|ket>))``, i.e. if `bra` is `ket` and normalized, the total energy. For this purpose, this function contracts ``get_LP(i0+1, store=False)`` and ``get_RP(i0, store=False)``. Parameters ---------- i0 : int Site index.
Calculate the energy by a full contraction of the network.
[ "Calculate", "the", "energy", "by", "a", "full", "contraction", "of", "the", "network", "." ]
def full_contraction(self, i0): """Calculate the energy by a full contraction of the network. The full contraction of the environments gives the value ``<bra|H|ket> / (norm(|bra>)*norm(|ket>))``, i.e. if `bra` is `ket` and normalized, the total energy. For this purpose, this function contracts ``get_LP(i0+1, store=False)`` and ``get_RP(i0, store=False)``. Parameters ---------- i0 : int Site index. """ # same as MPSEnvironment.full_contraction, but also contract 'wL' with 'wR' if self.ket.finite and i0 + 1 == self.L: # special case to handle `_to_valid_index` correctly: # get_LP(L) is not valid for finite b.c, so we use need to calculate it explicitly. LP = self.get_LP(i0, store=False) LP = self._contract_LP(i0, LP) else: LP = self.get_LP(i0 + 1, store=False) # multiply with `S` on bra and ket side S_bra = self.bra.get_SR(i0).conj() if isinstance(S_bra, npc.Array): LP = npc.tensordot(S_bra, LP, axes=['vL*', 'vR*']) else: LP = LP.scale_axis(S_bra, 'vR*') S_ket = self.ket.get_SR(i0) if isinstance(S_ket, npc.Array): LP = npc.tensordot(LP, S_ket, axes=['vR', 'vL']) else: LP = LP.scale_axis(S_ket, 'vR') RP = self.get_RP(i0, store=False) res = npc.inner(LP, RP, axes=[['vR*', 'wR', 'vR'], ['vL*', 'wL', 'vL']], do_conj=False) if self.H.explicit_plus_hc: res = res + np.conj(res) return res
[ "def", "full_contraction", "(", "self", ",", "i0", ")", ":", "# same as MPSEnvironment.full_contraction, but also contract 'wL' with 'wR'", "if", "self", ".", "ket", ".", "finite", "and", "i0", "+", "1", "==", "self", ".", "L", ":", "# special case to handle `_to_vali...
https://github.com/tenpy/tenpy/blob/bbdd3dbbdb511948eb0e6ba7ff619ac6ca657fff/tenpy/networks/mpo.py#L2018-L2056
Azure/azure-devops-cli-extension
11334cd55806bef0b99c3bee5a438eed71e44037
azure-devops/azext_devops/devops_sdk/v5_0/task_agent/task_agent_client.py
python
TaskAgentClient.add_deployment_group
(self, deployment_group, project)
return self._deserialize('DeploymentGroup', response)
AddDeploymentGroup. [Preview API] Create a deployment group. :param :class:`<DeploymentGroupCreateParameter> <azure.devops.v5_0.task_agent.models.DeploymentGroupCreateParameter>` deployment_group: Deployment group to create. :param str project: Project ID or project name :rtype: :class:`<DeploymentGroup> <azure.devops.v5_0.task_agent.models.DeploymentGroup>`
AddDeploymentGroup. [Preview API] Create a deployment group. :param :class:`<DeploymentGroupCreateParameter> <azure.devops.v5_0.task_agent.models.DeploymentGroupCreateParameter>` deployment_group: Deployment group to create. :param str project: Project ID or project name :rtype: :class:`<DeploymentGroup> <azure.devops.v5_0.task_agent.models.DeploymentGroup>`
[ "AddDeploymentGroup", ".", "[", "Preview", "API", "]", "Create", "a", "deployment", "group", ".", ":", "param", ":", "class", ":", "<DeploymentGroupCreateParameter", ">", "<azure", ".", "devops", ".", "v5_0", ".", "task_agent", ".", "models", ".", "DeploymentG...
def add_deployment_group(self, deployment_group, project): """AddDeploymentGroup. [Preview API] Create a deployment group. :param :class:`<DeploymentGroupCreateParameter> <azure.devops.v5_0.task_agent.models.DeploymentGroupCreateParameter>` deployment_group: Deployment group to create. :param str project: Project ID or project name :rtype: :class:`<DeploymentGroup> <azure.devops.v5_0.task_agent.models.DeploymentGroup>` """ route_values = {} if project is not None: route_values['project'] = self._serialize.url('project', project, 'str') content = self._serialize.body(deployment_group, 'DeploymentGroupCreateParameter') response = self._send(http_method='POST', location_id='083c4d89-ab35-45af-aa11-7cf66895c53e', version='5.0-preview.1', route_values=route_values, content=content) return self._deserialize('DeploymentGroup', response)
[ "def", "add_deployment_group", "(", "self", ",", "deployment_group", ",", "project", ")", ":", "route_values", "=", "{", "}", "if", "project", "is", "not", "None", ":", "route_values", "[", "'project'", "]", "=", "self", ".", "_serialize", ".", "url", "(",...
https://github.com/Azure/azure-devops-cli-extension/blob/11334cd55806bef0b99c3bee5a438eed71e44037/azure-devops/azext_devops/devops_sdk/v5_0/task_agent/task_agent_client.py#L91-L107
Alfanous-team/alfanous
594514729473c24efa3908e3107b45a38255de4b
src/alfanous/Support/whoosh/index.py
python
Index.doc_count_all
(self)
Returns the total number of documents, DELETED OR UNDELETED, in this index.
Returns the total number of documents, DELETED OR UNDELETED, in this index.
[ "Returns", "the", "total", "number", "of", "documents", "DELETED", "OR", "UNDELETED", "in", "this", "index", "." ]
def doc_count_all(self): """Returns the total number of documents, DELETED OR UNDELETED, in this index. """ raise NotImplementedError
[ "def", "doc_count_all", "(", "self", ")", ":", "raise", "NotImplementedError" ]
https://github.com/Alfanous-team/alfanous/blob/594514729473c24efa3908e3107b45a38255de4b/src/alfanous/Support/whoosh/index.py#L303-L307
reviewboard/reviewboard
7395902e4c181bcd1d633f61105012ffb1d18e1b
reviewboard/admin/templatetags/rbadmintags.py
python
split_error_title_text
(error)
return six.text_type(error).split('\n', 1)
Split an exception's text into a title and body text. Args: error (Exception): The error containing text to split. Returns: tuple: A tuple containing: 1. The title text. 2. The rest of the error message (or ``None``).
Split an exception's text into a title and body text.
[ "Split", "an", "exception", "s", "text", "into", "a", "title", "and", "body", "text", "." ]
def split_error_title_text(error): """Split an exception's text into a title and body text. Args: error (Exception): The error containing text to split. Returns: tuple: A tuple containing: 1. The title text. 2. The rest of the error message (or ``None``). """ return six.text_type(error).split('\n', 1)
[ "def", "split_error_title_text", "(", "error", ")", ":", "return", "six", ".", "text_type", "(", "error", ")", ".", "split", "(", "'\\n'", ",", "1", ")" ]
https://github.com/reviewboard/reviewboard/blob/7395902e4c181bcd1d633f61105012ffb1d18e1b/reviewboard/admin/templatetags/rbadmintags.py#L128-L142
pantsbuild/pex
473c6ac732ed4bc338b4b20a9ec930d1d722c9b4
pex/third_party/__init__.py
python
_ZipIterator._filter_names
(self, relpath, pattern, group)
[]
def _filter_names(self, relpath, pattern, group): # We use '/' here because the zip file format spec specifies that paths must use # forward slashes. See section 4.4.17 of # https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT. relpath_pat = "" if not relpath else "{}/".format(relpath.replace(os.sep, "/")) pat = re.compile(r"^{}{}{}$".format(self.prefix, relpath_pat, pattern)) with contextlib.closing(zipfile.ZipFile(self.zipfile_path)) as zf: for name in zf.namelist(): match = pat.match(name) if match: yield match.group(group)
[ "def", "_filter_names", "(", "self", ",", "relpath", ",", "pattern", ",", "group", ")", ":", "# We use '/' here because the zip file format spec specifies that paths must use", "# forward slashes. See section 4.4.17 of", "# https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT.", ...
https://github.com/pantsbuild/pex/blob/473c6ac732ed4bc338b4b20a9ec930d1d722c9b4/pex/third_party/__init__.py#L123-L133
Qiskit/qiskit-terra
b66030e3b9192efdd3eb95cf25c6545fe0a13da4
qiskit/result/distributions/probability.py
python
ProbDistribution.hex_probabilities
(self)
return {hex(key): value for key, value in self.items()}
Build a probabilities dictionary with hexadecimal string keys Returns: dict: A dictionary where the keys are hexadecimal strings in the format ``"0x1a"``
Build a probabilities dictionary with hexadecimal string keys
[ "Build", "a", "probabilities", "dictionary", "with", "hexadecimal", "string", "keys" ]
def hex_probabilities(self): """Build a probabilities dictionary with hexadecimal string keys Returns: dict: A dictionary where the keys are hexadecimal strings in the format ``"0x1a"`` """ return {hex(key): value for key, value in self.items()}
[ "def", "hex_probabilities", "(", "self", ")", ":", "return", "{", "hex", "(", "key", ")", ":", "value", "for", "key", ",", "value", "in", "self", ".", "items", "(", ")", "}" ]
https://github.com/Qiskit/qiskit-terra/blob/b66030e3b9192efdd3eb95cf25c6545fe0a13da4/qiskit/result/distributions/probability.py#L87-L94
rowliny/DiffHelper
ab3a96f58f9579d0023aed9ebd785f4edf26f8af
Tool/SitePackages/nltk/corpus/reader/framenet.py
python
FramenetCorpusReader.frame_relations
(self, frame=None, frame2=None, type=None)
return PrettyList( sorted( rels, key=lambda frel: (frel.type.ID, frel.superFrameName, frel.subFrameName), ) )
:param frame: (optional) frame object, name, or ID; only relations involving this frame will be returned :param frame2: (optional; 'frame' must be a different frame) only show relations between the two specified frames, in either direction :param type: (optional) frame relation type (name or object); show only relations of this type :type frame: int or str or AttrDict :return: A list of all of the frame relations in framenet :rtype: list(dict) >>> from nltk.corpus import framenet as fn >>> frels = fn.frame_relations() >>> isinstance(frels, list) True >>> len(frels) in (1676, 2070) # FN 1.5 and 1.7, resp. True >>> PrettyList(fn.frame_relations('Cooking_creation'), maxReprSize=0, breakLines=True) [<Parent=Intentionally_create -- Inheritance -> Child=Cooking_creation>, <Parent=Apply_heat -- Using -> Child=Cooking_creation>, <MainEntry=Apply_heat -- See_also -> ReferringEntry=Cooking_creation>] >>> PrettyList(fn.frame_relations(274), breakLines=True) [<Parent=Avoiding -- Inheritance -> Child=Dodging>, <Parent=Avoiding -- Inheritance -> Child=Evading>, ...] >>> PrettyList(fn.frame_relations(fn.frame('Cooking_creation')), breakLines=True) [<Parent=Intentionally_create -- Inheritance -> Child=Cooking_creation>, <Parent=Apply_heat -- Using -> Child=Cooking_creation>, ...] >>> PrettyList(fn.frame_relations('Cooking_creation', type='Inheritance')) [<Parent=Intentionally_create -- Inheritance -> Child=Cooking_creation>] >>> PrettyList(fn.frame_relations('Cooking_creation', 'Apply_heat'), breakLines=True) [<Parent=Apply_heat -- Using -> Child=Cooking_creation>, <MainEntry=Apply_heat -- See_also -> ReferringEntry=Cooking_creation>]
:param frame: (optional) frame object, name, or ID; only relations involving this frame will be returned :param frame2: (optional; 'frame' must be a different frame) only show relations between the two specified frames, in either direction :param type: (optional) frame relation type (name or object); show only relations of this type :type frame: int or str or AttrDict :return: A list of all of the frame relations in framenet :rtype: list(dict)
[ ":", "param", "frame", ":", "(", "optional", ")", "frame", "object", "name", "or", "ID", ";", "only", "relations", "involving", "this", "frame", "will", "be", "returned", ":", "param", "frame2", ":", "(", "optional", ";", "frame", "must", "be", "a", "d...
def frame_relations(self, frame=None, frame2=None, type=None): """ :param frame: (optional) frame object, name, or ID; only relations involving this frame will be returned :param frame2: (optional; 'frame' must be a different frame) only show relations between the two specified frames, in either direction :param type: (optional) frame relation type (name or object); show only relations of this type :type frame: int or str or AttrDict :return: A list of all of the frame relations in framenet :rtype: list(dict) >>> from nltk.corpus import framenet as fn >>> frels = fn.frame_relations() >>> isinstance(frels, list) True >>> len(frels) in (1676, 2070) # FN 1.5 and 1.7, resp. True >>> PrettyList(fn.frame_relations('Cooking_creation'), maxReprSize=0, breakLines=True) [<Parent=Intentionally_create -- Inheritance -> Child=Cooking_creation>, <Parent=Apply_heat -- Using -> Child=Cooking_creation>, <MainEntry=Apply_heat -- See_also -> ReferringEntry=Cooking_creation>] >>> PrettyList(fn.frame_relations(274), breakLines=True) [<Parent=Avoiding -- Inheritance -> Child=Dodging>, <Parent=Avoiding -- Inheritance -> Child=Evading>, ...] >>> PrettyList(fn.frame_relations(fn.frame('Cooking_creation')), breakLines=True) [<Parent=Intentionally_create -- Inheritance -> Child=Cooking_creation>, <Parent=Apply_heat -- Using -> Child=Cooking_creation>, ...] >>> PrettyList(fn.frame_relations('Cooking_creation', type='Inheritance')) [<Parent=Intentionally_create -- Inheritance -> Child=Cooking_creation>] >>> PrettyList(fn.frame_relations('Cooking_creation', 'Apply_heat'), breakLines=True) [<Parent=Apply_heat -- Using -> Child=Cooking_creation>, <MainEntry=Apply_heat -- See_also -> ReferringEntry=Cooking_creation>] """ relation_type = type if not self._frel_idx: self._buildrelationindex() rels = None if relation_type is not None: if not isinstance(relation_type, dict): type = [rt for rt in self.frame_relation_types() if rt.name == type][0] assert isinstance(type, dict) # lookup by 'frame' if frame is not None: if isinstance(frame, dict) and "frameRelations" in frame: rels = PrettyList(frame.frameRelations) else: if not isinstance(frame, int): if isinstance(frame, dict): frame = frame.ID else: frame = self.frame_by_name(frame).ID rels = [self._frel_idx[frelID] for frelID in self._frel_f_idx[frame]] # filter by 'type' if type is not None: rels = [rel for rel in rels if rel.type is type] elif type is not None: # lookup by 'type' rels = type.frameRelations else: rels = self._frel_idx.values() # filter by 'frame2' if frame2 is not None: if frame is None: raise FramenetError( "frame_relations(frame=None, frame2=<value>) is not allowed" ) if not isinstance(frame2, int): if isinstance(frame2, dict): frame2 = frame2.ID else: frame2 = self.frame_by_name(frame2).ID if frame == frame2: raise FramenetError( "The two frame arguments to frame_relations() must be different frames" ) rels = [ rel for rel in rels if rel.superFrame.ID == frame2 or rel.subFrame.ID == frame2 ] return PrettyList( sorted( rels, key=lambda frel: (frel.type.ID, frel.superFrameName, frel.subFrameName), ) )
[ "def", "frame_relations", "(", "self", ",", "frame", "=", "None", ",", "frame2", "=", "None", ",", "type", "=", "None", ")", ":", "relation_type", "=", "type", "if", "not", "self", ".", "_frel_idx", ":", "self", ".", "_buildrelationindex", "(", ")", "r...
https://github.com/rowliny/DiffHelper/blob/ab3a96f58f9579d0023aed9ebd785f4edf26f8af/Tool/SitePackages/nltk/corpus/reader/framenet.py#L2518-L2611
oilshell/oil
94388e7d44a9ad879b12615f6203b38596b5a2d3
Python-2.7.13/Lib/decimal.py
python
Context.log10
(self, a)
return a.log10(context=self)
Returns the base 10 logarithm of the operand. >>> c = ExtendedContext.copy() >>> c.Emin = -999 >>> c.Emax = 999 >>> c.log10(Decimal('0')) Decimal('-Infinity') >>> c.log10(Decimal('0.001')) Decimal('-3') >>> c.log10(Decimal('1.000')) Decimal('0') >>> c.log10(Decimal('2')) Decimal('0.301029996') >>> c.log10(Decimal('10')) Decimal('1') >>> c.log10(Decimal('70')) Decimal('1.84509804') >>> c.log10(Decimal('+Infinity')) Decimal('Infinity') >>> c.log10(0) Decimal('-Infinity') >>> c.log10(1) Decimal('0')
Returns the base 10 logarithm of the operand.
[ "Returns", "the", "base", "10", "logarithm", "of", "the", "operand", "." ]
def log10(self, a): """Returns the base 10 logarithm of the operand. >>> c = ExtendedContext.copy() >>> c.Emin = -999 >>> c.Emax = 999 >>> c.log10(Decimal('0')) Decimal('-Infinity') >>> c.log10(Decimal('0.001')) Decimal('-3') >>> c.log10(Decimal('1.000')) Decimal('0') >>> c.log10(Decimal('2')) Decimal('0.301029996') >>> c.log10(Decimal('10')) Decimal('1') >>> c.log10(Decimal('70')) Decimal('1.84509804') >>> c.log10(Decimal('+Infinity')) Decimal('Infinity') >>> c.log10(0) Decimal('-Infinity') >>> c.log10(1) Decimal('0') """ a = _convert_other(a, raiseit=True) return a.log10(context=self)
[ "def", "log10", "(", "self", ",", "a", ")", ":", "a", "=", "_convert_other", "(", "a", ",", "raiseit", "=", "True", ")", "return", "a", ".", "log10", "(", "context", "=", "self", ")" ]
https://github.com/oilshell/oil/blob/94388e7d44a9ad879b12615f6203b38596b5a2d3/Python-2.7.13/Lib/decimal.py#L4508-L4534
kubernetes-client/python
47b9da9de2d02b2b7a34fbe05afb44afd130d73a
kubernetes/client/api/rbac_authorization_v1alpha1_api.py
python
RbacAuthorizationV1alpha1Api.delete_namespaced_role_binding
(self, name, namespace, **kwargs)
return self.delete_namespaced_role_binding_with_http_info(name, namespace, **kwargs)
delete_namespaced_role_binding # noqa: E501 delete a RoleBinding # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.delete_namespaced_role_binding(name, namespace, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the RoleBinding (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param str pretty: If 'true', then the output is pretty printed. :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param int grace_period_seconds: The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately. :param bool orphan_dependents: Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both. :param str propagation_policy: Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground. :param V1DeleteOptions body: :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: V1Status If the method is called asynchronously, returns the request thread.
delete_namespaced_role_binding # noqa: E501
[ "delete_namespaced_role_binding", "#", "noqa", ":", "E501" ]
def delete_namespaced_role_binding(self, name, namespace, **kwargs): # noqa: E501 """delete_namespaced_role_binding # noqa: E501 delete a RoleBinding # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.delete_namespaced_role_binding(name, namespace, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the RoleBinding (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param str pretty: If 'true', then the output is pretty printed. :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param int grace_period_seconds: The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately. :param bool orphan_dependents: Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both. :param str propagation_policy: Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground. :param V1DeleteOptions body: :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: V1Status If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True return self.delete_namespaced_role_binding_with_http_info(name, namespace, **kwargs)
[ "def", "delete_namespaced_role_binding", "(", "self", ",", "name", ",", "namespace", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "return", "self", ".", "delete_namespaced_role_binding_with_http_info",...
https://github.com/kubernetes-client/python/blob/47b9da9de2d02b2b7a34fbe05afb44afd130d73a/kubernetes/client/api/rbac_authorization_v1alpha1_api.py#L1712-L1742
bungnoid/glTools
8ff0899de43784a18bd4543285655e68e28fb5e5
utils/namespace.py
python
moveNS
(srcNS,dstNS)
return newNS
Move all items from the source namespace to the destination namespace. @param srcNS: The source namespace @type srcNS: str @param dstNS: The destination namespace @type dstNS: str
Move all items from the source namespace to the destination namespace.
[ "Move", "all", "items", "from", "the", "source", "namespace", "to", "the", "destination", "namespace", "." ]
def moveNS(srcNS,dstNS): ''' Move all items from the source namespace to the destination namespace. @param srcNS: The source namespace @type srcNS: str @param dstNS: The destination namespace @type dstNS: str ''' # Check NS if not mc.namespace(exists=srcNS): raise Exception('Source namespace "'+srcNS+'" does not exist!') # Check Destination NS if not mc.namespace(exists=dstNS): # Create newNS dstNS = mc.namespace(add=dstNS,f=True) # Move namespace mc.namespace(mv=(srcNS,dstNS),f=True) # Return newNS return newNS
[ "def", "moveNS", "(", "srcNS", ",", "dstNS", ")", ":", "# Check NS", "if", "not", "mc", ".", "namespace", "(", "exists", "=", "srcNS", ")", ":", "raise", "Exception", "(", "'Source namespace \"'", "+", "srcNS", "+", "'\" does not exist!'", ")", "# Check Dest...
https://github.com/bungnoid/glTools/blob/8ff0899de43784a18bd4543285655e68e28fb5e5/utils/namespace.py#L94-L116
larryhastings/gilectomy
4315ec3f1d6d4f813cc82ce27a24e7f784dbfc1a
Lib/tempfile.py
python
_TemporaryFileWrapper.close
(self)
Close the temporary file, possibly deleting it.
Close the temporary file, possibly deleting it.
[ "Close", "the", "temporary", "file", "possibly", "deleting", "it", "." ]
def close(self): """ Close the temporary file, possibly deleting it. """ self._closer.close()
[ "def", "close", "(", "self", ")", ":", "self", ".", "_closer", ".", "close", "(", ")" ]
https://github.com/larryhastings/gilectomy/blob/4315ec3f1d6d4f813cc82ce27a24e7f784dbfc1a/Lib/tempfile.py#L505-L509
oracle/graalpython
577e02da9755d916056184ec441c26e00b70145c
graalpython/lib-python/3/tkinter/ttk.py
python
Treeview.__init__
(self, master=None, **kw)
Construct a Ttk Treeview with parent master. STANDARD OPTIONS class, cursor, style, takefocus, xscrollcommand, yscrollcommand WIDGET-SPECIFIC OPTIONS columns, displaycolumns, height, padding, selectmode, show ITEM OPTIONS text, image, values, open, tags TAG OPTIONS foreground, background, font, image
Construct a Ttk Treeview with parent master.
[ "Construct", "a", "Ttk", "Treeview", "with", "parent", "master", "." ]
def __init__(self, master=None, **kw): """Construct a Ttk Treeview with parent master. STANDARD OPTIONS class, cursor, style, takefocus, xscrollcommand, yscrollcommand WIDGET-SPECIFIC OPTIONS columns, displaycolumns, height, padding, selectmode, show ITEM OPTIONS text, image, values, open, tags TAG OPTIONS foreground, background, font, image """ Widget.__init__(self, master, "ttk::treeview", kw)
[ "def", "__init__", "(", "self", ",", "master", "=", "None", ",", "*", "*", "kw", ")", ":", "Widget", ".", "__init__", "(", "self", ",", "master", ",", "\"ttk::treeview\"", ",", "kw", ")" ]
https://github.com/oracle/graalpython/blob/577e02da9755d916056184ec441c26e00b70145c/graalpython/lib-python/3/tkinter/ttk.py#L1187-L1207
pythoncn/june
0cb9051e77757871479abe8b5da2a7df7ab191cb
june/handlers/account.py
python
signin
()
return render_template('account/signin.html', form=form)
Sign in page.
Sign in page.
[ "Sign", "in", "page", "." ]
def signin(): """Sign in page.""" next_url = request.args.get('next', '/') if g.user: return redirect(next_url) form = SigninForm() if form.validate_on_submit(): login_user(form.user, form.permanent.data) return redirect(next_url) return render_template('account/signin.html', form=form)
[ "def", "signin", "(", ")", ":", "next_url", "=", "request", ".", "args", ".", "get", "(", "'next'", ",", "'/'", ")", "if", "g", ".", "user", ":", "return", "redirect", "(", "next_url", ")", "form", "=", "SigninForm", "(", ")", "if", "form", ".", ...
https://github.com/pythoncn/june/blob/0cb9051e77757871479abe8b5da2a7df7ab191cb/june/handlers/account.py#L59-L68
rapid7/le
81d98bde8588f5ed74259b42b02ab03b51a0d339
src/le.py
python
date_patterns
()
Generates date patterns of the form [day<->month year?].
Generates date patterns of the form [day<->month year?].
[ "Generates", "date", "patterns", "of", "the", "form", "[", "day<", "-", ">", "month", "year?", "]", "." ]
def date_patterns(): """ Generates date patterns of the form [day<->month year?]. """ for year in [' %Y', ' %y']: for mon in ['%b', '%B', '%m']: yield ['%%d %s%s' % (mon, year), DAY, []] yield ['%s %%d%s' % (mon, year), DAY, []] for mon in ['%b', '%B']: # Year empty yield ['%%d %s' % (mon), DAY, [YEAR]] yield ['%s %%d' % (mon), DAY, [YEAR]] yield ['%%Y %%d %s' % (mon), DAY, []] yield ['%%Y %s %%d' % (mon), DAY, []] yield ['%Y %m %d', DAY, []]
[ "def", "date_patterns", "(", ")", ":", "for", "year", "in", "[", "' %Y'", ",", "' %y'", "]", ":", "for", "mon", "in", "[", "'%b'", ",", "'%B'", ",", "'%m'", "]", ":", "yield", "[", "'%%d %s%s'", "%", "(", "mon", ",", "year", ")", ",", "DAY", ",...
https://github.com/rapid7/le/blob/81d98bde8588f5ed74259b42b02ab03b51a0d339/src/le.py#L721-L733
quantopian/zipline
014f1fc339dc8b7671d29be2d85ce57d3daec343
zipline/utils/pool.py
python
ApplyAsyncResult.wait
(self)
Wait until the function is finished executing. Notes ----- In the :class:`~zipline.utils.pool.SequentialPool` case, this is a nop because the function is computed eagerly in the same thread as the call to :meth:`~zipline.utils.pool.SequentialPool.apply_async`.
Wait until the function is finished executing.
[ "Wait", "until", "the", "function", "is", "finished", "executing", "." ]
def wait(self): """Wait until the function is finished executing. Notes ----- In the :class:`~zipline.utils.pool.SequentialPool` case, this is a nop because the function is computed eagerly in the same thread as the call to :meth:`~zipline.utils.pool.SequentialPool.apply_async`. """ pass
[ "def", "wait", "(", "self", ")", ":", "pass" ]
https://github.com/quantopian/zipline/blob/014f1fc339dc8b7671d29be2d85ce57d3daec343/zipline/utils/pool.py#L45-L54
exodrifter/unity-python
bef6e4e9ddfbbf1eaf7acbbb973e9aa3dd64a20d
Lib/codecs.py
python
StreamReader.reset
(self)
Resets the codec buffers used for keeping state. Note that no stream repositioning should take place. This method is primarily intended to be able to recover from decoding errors.
Resets the codec buffers used for keeping state.
[ "Resets", "the", "codec", "buffers", "used", "for", "keeping", "state", "." ]
def reset(self): """ Resets the codec buffers used for keeping state. Note that no stream repositioning should take place. This method is primarily intended to be able to recover from decoding errors. """ self.bytebuffer = "" self.charbuffer = u"" self.linebuffer = None
[ "def", "reset", "(", "self", ")", ":", "self", ".", "bytebuffer", "=", "\"\"", "self", ".", "charbuffer", "=", "u\"\"", "self", ".", "linebuffer", "=", "None" ]
https://github.com/exodrifter/unity-python/blob/bef6e4e9ddfbbf1eaf7acbbb973e9aa3dd64a20d/Lib/codecs.py#L608-L619
wechatpy/wechatpy
5f693a7e90156786c2540ad3c941d12cdf6d88ef
wechatpy/client/api/merchant/__init__.py
python
WeChatMerchant.add_stock
(self, product_id, sku_info, quantity)
return self._post( "merchant/stock/add", data={"product_id": product_id, "sku_info": sku_info, "quantity": quantity}, )
增加库存 :param product_id: 商品ID :param sku_info: sku信息,格式"id1:vid1;id2:vid2",如商品为统一规格,则此处赋值为空字符串即可 :param quantity: 增加的库存数量 :return: 返回的 JSON 数据包
增加库存
[ "增加库存" ]
def add_stock(self, product_id, sku_info, quantity): """ 增加库存 :param product_id: 商品ID :param sku_info: sku信息,格式"id1:vid1;id2:vid2",如商品为统一规格,则此处赋值为空字符串即可 :param quantity: 增加的库存数量 :return: 返回的 JSON 数据包 """ return self._post( "merchant/stock/add", data={"product_id": product_id, "sku_info": sku_info, "quantity": quantity}, )
[ "def", "add_stock", "(", "self", ",", "product_id", ",", "sku_info", ",", "quantity", ")", ":", "return", "self", ".", "_post", "(", "\"merchant/stock/add\"", ",", "data", "=", "{", "\"product_id\"", ":", "product_id", ",", "\"sku_info\"", ":", "sku_info", "...
https://github.com/wechatpy/wechatpy/blob/5f693a7e90156786c2540ad3c941d12cdf6d88ef/wechatpy/client/api/merchant/__init__.py#L84-L96
tensorwerk/hangar-py
a6deb22854a6c9e9709011b91c1c0eeda7f47bb0
src/hangar/backends/chunk.py
python
_limit_es
(expected_mb)
return expected_mb
Protection against creating too small or too large chunks.
Protection against creating too small or too large chunks.
[ "Protection", "against", "creating", "too", "small", "or", "too", "large", "chunks", "." ]
def _limit_es(expected_mb): """Protection against creating too small or too large chunks.""" if expected_mb < 1: # < 1 MB expected_mb = 1 elif expected_mb > 10 ** 7: # > 10 TB expected_mb = 10 ** 7 return expected_mb
[ "def", "_limit_es", "(", "expected_mb", ")", ":", "if", "expected_mb", "<", "1", ":", "# < 1 MB", "expected_mb", "=", "1", "elif", "expected_mb", ">", "10", "**", "7", ":", "# > 10 TB", "expected_mb", "=", "10", "**", "7", "return", "expected_mb" ]
https://github.com/tensorwerk/hangar-py/blob/a6deb22854a6c9e9709011b91c1c0eeda7f47bb0/src/hangar/backends/chunk.py#L31-L38
m-labs/artiq
eaa1505c947c7987cdbd31c24056823c740e84e0
artiq/coredevice/novogorny.py
python
adc_channel
(data)
return (data >> 3) & 0x7
Return the channel index from a result packet
Return the channel index from a result packet
[ "Return", "the", "channel", "index", "from", "a", "result", "packet" ]
def adc_channel(data): """Return the channel index from a result packet""" return (data >> 3) & 0x7
[ "def", "adc_channel", "(", "data", ")", ":", "return", "(", "data", ">>", "3", ")", "&", "0x7" ]
https://github.com/m-labs/artiq/blob/eaa1505c947c7987cdbd31c24056823c740e84e0/artiq/coredevice/novogorny.py#L30-L32
SteveDoyle2/pyNastran
eda651ac2d4883d95a34951f8a002ff94f642a1a
pyNastran/op2/tables/geom/mpt.py
python
MPT._read_matt8
(self, data: bytes, n: int)
return n
common method to read MSC/NX MATT8s
common method to read MSC/NX MATT8s
[ "common", "method", "to", "read", "MSC", "/", "NX", "MATT8s" ]
def _read_matt8(self, data: bytes, n: int) -> int: """common method to read MSC/NX MATT8s""" op2 = self.op2 n = op2.reader_geom2._read_dual_card( data, n, self._read_matt8_18, self._read_matt8_19, 'MATT8', op2._add_methods._add_material_dependence_object) return n
[ "def", "_read_matt8", "(", "self", ",", "data", ":", "bytes", ",", "n", ":", "int", ")", "->", "int", ":", "op2", "=", "self", ".", "op2", "n", "=", "op2", ".", "reader_geom2", ".", "_read_dual_card", "(", "data", ",", "n", ",", "self", ".", "_re...
https://github.com/SteveDoyle2/pyNastran/blob/eda651ac2d4883d95a34951f8a002ff94f642a1a/pyNastran/op2/tables/geom/mpt.py#L998-L1004
almarklein/visvis
766ed97767b44a55a6ff72c742d7385e074d3d55
utils/guisupport.py
python
is_event_loop_running_qt4
(app=None)
Is the qt4 event loop running.
Is the qt4 event loop running.
[ "Is", "the", "qt4", "event", "loop", "running", "." ]
def is_event_loop_running_qt4(app=None): """Is the qt4 event loop running.""" if app is None: app = get_app_qt4(['']) if hasattr(app, '_in_event_loop'): return app._in_event_loop else: # Does qt4 provide a other way to detect this? return False
[ "def", "is_event_loop_running_qt4", "(", "app", "=", "None", ")", ":", "if", "app", "is", "None", ":", "app", "=", "get_app_qt4", "(", "[", "''", "]", ")", "if", "hasattr", "(", "app", ",", "'_in_event_loop'", ")", ":", "return", "app", ".", "_in_event...
https://github.com/almarklein/visvis/blob/766ed97767b44a55a6ff72c742d7385e074d3d55/utils/guisupport.py#L121-L129
MrH0wl/Cloudmare
65e5bc9888f9d362ab2abfb103ea6c1e869d67aa
thirdparty/click/types.py
python
convert_type
(ty, default=None)
return FuncParamType(ty)
Converts a callable or python type into the most appropriate param type.
Converts a callable or python type into the most appropriate param type.
[ "Converts", "a", "callable", "or", "python", "type", "into", "the", "most", "appropriate", "param", "type", "." ]
def convert_type(ty, default=None): """Converts a callable or python type into the most appropriate param type. """ guessed_type = False if ty is None and default is not None: if isinstance(default, tuple): ty = tuple(map(type, default)) else: ty = type(default) guessed_type = True if isinstance(ty, tuple): return Tuple(ty) if isinstance(ty, ParamType): return ty if ty is text_type or ty is str or ty is None: return STRING if ty is int: return INT # Booleans are only okay if not guessed. This is done because for # flags the default value is actually a bit of a lie in that it # indicates which of the flags is the one we want. See get_default() # for more information. if ty is bool and not guessed_type: return BOOL if ty is float: return FLOAT if guessed_type: return STRING # Catch a common mistake if __debug__: try: if issubclass(ty, ParamType): raise AssertionError( "Attempted to use an uninstantiated parameter type ({}).".format(ty) ) except TypeError: pass return FuncParamType(ty)
[ "def", "convert_type", "(", "ty", ",", "default", "=", "None", ")", ":", "guessed_type", "=", "False", "if", "ty", "is", "None", "and", "default", "is", "not", "None", ":", "if", "isinstance", "(", "default", ",", "tuple", ")", ":", "ty", "=", "tuple...
https://github.com/MrH0wl/Cloudmare/blob/65e5bc9888f9d362ab2abfb103ea6c1e869d67aa/thirdparty/click/types.py#L688-L728
mrJean1/PyGeodesy
7da5ca71aa3edb7bc49e219e0b8190686e1a7965
pygeodesy/utm.py
python
_toXtm8
(Xtm, z, lat, x, y, B, d, c, k, f, # PYCHOK 13+ args name, latlon, eps, Error=UTMError)
return r
(INTERNAL) Helper for methods L{toEtm8} and L{toUtm8}.
(INTERNAL) Helper for methods L{toEtm8} and L{toUtm8}.
[ "(", "INTERNAL", ")", "Helper", "for", "methods", "L", "{", "toEtm8", "}", "and", "L", "{", "toUtm8", "}", "." ]
def _toXtm8(Xtm, z, lat, x, y, B, d, c, k, f, # PYCHOK 13+ args name, latlon, eps, Error=UTMError): '''(INTERNAL) Helper for methods L{toEtm8} and L{toUtm8}. ''' h = _hemi(lat) if f: x, y = _false2(x, y, h) if Xtm is None: # DEPRECATED r = UtmUps8Tuple(z, h, x, y, B, d, c, k, Error=Error, name=name) else: r = _xnamed(Xtm(z, h, x, y, band=B, datum=d, falsed=f, convergence=c, scale=k), name) if isinstance(latlon, _LLEB) and d is latlon.datum: # see ups.toUtm8 r._latlon5args(latlon, _toBand, f, eps) # XXX weakref(latlon)? latlon._convergence = c latlon._scale = k elif not r._band: r._band = _toBand(lat) return r
[ "def", "_toXtm8", "(", "Xtm", ",", "z", ",", "lat", ",", "x", ",", "y", ",", "B", ",", "d", ",", "c", ",", "k", ",", "f", ",", "# PYCHOK 13+ args", "name", ",", "latlon", ",", "eps", ",", "Error", "=", "UTMError", ")", ":", "h", "=", "_hemi",...
https://github.com/mrJean1/PyGeodesy/blob/7da5ca71aa3edb7bc49e219e0b8190686e1a7965/pygeodesy/utm.py#L793-L811
owtf/owtf
22d6d35fb2a232fcc56bf5ed504ec52fd65f15b6
owtf/net/scanner.py
python
Scanner.target_service
(self, nmap_file, service)
return response
Services for a target :param nmap_file: Path to nmap file :type nmap_file: `str` :param service: Service to get :type service: `str` :return: Response :rtype: `str`
Services for a target
[ "Services", "for", "a", "target" ]
def target_service(self, nmap_file, service): """Services for a target :param nmap_file: Path to nmap file :type nmap_file: `str` :param service: Service to get :type service: `str` :return: Response :rtype: `str` """ ports_for_service = self.get_ports_for_service(service, "") f = FileOperations.open(nmap_file.strip()) response = "" for host_ports in re.findall("Host: (.*?)\tPorts: (.*?)[\t\n]", f.read()): host = host_ports[0].split(" ")[0] # Remove junk at the end ports = host_ports[1].split(",") for port_info in ports: if len(port_info) < 1: continue chunk = port_info.split("/") port = chunk[0].strip() port_state = chunk[1].strip() # No point in wasting time probing closed/filtered ports!! # (nmap sometimes adds these to the gnmap file for some reason ..) if port_state in ["closed", "filtered"]: continue try: prot = chunk[2].strip() except BaseException: continue if port in ports_for_service: response += "{!s}:{!s}:{!s}##".format(host, port, prot) f.close() return response
[ "def", "target_service", "(", "self", ",", "nmap_file", ",", "service", ")", ":", "ports_for_service", "=", "self", ".", "get_ports_for_service", "(", "service", ",", "\"\"", ")", "f", "=", "FileOperations", ".", "open", "(", "nmap_file", ".", "strip", "(", ...
https://github.com/owtf/owtf/blob/22d6d35fb2a232fcc56bf5ed504ec52fd65f15b6/owtf/net/scanner.py#L218-L251
oilshell/oil
94388e7d44a9ad879b12615f6203b38596b5a2d3
Python-2.7.13/Lib/threading.py
python
_Condition._is_owned
(self)
[]
def _is_owned(self): # Return True if lock is owned by current_thread. # This method is called only if __lock doesn't have _is_owned(). if self.__lock.acquire(0): self.__lock.release() return False else: return True
[ "def", "_is_owned", "(", "self", ")", ":", "# Return True if lock is owned by current_thread.", "# This method is called only if __lock doesn't have _is_owned().", "if", "self", ".", "__lock", ".", "acquire", "(", "0", ")", ":", "self", ".", "__lock", ".", "release", "(...
https://github.com/oilshell/oil/blob/94388e7d44a9ad879b12615f6203b38596b5a2d3/Python-2.7.13/Lib/threading.py#L300-L307
holzschu/Carnets
44effb10ddfc6aa5c8b0687582a724ba82c6b547
Library/lib/python3.7/site-packages/sympy/integrals/rubi/utility_function.py
python
SumSimplerQ
(u, v)
If u + v is simpler than u, SumSimplerQ(u, v) returns True, else it returns False. If for every term w of v there is a term of u equal to n*w where n<-1/2, u + v will be simpler than u. Examples ======== >>> from sympy.integrals.rubi.utility_function import SumSimplerQ >>> from sympy.abc import x >>> from sympy import S >>> SumSimplerQ(S(4 + x),S(3 + x**3)) False
If u + v is simpler than u, SumSimplerQ(u, v) returns True, else it returns False. If for every term w of v there is a term of u equal to n*w where n<-1/2, u + v will be simpler than u.
[ "If", "u", "+", "v", "is", "simpler", "than", "u", "SumSimplerQ", "(", "u", "v", ")", "returns", "True", "else", "it", "returns", "False", ".", "If", "for", "every", "term", "w", "of", "v", "there", "is", "a", "term", "of", "u", "equal", "to", "n...
def SumSimplerQ(u, v): """ If u + v is simpler than u, SumSimplerQ(u, v) returns True, else it returns False. If for every term w of v there is a term of u equal to n*w where n<-1/2, u + v will be simpler than u. Examples ======== >>> from sympy.integrals.rubi.utility_function import SumSimplerQ >>> from sympy.abc import x >>> from sympy import S >>> SumSimplerQ(S(4 + x),S(3 + x**3)) False """ if RationalQ(u, v): if v == S(0): return False elif v > S(0): return u < -S(1) else: return u >= -v else: return SumSimplerAuxQ(Expand(u), Expand(v))
[ "def", "SumSimplerQ", "(", "u", ",", "v", ")", ":", "if", "RationalQ", "(", "u", ",", "v", ")", ":", "if", "v", "==", "S", "(", "0", ")", ":", "return", "False", "elif", "v", ">", "S", "(", "0", ")", ":", "return", "u", "<", "-", "S", "("...
https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/site-packages/sympy/integrals/rubi/utility_function.py#L2303-L2326
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/lib/python2.7/site-packages/setuptools/dist.py
python
Distribution.get_egg_cache_dir
(self)
return egg_cache_dir
[]
def get_egg_cache_dir(self): egg_cache_dir = os.path.join(os.curdir, '.eggs') if not os.path.exists(egg_cache_dir): os.mkdir(egg_cache_dir) windows_support.hide_file(egg_cache_dir) readme_txt_filename = os.path.join(egg_cache_dir, 'README.txt') with open(readme_txt_filename, 'w') as f: f.write('This directory contains eggs that were downloaded ' 'by setuptools to build, test, and run plug-ins.\n\n') f.write('This directory caches those eggs to prevent ' 'repeated downloads.\n\n') f.write('However, it is safe to delete this directory.\n\n') return egg_cache_dir
[ "def", "get_egg_cache_dir", "(", "self", ")", ":", "egg_cache_dir", "=", "os", ".", "path", ".", "join", "(", "os", ".", "curdir", ",", "'.eggs'", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "egg_cache_dir", ")", ":", "os", ".", "mkdir",...
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/lib/python2.7/site-packages/setuptools/dist.py#L539-L552
brython-dev/brython
9cba5fb7f43a9b52fff13e89b403e02a1dfaa5f3
www/src/Lib/difflib.py
python
unified_diff
(a, b, fromfile='', tofile='', fromfiledate='', tofiledate='', n=3, lineterm='\n')
r""" Compare two sequences of lines; generate the delta as a unified diff. Unified diffs are a compact way of showing line changes and a few lines of context. The number of context lines is set by 'n' which defaults to three. By default, the diff control lines (those with ---, +++, or @@) are created with a trailing newline. This is helpful so that inputs created from file.readlines() result in diffs that are suitable for file.writelines() since both the inputs and outputs have trailing newlines. For inputs that do not have trailing newlines, set the lineterm argument to "" so that the output will be uniformly newline free. The unidiff format normally has a header for filenames and modification times. Any or all of these may be specified using strings for 'fromfile', 'tofile', 'fromfiledate', and 'tofiledate'. The modification times are normally expressed in the ISO 8601 format. Example: >>> for line in unified_diff('one two three four'.split(), ... 'zero one tree four'.split(), 'Original', 'Current', ... '2005-01-26 23:30:50', '2010-04-02 10:20:52', ... lineterm=''): ... print(line) # doctest: +NORMALIZE_WHITESPACE --- Original 2005-01-26 23:30:50 +++ Current 2010-04-02 10:20:52 @@ -1,4 +1,4 @@ +zero one -two -three +tree four
r""" Compare two sequences of lines; generate the delta as a unified diff.
[ "r", "Compare", "two", "sequences", "of", "lines", ";", "generate", "the", "delta", "as", "a", "unified", "diff", "." ]
def unified_diff(a, b, fromfile='', tofile='', fromfiledate='', tofiledate='', n=3, lineterm='\n'): r""" Compare two sequences of lines; generate the delta as a unified diff. Unified diffs are a compact way of showing line changes and a few lines of context. The number of context lines is set by 'n' which defaults to three. By default, the diff control lines (those with ---, +++, or @@) are created with a trailing newline. This is helpful so that inputs created from file.readlines() result in diffs that are suitable for file.writelines() since both the inputs and outputs have trailing newlines. For inputs that do not have trailing newlines, set the lineterm argument to "" so that the output will be uniformly newline free. The unidiff format normally has a header for filenames and modification times. Any or all of these may be specified using strings for 'fromfile', 'tofile', 'fromfiledate', and 'tofiledate'. The modification times are normally expressed in the ISO 8601 format. Example: >>> for line in unified_diff('one two three four'.split(), ... 'zero one tree four'.split(), 'Original', 'Current', ... '2005-01-26 23:30:50', '2010-04-02 10:20:52', ... lineterm=''): ... print(line) # doctest: +NORMALIZE_WHITESPACE --- Original 2005-01-26 23:30:50 +++ Current 2010-04-02 10:20:52 @@ -1,4 +1,4 @@ +zero one -two -three +tree four """ _check_types(a, b, fromfile, tofile, fromfiledate, tofiledate, lineterm) started = False for group in SequenceMatcher(None,a,b).get_grouped_opcodes(n): if not started: started = True fromdate = '\t{}'.format(fromfiledate) if fromfiledate else '' todate = '\t{}'.format(tofiledate) if tofiledate else '' yield '--- {}{}{}'.format(fromfile, fromdate, lineterm) yield '+++ {}{}{}'.format(tofile, todate, lineterm) first, last = group[0], group[-1] file1_range = _format_range_unified(first[1], last[2]) file2_range = _format_range_unified(first[3], last[4]) yield '@@ -{} +{} @@{}'.format(file1_range, file2_range, lineterm) for tag, i1, i2, j1, j2 in group: if tag == 'equal': for line in a[i1:i2]: yield ' ' + line continue if tag in {'replace', 'delete'}: for line in a[i1:i2]: yield '-' + line if tag in {'replace', 'insert'}: for line in b[j1:j2]: yield '+' + line
[ "def", "unified_diff", "(", "a", ",", "b", ",", "fromfile", "=", "''", ",", "tofile", "=", "''", ",", "fromfiledate", "=", "''", ",", "tofiledate", "=", "''", ",", "n", "=", "3", ",", "lineterm", "=", "'\\n'", ")", ":", "_check_types", "(", "a", ...
https://github.com/brython-dev/brython/blob/9cba5fb7f43a9b52fff13e89b403e02a1dfaa5f3/www/src/Lib/difflib.py#L1135-L1201
kensho-technologies/graphql-compiler
4318443b7b2512a059f3616112bfc40bbf8eec06
graphql_compiler/schema/__init__.py
python
is_vertex_field_name
(field_name: str)
return field_name.startswith(OUTBOUND_EDGE_FIELD_PREFIX) or field_name.startswith( INBOUND_EDGE_FIELD_PREFIX )
Return True if the field's name indicates it is a non-root vertex field.
Return True if the field's name indicates it is a non-root vertex field.
[ "Return", "True", "if", "the", "field", "s", "name", "indicates", "it", "is", "a", "non", "-", "root", "vertex", "field", "." ]
def is_vertex_field_name(field_name: str) -> bool: """Return True if the field's name indicates it is a non-root vertex field.""" # N.B.: A vertex field is a field whose type is a vertex type. This is what edges are. return field_name.startswith(OUTBOUND_EDGE_FIELD_PREFIX) or field_name.startswith( INBOUND_EDGE_FIELD_PREFIX )
[ "def", "is_vertex_field_name", "(", "field_name", ":", "str", ")", "->", "bool", ":", "# N.B.: A vertex field is a field whose type is a vertex type. This is what edges are.", "return", "field_name", ".", "startswith", "(", "OUTBOUND_EDGE_FIELD_PREFIX", ")", "or", "field_name",...
https://github.com/kensho-technologies/graphql-compiler/blob/4318443b7b2512a059f3616112bfc40bbf8eec06/graphql_compiler/schema/__init__.py#L313-L318
arsaboo/homeassistant-config
53c998986fbe84d793a0b174757154ab30e676e4
custom_components/futures_cnn/sensor.py
python
CNNFuturesSensor.icon
(self)
return icon
Return the icon to use in the frontend, if any.
Return the icon to use in the frontend, if any.
[ "Return", "the", "icon", "to", "use", "in", "the", "frontend", "if", "any", "." ]
def icon(self): """Return the icon to use in the frontend, if any.""" if self.type in ['sp', 'dow', 'nasdaq'] or self._state == 0: icon = DEFAULT_ICON elif self._state > 0: icon = 'mdi:arrow-up-bold-circle' elif self._state < 0: icon = 'mdi:arrow-down-bold-circle' return icon
[ "def", "icon", "(", "self", ")", ":", "if", "self", ".", "type", "in", "[", "'sp'", ",", "'dow'", ",", "'nasdaq'", "]", "or", "self", ".", "_state", "==", "0", ":", "icon", "=", "DEFAULT_ICON", "elif", "self", ".", "_state", ">", "0", ":", "icon"...
https://github.com/arsaboo/homeassistant-config/blob/53c998986fbe84d793a0b174757154ab30e676e4/custom_components/futures_cnn/sensor.py#L78-L86
pythonarcade/arcade
1ee3eb1900683213e8e8df93943327c2ea784564
arcade/examples/sprite_move_animation.py
python
load_texture_pair
(filename)
return [ arcade.load_texture(filename), arcade.load_texture(filename, flipped_horizontally=True) ]
Load a texture pair, with the second being a mirror image.
Load a texture pair, with the second being a mirror image.
[ "Load", "a", "texture", "pair", "with", "the", "second", "being", "a", "mirror", "image", "." ]
def load_texture_pair(filename): """ Load a texture pair, with the second being a mirror image. """ return [ arcade.load_texture(filename), arcade.load_texture(filename, flipped_horizontally=True) ]
[ "def", "load_texture_pair", "(", "filename", ")", ":", "return", "[", "arcade", ".", "load_texture", "(", "filename", ")", ",", "arcade", ".", "load_texture", "(", "filename", ",", "flipped_horizontally", "=", "True", ")", "]" ]
https://github.com/pythonarcade/arcade/blob/1ee3eb1900683213e8e8df93943327c2ea784564/arcade/examples/sprite_move_animation.py#L31-L38
TencentCloud/tencentcloud-sdk-python
3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2
tencentcloud/dcdb/v20180411/models.py
python
DCDBShardInfo.__init__
(self)
r""" :param InstanceId: 所属实例Id :type InstanceId: str :param ShardSerialId: 分片SQL透传Id,用于将sql透传到指定分片执行 :type ShardSerialId: str :param ShardInstanceId: 全局唯一的分片Id :type ShardInstanceId: str :param Status: 状态:0 创建中,1 流程处理中, 2 运行中,3 分片未初始化 :type Status: int :param StatusDesc: 状态中文描述 :type StatusDesc: str :param CreateTime: 创建时间 :type CreateTime: str :param VpcId: 字符串格式的私有网络Id :type VpcId: str :param SubnetId: 字符串格式的私有网络子网Id :type SubnetId: str :param ProjectId: 项目ID :type ProjectId: int :param Region: 地域 :type Region: str :param Zone: 可用区 :type Zone: str :param Memory: 内存大小,单位 GB :type Memory: int :param Storage: 存储大小,单位 GB :type Storage: int :param PeriodEndTime: 到期时间 :type PeriodEndTime: str :param NodeCount: 节点数,2 为一主一从, 3 为一主二从 :type NodeCount: int :param StorageUsage: 存储使用率,单位为 % :type StorageUsage: float :param MemoryUsage: 内存使用率,单位为 % :type MemoryUsage: float :param ShardId: 数字分片Id(过时字段,请勿依赖该值) :type ShardId: int :param Pid: 产品ProductID :type Pid: int :param ProxyVersion: Proxy版本 :type ProxyVersion: str :param Paymode: 付费模型 注意:此字段可能返回 null,表示取不到有效值。 :type Paymode: str :param ShardMasterZone: 分片的主可用区 注意:此字段可能返回 null,表示取不到有效值。 :type ShardMasterZone: str :param ShardSlaveZones: 分片的从可用区列表 注意:此字段可能返回 null,表示取不到有效值。 :type ShardSlaveZones: list of str :param Cpu: CPU核数 :type Cpu: int :param Range: 分片ShardKey的范围(总共64个哈希值),例如: 0-31,32-63 :type Range: str
r""" :param InstanceId: 所属实例Id :type InstanceId: str :param ShardSerialId: 分片SQL透传Id,用于将sql透传到指定分片执行 :type ShardSerialId: str :param ShardInstanceId: 全局唯一的分片Id :type ShardInstanceId: str :param Status: 状态:0 创建中,1 流程处理中, 2 运行中,3 分片未初始化 :type Status: int :param StatusDesc: 状态中文描述 :type StatusDesc: str :param CreateTime: 创建时间 :type CreateTime: str :param VpcId: 字符串格式的私有网络Id :type VpcId: str :param SubnetId: 字符串格式的私有网络子网Id :type SubnetId: str :param ProjectId: 项目ID :type ProjectId: int :param Region: 地域 :type Region: str :param Zone: 可用区 :type Zone: str :param Memory: 内存大小,单位 GB :type Memory: int :param Storage: 存储大小,单位 GB :type Storage: int :param PeriodEndTime: 到期时间 :type PeriodEndTime: str :param NodeCount: 节点数,2 为一主一从, 3 为一主二从 :type NodeCount: int :param StorageUsage: 存储使用率,单位为 % :type StorageUsage: float :param MemoryUsage: 内存使用率,单位为 % :type MemoryUsage: float :param ShardId: 数字分片Id(过时字段,请勿依赖该值) :type ShardId: int :param Pid: 产品ProductID :type Pid: int :param ProxyVersion: Proxy版本 :type ProxyVersion: str :param Paymode: 付费模型 注意:此字段可能返回 null,表示取不到有效值。 :type Paymode: str :param ShardMasterZone: 分片的主可用区 注意:此字段可能返回 null,表示取不到有效值。 :type ShardMasterZone: str :param ShardSlaveZones: 分片的从可用区列表 注意:此字段可能返回 null,表示取不到有效值。 :type ShardSlaveZones: list of str :param Cpu: CPU核数 :type Cpu: int :param Range: 分片ShardKey的范围(总共64个哈希值),例如: 0-31,32-63 :type Range: str
[ "r", ":", "param", "InstanceId", ":", "所属实例Id", ":", "type", "InstanceId", ":", "str", ":", "param", "ShardSerialId", ":", "分片SQL透传Id,用于将sql透传到指定分片执行", ":", "type", "ShardSerialId", ":", "str", ":", "param", "ShardInstanceId", ":", "全局唯一的分片Id", ":", "type", "S...
def __init__(self): r""" :param InstanceId: 所属实例Id :type InstanceId: str :param ShardSerialId: 分片SQL透传Id,用于将sql透传到指定分片执行 :type ShardSerialId: str :param ShardInstanceId: 全局唯一的分片Id :type ShardInstanceId: str :param Status: 状态:0 创建中,1 流程处理中, 2 运行中,3 分片未初始化 :type Status: int :param StatusDesc: 状态中文描述 :type StatusDesc: str :param CreateTime: 创建时间 :type CreateTime: str :param VpcId: 字符串格式的私有网络Id :type VpcId: str :param SubnetId: 字符串格式的私有网络子网Id :type SubnetId: str :param ProjectId: 项目ID :type ProjectId: int :param Region: 地域 :type Region: str :param Zone: 可用区 :type Zone: str :param Memory: 内存大小,单位 GB :type Memory: int :param Storage: 存储大小,单位 GB :type Storage: int :param PeriodEndTime: 到期时间 :type PeriodEndTime: str :param NodeCount: 节点数,2 为一主一从, 3 为一主二从 :type NodeCount: int :param StorageUsage: 存储使用率,单位为 % :type StorageUsage: float :param MemoryUsage: 内存使用率,单位为 % :type MemoryUsage: float :param ShardId: 数字分片Id(过时字段,请勿依赖该值) :type ShardId: int :param Pid: 产品ProductID :type Pid: int :param ProxyVersion: Proxy版本 :type ProxyVersion: str :param Paymode: 付费模型 注意:此字段可能返回 null,表示取不到有效值。 :type Paymode: str :param ShardMasterZone: 分片的主可用区 注意:此字段可能返回 null,表示取不到有效值。 :type ShardMasterZone: str :param ShardSlaveZones: 分片的从可用区列表 注意:此字段可能返回 null,表示取不到有效值。 :type ShardSlaveZones: list of str :param Cpu: CPU核数 :type Cpu: int :param Range: 分片ShardKey的范围(总共64个哈希值),例如: 0-31,32-63 :type Range: str """ self.InstanceId = None self.ShardSerialId = None self.ShardInstanceId = None self.Status = None self.StatusDesc = None self.CreateTime = None self.VpcId = None self.SubnetId = None self.ProjectId = None self.Region = None self.Zone = None self.Memory = None self.Storage = None self.PeriodEndTime = None self.NodeCount = None self.StorageUsage = None self.MemoryUsage = None self.ShardId = None self.Pid = None self.ProxyVersion = None self.Paymode = None self.ShardMasterZone = None self.ShardSlaveZones = None self.Cpu = None self.Range = None
[ "def", "__init__", "(", "self", ")", ":", "self", ".", "InstanceId", "=", "None", "self", ".", "ShardSerialId", "=", "None", "self", ".", "ShardInstanceId", "=", "None", "self", ".", "Status", "=", "None", "self", ".", "StatusDesc", "=", "None", "self", ...
https://github.com/TencentCloud/tencentcloud-sdk-python/blob/3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2/tencentcloud/dcdb/v20180411/models.py#L1074-L1154
PowerScript/KatanaFramework
0f6ad90a88de865d58ec26941cb4460501e75496
lib/libusb1/build/lib.linux-i686-2.7/usb1.py
python
USBTransfer.getUserData
(self)
return self.__user_data
Retrieve user data provided on setup.
Retrieve user data provided on setup.
[ "Retrieve", "user", "data", "provided", "on", "setup", "." ]
def getUserData(self): """ Retrieve user data provided on setup. """ return self.__user_data
[ "def", "getUserData", "(", "self", ")", ":", "return", "self", ".", "__user_data" ]
https://github.com/PowerScript/KatanaFramework/blob/0f6ad90a88de865d58ec26941cb4460501e75496/lib/libusb1/build/lib.linux-i686-2.7/usb1.py#L583-L587
Conchylicultor/MusicGenerator
adea76dccaba923b7d3807082ec6f5b512d16bb9
deepmusic/modules/decoder.py
python
Rnn.build
(self)
Initialize the weights of the model
Initialize the weights of the model
[ "Initialize", "the", "weights", "of", "the", "model" ]
def build(self): """ Initialize the weights of the model """ self.rnn_cell = tfutils.get_rnn_cell(self.args, "deco_cell") self.project_key = tfutils.single_layer_perceptron([self.args.hidden_size, 1], 'project_key')
[ "def", "build", "(", "self", ")", ":", "self", ".", "rnn_cell", "=", "tfutils", ".", "get_rnn_cell", "(", "self", ".", "args", ",", "\"deco_cell\"", ")", "self", ".", "project_key", "=", "tfutils", ".", "single_layer_perceptron", "(", "[", "self", ".", "...
https://github.com/Conchylicultor/MusicGenerator/blob/adea76dccaba923b7d3807082ec6f5b512d16bb9/deepmusic/modules/decoder.py#L77-L82
steeve/xbmctorrent
e6bcb1037668959e1e3cb5ba8cf3e379c6638da9
resources/site-packages/html5lib/treewalkers/dom.py
python
TreeWalker.getParentNode
(self, node)
return node.parentNode
[]
def getParentNode(self, node): return node.parentNode
[ "def", "getParentNode", "(", "self", ",", "node", ")", ":", "return", "node", ".", "parentNode" ]
https://github.com/steeve/xbmctorrent/blob/e6bcb1037668959e1e3cb5ba8cf3e379c6638da9/resources/site-packages/html5lib/treewalkers/dom.py#L45-L46
GNS3/gns3-gui
da8adbaa18ab60e053af2a619efd468f4c8950f3
gns3/dialogs/doctor_dialog.py
python
DoctorDialog.checkExperimentalFeaturesEnabled
(self)
return (0, None)
Checking if experimental features are not enabled
Checking if experimental features are not enabled
[ "Checking", "if", "experimental", "features", "are", "not", "enabled" ]
def checkExperimentalFeaturesEnabled(self): """Checking if experimental features are not enabled""" if LocalConfig.instance().experimental(): return (1, "Experimental features are enabled. Turn them off by going to Preferences -> General -> Miscellaneous.") return (0, None)
[ "def", "checkExperimentalFeaturesEnabled", "(", "self", ")", ":", "if", "LocalConfig", ".", "instance", "(", ")", ".", "experimental", "(", ")", ":", "return", "(", "1", ",", "\"Experimental features are enabled. Turn them off by going to Preferences -> General -> Miscellan...
https://github.com/GNS3/gns3-gui/blob/da8adbaa18ab60e053af2a619efd468f4c8950f3/gns3/dialogs/doctor_dialog.py#L89-L93
BillBillBillBill/Tickeys-linux
2df31b8665004c58a5d4ab05277f245267d96364
tickeys/kivy_32/kivy/storage/__init__.py
python
AbstractStore.keys
(self)
return self.store_keys()
Return a list of all the keys in the storage.
Return a list of all the keys in the storage.
[ "Return", "a", "list", "of", "all", "the", "keys", "in", "the", "storage", "." ]
def keys(self): '''Return a list of all the keys in the storage. ''' return self.store_keys()
[ "def", "keys", "(", "self", ")", ":", "return", "self", ".", "store_keys", "(", ")" ]
https://github.com/BillBillBillBill/Tickeys-linux/blob/2df31b8665004c58a5d4ab05277f245267d96364/tickeys/kivy_32/kivy/storage/__init__.py#L256-L259
JinpengLI/deep_ocr
450148c0c51b3565a96ac2f3c94ee33022e55307
deep_ocr/ocrolib/common.py
python
RegionExtractor.bbox
(self,i)
return (r[0].start,r[1].start,r[0].stop,r[1].stop)
Return the bounding box in raster coordinates (row0,col0,row1,col1).
Return the bounding box in raster coordinates (row0,col0,row1,col1).
[ "Return", "the", "bounding", "box", "in", "raster", "coordinates", "(", "row0", "col0", "row1", "col1", ")", "." ]
def bbox(self,i): """Return the bounding box in raster coordinates (row0,col0,row1,col1).""" r = self.objects[i] # print("@@@bbox", i, r) return (r[0].start,r[1].start,r[0].stop,r[1].stop)
[ "def", "bbox", "(", "self", ",", "i", ")", ":", "r", "=", "self", ".", "objects", "[", "i", "]", "# print(\"@@@bbox\", i, r)", "return", "(", "r", "[", "0", "]", ".", "start", ",", "r", "[", "1", "]", ".", "start", ",", "r", "[", "0", "]", "....
https://github.com/JinpengLI/deep_ocr/blob/450148c0c51b3565a96ac2f3c94ee33022e55307/deep_ocr/ocrolib/common.py#L362-L367
qibinlou/SinaWeibo-Emotion-Classification
f336fc104abd68b0ec4180fe2ed80fafe49cb790
nltk/tag/senna.py
python
NERTagger.batch_tag
(self, sentences)
return tagged_sents
Applies the tag method over a list of sentences. This method will return for each sentence a list of tuples of (word, tag).
Applies the tag method over a list of sentences. This method will return for each sentence a list of tuples of (word, tag).
[ "Applies", "the", "tag", "method", "over", "a", "list", "of", "sentences", ".", "This", "method", "will", "return", "for", "each", "sentence", "a", "list", "of", "tuples", "of", "(", "word", "tag", ")", "." ]
def batch_tag(self, sentences): """ Applies the tag method over a list of sentences. This method will return for each sentence a list of tuples of (word, tag). """ tagged_sents = super(NERTagger, self).batch_tag(sentences) for i in range(len(tagged_sents)): for j in range(len(tagged_sents[i])): annotations = tagged_sents[i][j] tagged_sents[i][j] = (annotations['word'], annotations['ner']) return tagged_sents
[ "def", "batch_tag", "(", "self", ",", "sentences", ")", ":", "tagged_sents", "=", "super", "(", "NERTagger", ",", "self", ")", ".", "batch_tag", "(", "sentences", ")", "for", "i", "in", "range", "(", "len", "(", "tagged_sents", ")", ")", ":", "for", ...
https://github.com/qibinlou/SinaWeibo-Emotion-Classification/blob/f336fc104abd68b0ec4180fe2ed80fafe49cb790/nltk/tag/senna.py#L244-L254
Tribler/tribler
f1de8bd54f293b01b2646a1dead1c1dc9dfdb356
src/tribler-core/tribler_core/components/libtorrent/download_manager/download_config.py
python
DownloadConfig.get_selected_files
(self)
return self.config['download_defaults']['selected_file_indexes']
Returns the list of files selected for download. @return A list of file indexes.
Returns the list of files selected for download.
[ "Returns", "the", "list", "of", "files", "selected", "for", "download", "." ]
def get_selected_files(self): """ Returns the list of files selected for download. @return A list of file indexes. """ return self.config['download_defaults']['selected_file_indexes']
[ "def", "get_selected_files", "(", "self", ")", ":", "return", "self", ".", "config", "[", "'download_defaults'", "]", "[", "'selected_file_indexes'", "]" ]
https://github.com/Tribler/tribler/blob/f1de8bd54f293b01b2646a1dead1c1dc9dfdb356/src/tribler-core/tribler_core/components/libtorrent/download_manager/download_config.py#L116-L119
iocast/featureserver
2828532294fe232f1ddf358cfbd2cc81af102e56
vectorformats/lib/shapefile.py
python
Writer.saveDbf
(self, target)
Save a dbf file.
Save a dbf file.
[ "Save", "a", "dbf", "file", "." ]
def saveDbf(self, target): """Save a dbf file.""" if not hasattr(target, "write"): target = os.path.splitext(target)[0] + '.dbf' self.dbf = self.__getFileObj(target) self.__dbfHeader() self.__dbfRecords()
[ "def", "saveDbf", "(", "self", ",", "target", ")", ":", "if", "not", "hasattr", "(", "target", ",", "\"write\"", ")", ":", "target", "=", "os", ".", "path", ".", "splitext", "(", "target", ")", "[", "0", "]", "+", "'.dbf'", "self", ".", "dbf", "=...
https://github.com/iocast/featureserver/blob/2828532294fe232f1ddf358cfbd2cc81af102e56/vectorformats/lib/shapefile.py#L1830-L1836
RomelTorres/alpha_vantage
c637657579950d72605320c68ded42a447566cdf
alpha_vantage/async_support/sectorperformance.py
python
SectorPerformances.__init__
(self, *args, **kwargs)
Inherit AlphaVantage base class with its default arguments
Inherit AlphaVantage base class with its default arguments
[ "Inherit", "AlphaVantage", "base", "class", "with", "its", "default", "arguments" ]
def __init__(self, *args, **kwargs): """ Inherit AlphaVantage base class with its default arguments """ super(SectorPerformances, self).__init__(*args, **kwargs) self._append_type = False if self.output_format.lower() == 'csv': raise ValueError("Output format {} is not comatible with the SectorPerformances class".format( self.output_format.lower()))
[ "def", "__init__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "super", "(", "SectorPerformances", ",", "self", ")", ".", "__init__", "(", "*", "args", ",", "*", "*", "kwargs", ")", "self", ".", "_append_type", "=", "False", "...
https://github.com/RomelTorres/alpha_vantage/blob/c637657579950d72605320c68ded42a447566cdf/alpha_vantage/async_support/sectorperformance.py#L9-L17
GoogleCloudPlatform/PerfKitBenchmarker
6e3412d7d5e414b8ca30ed5eaf970cef1d919a67
perfkitbenchmarker/linux_packages/ycsb.py
python
YCSBExecutor._RunThreaded
(self, vms, **kwargs)
return results
Run a single workload using `vms`.
Run a single workload using `vms`.
[ "Run", "a", "single", "workload", "using", "vms", "." ]
def _RunThreaded(self, vms, **kwargs): """Run a single workload using `vms`.""" target = kwargs.pop('target', None) if target is not None: target_per_client = target // len(vms) targets = [ target_per_client + (1 if i < (target % len(vms)) else 0) for i in range(len(vms)) ] else: targets = [target for _ in vms] results = [] if self.shardkeyspace: record_count = int(self.workload_meta.get('recordcount', '1000')) n_per_client = int(record_count) // len(vms) loader_counts = [ n_per_client + (1 if i < (record_count % len(vms)) else 0) for i in range(len(vms)) ] def _Run(loader_index): """Run YCSB on an individual VM.""" vm = vms[loader_index] params = copy.deepcopy(kwargs) params['target'] = targets[loader_index] if self.perclientparam is not None: params.update(self.perclientparam[loader_index]) if self.shardkeyspace: start = sum(loader_counts[:loader_index]) end = start + loader_counts[loader_index] params.update(insertstart=start, recordcount=end) results.append(self._Run(vm, **params)) logging.info('VM %d (%s) finished', loader_index, vm) vm_util.RunThreaded(_Run, list(range(len(vms)))) if len(results) != len(vms): raise IOError('Missing results: only {0}/{1} reported\n{2}'.format( len(results), len(vms), results)) return results
[ "def", "_RunThreaded", "(", "self", ",", "vms", ",", "*", "*", "kwargs", ")", ":", "target", "=", "kwargs", ".", "pop", "(", "'target'", ",", "None", ")", "if", "target", "is", "not", "None", ":", "target_per_client", "=", "target", "//", "len", "(",...
https://github.com/GoogleCloudPlatform/PerfKitBenchmarker/blob/6e3412d7d5e414b8ca30ed5eaf970cef1d919a67/perfkitbenchmarker/linux_packages/ycsb.py#L1140-L1183
tensorboy/pytorch_Realtime_Multi-Person_Pose_Estimation
b3e8abf12b172da1ab850e0ff8411c75151154c0
lib/network/post.py
python
group_limbs_of_same_person
(connected_limbs, joint_list)
return np.array(person_to_joint_assoc)
Associate limbs belonging to the same person together. :param connected_limbs: See 'return' doc of find_connected_joints() :param joint_list: unravel'd version of joint_list_per_joint [See 'return' doc of NMS()] :return: 2d np.array of size num_people x (NUM_JOINTS+2). For each person found: # First NUM_JOINTS columns contain the index (in joint_list) of the joints associated with that person (or -1 if their i-th joint wasn't found) # 2nd-to-last column: Overall score of the joints+limbs that belong to this person # Last column: Total count of joints found for this person
Associate limbs belonging to the same person together. :param connected_limbs: See 'return' doc of find_connected_joints() :param joint_list: unravel'd version of joint_list_per_joint [See 'return' doc of NMS()] :return: 2d np.array of size num_people x (NUM_JOINTS+2). For each person found: # First NUM_JOINTS columns contain the index (in joint_list) of the joints associated with that person (or -1 if their i-th joint wasn't found) # 2nd-to-last column: Overall score of the joints+limbs that belong to this person # Last column: Total count of joints found for this person
[ "Associate", "limbs", "belonging", "to", "the", "same", "person", "together", ".", ":", "param", "connected_limbs", ":", "See", "return", "doc", "of", "find_connected_joints", "()", ":", "param", "joint_list", ":", "unravel", "d", "version", "of", "joint_list_pe...
def group_limbs_of_same_person(connected_limbs, joint_list): """ Associate limbs belonging to the same person together. :param connected_limbs: See 'return' doc of find_connected_joints() :param joint_list: unravel'd version of joint_list_per_joint [See 'return' doc of NMS()] :return: 2d np.array of size num_people x (NUM_JOINTS+2). For each person found: # First NUM_JOINTS columns contain the index (in joint_list) of the joints associated with that person (or -1 if their i-th joint wasn't found) # 2nd-to-last column: Overall score of the joints+limbs that belong to this person # Last column: Total count of joints found for this person """ person_to_joint_assoc = [] for limb_type in range(NUM_LIMBS): joint_src_type, joint_dst_type = joint_to_limb_heatmap_relationship[limb_type] for limb_info in connected_limbs[limb_type]: person_assoc_idx = [] for person, person_limbs in enumerate(person_to_joint_assoc): if person_limbs[joint_src_type] == limb_info[0] or person_limbs[joint_dst_type] == limb_info[1]: person_assoc_idx.append(person) # If one of the joints has been associated to a person, and either # the other joint is also associated with the same person or not # associated to anyone yet: if len(person_assoc_idx) == 1: person_limbs = person_to_joint_assoc[person_assoc_idx[0]] # If the other joint is not associated to anyone yet, if person_limbs[joint_dst_type] != limb_info[1]: # Associate it with the current person person_limbs[joint_dst_type] = limb_info[1] # Increase the number of limbs associated to this person person_limbs[-1] += 1 # And update the total score (+= heatmap score of joint_dst # + score of connecting joint_src with joint_dst) person_limbs[-2] += joint_list[limb_info[1] .astype(int), 2] + limb_info[2] elif len(person_assoc_idx) == 2: # if found 2 and disjoint, merge them person1_limbs = person_to_joint_assoc[person_assoc_idx[0]] person2_limbs = person_to_joint_assoc[person_assoc_idx[1]] membership = ((person1_limbs >= 0) & (person2_limbs >= 0))[:-2] if not membership.any(): # If both people have no same joints connected, merge them into a single person # Update which joints are connected person1_limbs[:-2] += (person2_limbs[:-2] + 1) # Update the overall score and total count of joints # connected by summing their counters person1_limbs[-2:] += person2_limbs[-2:] # Add the score of the current joint connection to the # overall score person1_limbs[-2] += limb_info[2] person_to_joint_assoc.pop(person_assoc_idx[1]) else: # Same case as len(person_assoc_idx)==1 above person1_limbs[joint_dst_type] = limb_info[1] person1_limbs[-1] += 1 person1_limbs[-2] += joint_list[limb_info[1] .astype(int), 2] + limb_info[2] else: # No person has claimed any of these joints, create a new person # Initialize person info to all -1 (no joint associations) row = -1 * np.ones(20) # Store the joint info of the new connection row[joint_src_type] = limb_info[0] row[joint_dst_type] = limb_info[1] # Total count of connected joints for this person: 2 row[-1] = 2 # Compute overall score: score joint_src + score joint_dst + score connection # {joint_src,joint_dst} row[-2] = sum(joint_list[limb_info[:2].astype(int), 2] ) + limb_info[2] person_to_joint_assoc.append(row) # Delete people who have very few parts connected people_to_delete = [] for person_id, person_info in enumerate(person_to_joint_assoc): if person_info[-1] < 3 or person_info[-2] / person_info[-1] < 0.2: people_to_delete.append(person_id) # Traverse the list in reverse order so we delete indices starting from the # last one (otherwise, removing item for example 0 would modify the indices of # the remaining people to be deleted!) for index in people_to_delete[::-1]: person_to_joint_assoc.pop(index) # Appending items to a np.array can be very costly (allocating new memory, copying over the array, then adding new row) # Instead, we treat the set of people as a list (fast to append items) and # only convert to np.array at the end return np.array(person_to_joint_assoc)
[ "def", "group_limbs_of_same_person", "(", "connected_limbs", ",", "joint_list", ")", ":", "person_to_joint_assoc", "=", "[", "]", "for", "limb_type", "in", "range", "(", "NUM_LIMBS", ")", ":", "joint_src_type", ",", "joint_dst_type", "=", "joint_to_limb_heatmap_relati...
https://github.com/tensorboy/pytorch_Realtime_Multi-Person_Pose_Estimation/blob/b3e8abf12b172da1ab850e0ff8411c75151154c0/lib/network/post.py#L270-L354
ssato/python-anyconfig
09af1950f3226759932f5168d52f5e06ab88815c
src/anyconfig/processors/utils.py
python
load_plugins
(pgroup: str)
A generator function to yield a class object of :class:`anyconfig.models.processor.Processor`. :param pgroup: A string represents plugin type, e.g. anyconfig_backends
A generator function to yield a class object of :class:`anyconfig.models.processor.Processor`.
[ "A", "generator", "function", "to", "yield", "a", "class", "object", "of", ":", "class", ":", "anyconfig", ".", "models", ".", "processor", ".", "Processor", "." ]
def load_plugins(pgroup: str) -> typing.Iterator[ProcClsT]: """ A generator function to yield a class object of :class:`anyconfig.models.processor.Processor`. :param pgroup: A string represents plugin type, e.g. anyconfig_backends """ for res in pkg_resources.iter_entry_points(pgroup): try: yield res.load() except ImportError as exc: warnings.warn(f'Failed to load plugin, exc={exc!s}')
[ "def", "load_plugins", "(", "pgroup", ":", "str", ")", "->", "typing", ".", "Iterator", "[", "ProcClsT", "]", ":", "for", "res", "in", "pkg_resources", ".", "iter_entry_points", "(", "pgroup", ")", ":", "try", ":", "yield", "res", ".", "load", "(", ")"...
https://github.com/ssato/python-anyconfig/blob/09af1950f3226759932f5168d52f5e06ab88815c/src/anyconfig/processors/utils.py#L224-L235
facebookresearch/DetectAndTrack
9d64bfb16d6ed85c828ca03d195ac618ca04a67b
lib/utils/file_sys.py
python
mkdir_exists
(path)
Makes a directory if it does not exist already.
Makes a directory if it does not exist already.
[ "Makes", "a", "directory", "if", "it", "does", "not", "exist", "already", "." ]
def mkdir_exists(path): """Makes a directory if it does not exist already.""" try: os.mkdir(path) except OSError as exc: if exc.errno != errno.EEXIST: raise
[ "def", "mkdir_exists", "(", "path", ")", ":", "try", ":", "os", ".", "mkdir", "(", "path", ")", "except", "OSError", "as", "exc", ":", "if", "exc", ".", "errno", "!=", "errno", ".", "EEXIST", ":", "raise" ]
https://github.com/facebookresearch/DetectAndTrack/blob/9d64bfb16d6ed85c828ca03d195ac618ca04a67b/lib/utils/file_sys.py#L22-L28
numba/numba
bf480b9e0da858a65508c2b17759a72ee6a44c51
numba/core/interpreter.py
python
Interpreter.store
(self, value, name, redefine=False)
return target
Store *value* (a Expr or Var instance) into the variable named *name* (a str object). Returns the target variable.
Store *value* (a Expr or Var instance) into the variable named *name* (a str object). Returns the target variable.
[ "Store", "*", "value", "*", "(", "a", "Expr", "or", "Var", "instance", ")", "into", "the", "variable", "named", "*", "name", "*", "(", "a", "str", "object", ")", ".", "Returns", "the", "target", "variable", "." ]
def store(self, value, name, redefine=False): """ Store *value* (a Expr or Var instance) into the variable named *name* (a str object). Returns the target variable. """ if redefine or self.current_block_offset in self.cfa.backbone: rename = not (name in self.code_cellvars) target = self.current_scope.redefine(name, loc=self.loc, rename=rename) else: target = self.current_scope.get_or_define(name, loc=self.loc) if isinstance(value, ir.Var): value = self.assigner.assign(value, target) stmt = ir.Assign(value=value, target=target, loc=self.loc) self.current_block.append(stmt) self.definitions[target.name].append(value) return target
[ "def", "store", "(", "self", ",", "value", ",", "name", ",", "redefine", "=", "False", ")", ":", "if", "redefine", "or", "self", ".", "current_block_offset", "in", "self", ".", "cfa", ".", "backbone", ":", "rename", "=", "not", "(", "name", "in", "se...
https://github.com/numba/numba/blob/bf480b9e0da858a65508c2b17759a72ee6a44c51/numba/core/interpreter.py#L692-L708
kedro-org/kedro
e78990c6b606a27830f0d502afa0f639c0830950
kedro/extras/datasets/spark/spark_hive_dataset.py
python
SparkHiveDataSet.__init__
( self, database: str, table: str, write_mode: str, table_pk: List[str] = None )
Creates a new instance of ``SparkHiveDataSet``. Args: database: The name of the hive database. table: The name of the table within the database. write_mode: ``insert``, ``upsert`` or ``overwrite`` are supported. table_pk: If performing an upsert, this identifies the primary key columns used to resolve preexisting data. Is required for ``write_mode="upsert"``. Raises: DataSetError: Invalid configuration supplied
Creates a new instance of ``SparkHiveDataSet``.
[ "Creates", "a", "new", "instance", "of", "SparkHiveDataSet", "." ]
def __init__( self, database: str, table: str, write_mode: str, table_pk: List[str] = None ) -> None: """Creates a new instance of ``SparkHiveDataSet``. Args: database: The name of the hive database. table: The name of the table within the database. write_mode: ``insert``, ``upsert`` or ``overwrite`` are supported. table_pk: If performing an upsert, this identifies the primary key columns used to resolve preexisting data. Is required for ``write_mode="upsert"``. Raises: DataSetError: Invalid configuration supplied """ valid_write_modes = ["insert", "upsert", "overwrite"] if write_mode not in valid_write_modes: valid_modes = ", ".join(valid_write_modes) raise DataSetError( f"Invalid `write_mode` provided: {write_mode}. " f"`write_mode` must be one of: {valid_modes}" ) if write_mode == "upsert" and not table_pk: raise DataSetError("`table_pk` must be set to utilise `upsert` read mode") self._write_mode = write_mode self._table_pk = table_pk or [] self._database = database self._table = table self._stage_table = "_temp_" + table # self._table_columns is set up in _save() to speed up initialization self._table_columns = []
[ "def", "__init__", "(", "self", ",", "database", ":", "str", ",", "table", ":", "str", ",", "write_mode", ":", "str", ",", "table_pk", ":", "List", "[", "str", "]", "=", "None", ")", "->", "None", ":", "valid_write_modes", "=", "[", "\"insert\"", ","...
https://github.com/kedro-org/kedro/blob/e78990c6b606a27830f0d502afa0f639c0830950/kedro/extras/datasets/spark/spark_hive_dataset.py#L108-L140
Yubico/yubikey-manager
32914673d1d0004aba820e614ac9a9a640b4d196
yubikit/yubiotp.py
python
HotpSlotConfiguration.__init__
(self, key: bytes)
[]
def __init__(self, key: bytes): super(HotpSlotConfiguration, self).__init__() key = _shorten_hmac_key(key) # Key is packed into key and uid self._key = key[:KEY_SIZE].ljust(KEY_SIZE, b"\0") self._uid = key[KEY_SIZE:].ljust(UID_SIZE, b"\0") self._update_flags(TKTFLAG.OATH_HOTP, True) self._update_flags(CFGFLAG.OATH_FIXED_MODHEX2, True)
[ "def", "__init__", "(", "self", ",", "key", ":", "bytes", ")", ":", "super", "(", "HotpSlotConfiguration", ",", "self", ")", ".", "__init__", "(", ")", "key", "=", "_shorten_hmac_key", "(", "key", ")", "# Key is packed into key and uid", "self", ".", "_key",...
https://github.com/Yubico/yubikey-manager/blob/32914673d1d0004aba820e614ac9a9a640b4d196/yubikit/yubiotp.py#L417-L427
leapcode/bitmask_client
d2fe20df24fc6eaf146fa5ce1e847de6ab515688
src/leap/bitmask/services/eip/eipconfig.py
python
EIPConfig.get_gateway_ip
(self, index=0)
Returns the ip of the gateway. :rtype: An IPv4Address or IPv6Address object.
Returns the ip of the gateway.
[ "Returns", "the", "ip", "of", "the", "gateway", "." ]
def get_gateway_ip(self, index=0): """ Returns the ip of the gateway. :rtype: An IPv4Address or IPv6Address object. """ gateways = self.get_gateways() leap_assert(len(gateways) > 0, "We don't have any gateway!") if index > len(gateways): index = 0 logger.warning("Provided an unknown gateway index %s, " + "defaulting to 0") ip_addr_str = gateways[index]["ip_address"] try: ipaddr.IPAddress(ip_addr_str) return ip_addr_str except ValueError: logger.error("Invalid ip address in config: %s" % (ip_addr_str,)) return None
[ "def", "get_gateway_ip", "(", "self", ",", "index", "=", "0", ")", ":", "gateways", "=", "self", ".", "get_gateways", "(", ")", "leap_assert", "(", "len", "(", "gateways", ")", ">", "0", ",", "\"We don't have any gateway!\"", ")", "if", "index", ">", "le...
https://github.com/leapcode/bitmask_client/blob/d2fe20df24fc6eaf146fa5ce1e847de6ab515688/src/leap/bitmask/services/eip/eipconfig.py#L290-L309
nephila/djangocms-blog
d18382808766548c0ec1b9f0dabe443d5430aebf
djangocms_blog/media/base.py
python
MediaAttachmentPluginMixin.get_thumb_image
(self)
return self._media_autoconfiguration["thumb_url"] % self.media_params
URL of the media cover at intermediate resolution :rtype: str
URL of the media cover at intermediate resolution
[ "URL", "of", "the", "media", "cover", "at", "intermediate", "resolution" ]
def get_thumb_image(self): """ URL of the media cover at intermediate resolution :rtype: str """ return self._media_autoconfiguration["thumb_url"] % self.media_params
[ "def", "get_thumb_image", "(", "self", ")", ":", "return", "self", ".", "_media_autoconfiguration", "[", "\"thumb_url\"", "]", "%", "self", ".", "media_params" ]
https://github.com/nephila/djangocms-blog/blob/d18382808766548c0ec1b9f0dabe443d5430aebf/djangocms_blog/media/base.py#L103-L109
JaniceWuo/MovieRecommend
4c86db64ca45598917d304f535413df3bc9fea65
movierecommend/venv1/Lib/site-packages/django/contrib/gis/db/models/query.py
python
GeoQuerySet._geocol_select
(self, geo_field, field_name)
Helper routine for constructing the SQL to select the geographic column. Takes into account if the geographic field is in a ForeignKey relation to the current model.
Helper routine for constructing the SQL to select the geographic column. Takes into account if the geographic field is in a ForeignKey relation to the current model.
[ "Helper", "routine", "for", "constructing", "the", "SQL", "to", "select", "the", "geographic", "column", ".", "Takes", "into", "account", "if", "the", "geographic", "field", "is", "in", "a", "ForeignKey", "relation", "to", "the", "current", "model", "." ]
def _geocol_select(self, geo_field, field_name): """ Helper routine for constructing the SQL to select the geographic column. Takes into account if the geographic field is in a ForeignKey relation to the current model. """ compiler = self.query.get_compiler(self.db) opts = self.model._meta if geo_field not in opts.fields: # Is this operation going to be on a related geographic field? # If so, it'll have to be added to the select related information # (e.g., if 'location__point' was given as the field name, then # chop the non-relational field and add select_related('location')). # Note: the operation really is defined as "must add select related!" self.query.add_select_related([field_name.rsplit(LOOKUP_SEP, 1)[0]]) # Call pre_sql_setup() so that compiler.select gets populated. compiler.pre_sql_setup() for col, _, _ in compiler.select: if col.output_field == geo_field: return col.as_sql(compiler, compiler.connection)[0] raise ValueError("%r not in compiler's related_select_cols" % geo_field) elif geo_field not in opts.local_fields: # This geographic field is inherited from another model, so we have to # use the db table for the _parent_ model instead. parent_model = geo_field.model._meta.concrete_model return self._field_column(compiler, geo_field, parent_model._meta.db_table) else: return self._field_column(compiler, geo_field)
[ "def", "_geocol_select", "(", "self", ",", "geo_field", ",", "field_name", ")", ":", "compiler", "=", "self", ".", "query", ".", "get_compiler", "(", "self", ".", "db", ")", "opts", "=", "self", ".", "model", ".", "_meta", "if", "geo_field", "not", "in...
https://github.com/JaniceWuo/MovieRecommend/blob/4c86db64ca45598917d304f535413df3bc9fea65/movierecommend/venv1/Lib/site-packages/django/contrib/gis/db/models/query.py#L667-L694
openstack/taskflow
38b9011094dbcfdd00e6446393816201e8256d38
taskflow/jobs/backends/impl_zookeeper.py
python
ZookeeperJobBoard._process_child
(self, path, request, quiet=True)
Receives the result of a child data fetch request.
Receives the result of a child data fetch request.
[ "Receives", "the", "result", "of", "a", "child", "data", "fetch", "request", "." ]
def _process_child(self, path, request, quiet=True): """Receives the result of a child data fetch request.""" job = None try: raw_data, node_stat = request.get() job_data = misc.decode_json(raw_data) job_created_on = misc.millis_to_datetime(node_stat.ctime) try: job_priority = job_data['priority'] job_priority = base.JobPriority.convert(job_priority) except KeyError: job_priority = base.JobPriority.NORMAL job_uuid = job_data['uuid'] job_name = job_data['name'] except (ValueError, TypeError, KeyError): with excutils.save_and_reraise_exception(reraise=not quiet): LOG.warning("Incorrectly formatted job data found at path: %s", path, exc_info=True) except self._client.handler.timeout_exception: with excutils.save_and_reraise_exception(reraise=not quiet): LOG.warning("Operation timed out fetching job data from" " from path: %s", path, exc_info=True) except k_exceptions.SessionExpiredError: with excutils.save_and_reraise_exception(reraise=not quiet): LOG.warning("Session expired fetching job data from path: %s", path, exc_info=True) except k_exceptions.NoNodeError: LOG.debug("No job node found at path: %s, it must have" " disappeared or was removed", path) except k_exceptions.KazooException: with excutils.save_and_reraise_exception(reraise=not quiet): LOG.warning("Internal error fetching job data from path: %s", path, exc_info=True) else: with self._job_cond: # Now we can officially check if someone already placed this # jobs information into the known job set (if it's already # existing then just leave it alone). if path not in self._known_jobs: job = ZookeeperJob(self, job_name, self._client, path, backend=self._persistence, uuid=job_uuid, book_data=job_data.get("book"), details=job_data.get("details", {}), created_on=job_created_on, priority=job_priority) self._known_jobs[path] = job self._job_cond.notify_all() if job is not None: self._try_emit(base.POSTED, details={'job': job})
[ "def", "_process_child", "(", "self", ",", "path", ",", "request", ",", "quiet", "=", "True", ")", ":", "job", "=", "None", "try", ":", "raw_data", ",", "node_stat", "=", "request", ".", "get", "(", ")", "job_data", "=", "misc", ".", "decode_json", "...
https://github.com/openstack/taskflow/blob/38b9011094dbcfdd00e6446393816201e8256d38/taskflow/jobs/backends/impl_zookeeper.py#L413-L464
kuri65536/python-for-android
26402a08fc46b09ef94e8d7a6bbc3a54ff9d0891
python-modules/twisted/twisted/python/dist.py
python
getVersion
(proj, base="twisted")
return ns['version'].base()
Extract the version number for a given project. @param proj: the name of the project. Examples are "core", "conch", "words", "mail". @rtype: str @returns: The version number of the project, as a string like "2.0.0".
Extract the version number for a given project.
[ "Extract", "the", "version", "number", "for", "a", "given", "project", "." ]
def getVersion(proj, base="twisted"): """ Extract the version number for a given project. @param proj: the name of the project. Examples are "core", "conch", "words", "mail". @rtype: str @returns: The version number of the project, as a string like "2.0.0". """ if proj == 'core': vfile = os.path.join(base, '_version.py') else: vfile = os.path.join(base, proj, '_version.py') ns = {'__name__': 'Nothing to see here'} execfile(vfile, ns) return ns['version'].base()
[ "def", "getVersion", "(", "proj", ",", "base", "=", "\"twisted\"", ")", ":", "if", "proj", "==", "'core'", ":", "vfile", "=", "os", ".", "path", ".", "join", "(", "base", ",", "'_version.py'", ")", "else", ":", "vfile", "=", "os", ".", "path", ".",...
https://github.com/kuri65536/python-for-android/blob/26402a08fc46b09ef94e8d7a6bbc3a54ff9d0891/python-modules/twisted/twisted/python/dist.py#L103-L120
hhyo/Archery
c9b057d37e47894ca8531e5cd10afdb064cd0122
sql/engines/models.py
python
ReviewResult.__init__
(self, inception_result=None, **kwargs)
inception的结果列 = ['ID', 'stage', 'errlevel', 'stagestatus', 'errormessage', 'SQL', 'Affected_rows', 'sequence','backup_dbname', 'execute_time', 'sqlsha1'] go_inception的结果列 = ['order_id', 'stage', 'error_level', 'stage_status', 'error_message', 'sql', 'affected_rows', 'sequence', 'backup_dbname', 'execute_time', 'sqlsha1', 'backup_time']
inception的结果列 = ['ID', 'stage', 'errlevel', 'stagestatus', 'errormessage', 'SQL', 'Affected_rows', 'sequence','backup_dbname', 'execute_time', 'sqlsha1'] go_inception的结果列 = ['order_id', 'stage', 'error_level', 'stage_status', 'error_message', 'sql', 'affected_rows', 'sequence', 'backup_dbname', 'execute_time', 'sqlsha1', 'backup_time']
[ "inception的结果列", "=", "[", "ID", "stage", "errlevel", "stagestatus", "errormessage", "SQL", "Affected_rows", "sequence", "backup_dbname", "execute_time", "sqlsha1", "]", "go_inception的结果列", "=", "[", "order_id", "stage", "error_level", "stage_status", "error_message", "...
def __init__(self, inception_result=None, **kwargs): """ inception的结果列 = ['ID', 'stage', 'errlevel', 'stagestatus', 'errormessage', 'SQL', 'Affected_rows', 'sequence','backup_dbname', 'execute_time', 'sqlsha1'] go_inception的结果列 = ['order_id', 'stage', 'error_level', 'stage_status', 'error_message', 'sql', 'affected_rows', 'sequence', 'backup_dbname', 'execute_time', 'sqlsha1', 'backup_time'] """ if inception_result: self.id = inception_result[0] or 0 self.stage = inception_result[1] or '' self.errlevel = inception_result[2] or 0 self.stagestatus = inception_result[3] or '' self.errormessage = inception_result[4] or '' self.sql = inception_result[5] or '' self.affected_rows = inception_result[6] or 0 self.sequence = inception_result[7] or '' self.backup_dbname = inception_result[8] or '' self.execute_time = inception_result[9] or '' self.sqlsha1 = inception_result[10] or '' self.backup_time = inception_result[11] if len(inception_result) >= 12 else '' self.actual_affected_rows = '' else: self.id = kwargs.get('id', 0) self.stage = kwargs.get('stage', '') self.errlevel = kwargs.get('errlevel', 0) self.stagestatus = kwargs.get('stagestatus', '') self.errormessage = kwargs.get('errormessage', '') self.sql = kwargs.get('sql', '') self.affected_rows = kwargs.get('affected_rows', 0) self.sequence = kwargs.get('sequence', '') self.backup_dbname = kwargs.get('backup_dbname', '') self.execute_time = kwargs.get('execute_time', '') self.sqlsha1 = kwargs.get('sqlsha1', '') self.backup_time = kwargs.get('backup_time', '') self.actual_affected_rows = kwargs.get('actual_affected_rows', '') # 自定义属性 for key, value in kwargs.items(): if not hasattr(self, key): setattr(self, key, value)
[ "def", "__init__", "(", "self", ",", "inception_result", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "inception_result", ":", "self", ".", "id", "=", "inception_result", "[", "0", "]", "or", "0", "self", ".", "stage", "=", "inception_result", ...
https://github.com/hhyo/Archery/blob/c9b057d37e47894ca8531e5cd10afdb064cd0122/sql/engines/models.py#L28-L67
andrewekhalel/edafa
122da335fa3aada1e4df6b9bc88411f544a23c22
examples/tensorflow/slim/nets/inception_v3.py
python
inception_v3_base
(inputs, final_endpoint='Mixed_7c', min_depth=16, depth_multiplier=1.0, scope=None)
Inception model from http://arxiv.org/abs/1512.00567. Constructs an Inception v3 network from inputs to the given final endpoint. This method can construct the network up to the final inception block Mixed_7c. Note that the names of the layers in the paper do not correspond to the names of the endpoints registered by this function although they build the same network. Here is a mapping from the old_names to the new names: Old name | New name ======================================= conv0 | Conv2d_1a_3x3 conv1 | Conv2d_2a_3x3 conv2 | Conv2d_2b_3x3 pool1 | MaxPool_3a_3x3 conv3 | Conv2d_3b_1x1 conv4 | Conv2d_4a_3x3 pool2 | MaxPool_5a_3x3 mixed_35x35x256a | Mixed_5b mixed_35x35x288a | Mixed_5c mixed_35x35x288b | Mixed_5d mixed_17x17x768a | Mixed_6a mixed_17x17x768b | Mixed_6b mixed_17x17x768c | Mixed_6c mixed_17x17x768d | Mixed_6d mixed_17x17x768e | Mixed_6e mixed_8x8x1280a | Mixed_7a mixed_8x8x2048a | Mixed_7b mixed_8x8x2048b | Mixed_7c Args: inputs: a tensor of size [batch_size, height, width, channels]. final_endpoint: specifies the endpoint to construct the network up to. It can be one of ['Conv2d_1a_3x3', 'Conv2d_2a_3x3', 'Conv2d_2b_3x3', 'MaxPool_3a_3x3', 'Conv2d_3b_1x1', 'Conv2d_4a_3x3', 'MaxPool_5a_3x3', 'Mixed_5b', 'Mixed_5c', 'Mixed_5d', 'Mixed_6a', 'Mixed_6b', 'Mixed_6c', 'Mixed_6d', 'Mixed_6e', 'Mixed_7a', 'Mixed_7b', 'Mixed_7c']. min_depth: Minimum depth value (number of channels) for all convolution ops. Enforced when depth_multiplier < 1, and not an active constraint when depth_multiplier >= 1. depth_multiplier: Float multiplier for the depth (number of channels) for all convolution ops. The value must be greater than zero. Typical usage will be to set this value in (0, 1) to reduce the number of parameters or computation cost of the model. scope: Optional variable_scope. Returns: tensor_out: output tensor corresponding to the final_endpoint. end_points: a set of activations for external use, for example summaries or losses. Raises: ValueError: if final_endpoint is not set to one of the predefined values, or depth_multiplier <= 0
Inception model from http://arxiv.org/abs/1512.00567.
[ "Inception", "model", "from", "http", ":", "//", "arxiv", ".", "org", "/", "abs", "/", "1512", ".", "00567", "." ]
def inception_v3_base(inputs, final_endpoint='Mixed_7c', min_depth=16, depth_multiplier=1.0, scope=None): """Inception model from http://arxiv.org/abs/1512.00567. Constructs an Inception v3 network from inputs to the given final endpoint. This method can construct the network up to the final inception block Mixed_7c. Note that the names of the layers in the paper do not correspond to the names of the endpoints registered by this function although they build the same network. Here is a mapping from the old_names to the new names: Old name | New name ======================================= conv0 | Conv2d_1a_3x3 conv1 | Conv2d_2a_3x3 conv2 | Conv2d_2b_3x3 pool1 | MaxPool_3a_3x3 conv3 | Conv2d_3b_1x1 conv4 | Conv2d_4a_3x3 pool2 | MaxPool_5a_3x3 mixed_35x35x256a | Mixed_5b mixed_35x35x288a | Mixed_5c mixed_35x35x288b | Mixed_5d mixed_17x17x768a | Mixed_6a mixed_17x17x768b | Mixed_6b mixed_17x17x768c | Mixed_6c mixed_17x17x768d | Mixed_6d mixed_17x17x768e | Mixed_6e mixed_8x8x1280a | Mixed_7a mixed_8x8x2048a | Mixed_7b mixed_8x8x2048b | Mixed_7c Args: inputs: a tensor of size [batch_size, height, width, channels]. final_endpoint: specifies the endpoint to construct the network up to. It can be one of ['Conv2d_1a_3x3', 'Conv2d_2a_3x3', 'Conv2d_2b_3x3', 'MaxPool_3a_3x3', 'Conv2d_3b_1x1', 'Conv2d_4a_3x3', 'MaxPool_5a_3x3', 'Mixed_5b', 'Mixed_5c', 'Mixed_5d', 'Mixed_6a', 'Mixed_6b', 'Mixed_6c', 'Mixed_6d', 'Mixed_6e', 'Mixed_7a', 'Mixed_7b', 'Mixed_7c']. min_depth: Minimum depth value (number of channels) for all convolution ops. Enforced when depth_multiplier < 1, and not an active constraint when depth_multiplier >= 1. depth_multiplier: Float multiplier for the depth (number of channels) for all convolution ops. The value must be greater than zero. Typical usage will be to set this value in (0, 1) to reduce the number of parameters or computation cost of the model. scope: Optional variable_scope. Returns: tensor_out: output tensor corresponding to the final_endpoint. end_points: a set of activations for external use, for example summaries or losses. Raises: ValueError: if final_endpoint is not set to one of the predefined values, or depth_multiplier <= 0 """ # end_points will collect relevant activations for external use, for example # summaries or losses. end_points = {} if depth_multiplier <= 0: raise ValueError('depth_multiplier is not greater than zero.') depth = lambda d: max(int(d * depth_multiplier), min_depth) with tf.variable_scope(scope, 'InceptionV3', [inputs]): with slim.arg_scope([slim.conv2d, slim.max_pool2d, slim.avg_pool2d], stride=1, padding='VALID'): # 299 x 299 x 3 end_point = 'Conv2d_1a_3x3' net = slim.conv2d(inputs, depth(32), [3, 3], stride=2, scope=end_point) end_points[end_point] = net if end_point == final_endpoint: return net, end_points # 149 x 149 x 32 end_point = 'Conv2d_2a_3x3' net = slim.conv2d(net, depth(32), [3, 3], scope=end_point) end_points[end_point] = net if end_point == final_endpoint: return net, end_points # 147 x 147 x 32 end_point = 'Conv2d_2b_3x3' net = slim.conv2d(net, depth(64), [3, 3], padding='SAME', scope=end_point) end_points[end_point] = net if end_point == final_endpoint: return net, end_points # 147 x 147 x 64 end_point = 'MaxPool_3a_3x3' net = slim.max_pool2d(net, [3, 3], stride=2, scope=end_point) end_points[end_point] = net if end_point == final_endpoint: return net, end_points # 73 x 73 x 64 end_point = 'Conv2d_3b_1x1' net = slim.conv2d(net, depth(80), [1, 1], scope=end_point) end_points[end_point] = net if end_point == final_endpoint: return net, end_points # 73 x 73 x 80. end_point = 'Conv2d_4a_3x3' net = slim.conv2d(net, depth(192), [3, 3], scope=end_point) end_points[end_point] = net if end_point == final_endpoint: return net, end_points # 71 x 71 x 192. end_point = 'MaxPool_5a_3x3' net = slim.max_pool2d(net, [3, 3], stride=2, scope=end_point) end_points[end_point] = net if end_point == final_endpoint: return net, end_points # 35 x 35 x 192. # Inception blocks with slim.arg_scope([slim.conv2d, slim.max_pool2d, slim.avg_pool2d], stride=1, padding='SAME'): # mixed: 35 x 35 x 256. end_point = 'Mixed_5b' with tf.variable_scope(end_point): with tf.variable_scope('Branch_0'): branch_0 = slim.conv2d(net, depth(64), [1, 1], scope='Conv2d_0a_1x1') with tf.variable_scope('Branch_1'): branch_1 = slim.conv2d(net, depth(48), [1, 1], scope='Conv2d_0a_1x1') branch_1 = slim.conv2d(branch_1, depth(64), [5, 5], scope='Conv2d_0b_5x5') with tf.variable_scope('Branch_2'): branch_2 = slim.conv2d(net, depth(64), [1, 1], scope='Conv2d_0a_1x1') branch_2 = slim.conv2d(branch_2, depth(96), [3, 3], scope='Conv2d_0b_3x3') branch_2 = slim.conv2d(branch_2, depth(96), [3, 3], scope='Conv2d_0c_3x3') with tf.variable_scope('Branch_3'): branch_3 = slim.avg_pool2d(net, [3, 3], scope='AvgPool_0a_3x3') branch_3 = slim.conv2d(branch_3, depth(32), [1, 1], scope='Conv2d_0b_1x1') net = tf.concat(axis=3, values=[branch_0, branch_1, branch_2, branch_3]) end_points[end_point] = net if end_point == final_endpoint: return net, end_points # mixed_1: 35 x 35 x 288. end_point = 'Mixed_5c' with tf.variable_scope(end_point): with tf.variable_scope('Branch_0'): branch_0 = slim.conv2d(net, depth(64), [1, 1], scope='Conv2d_0a_1x1') with tf.variable_scope('Branch_1'): branch_1 = slim.conv2d(net, depth(48), [1, 1], scope='Conv2d_0b_1x1') branch_1 = slim.conv2d(branch_1, depth(64), [5, 5], scope='Conv_1_0c_5x5') with tf.variable_scope('Branch_2'): branch_2 = slim.conv2d(net, depth(64), [1, 1], scope='Conv2d_0a_1x1') branch_2 = slim.conv2d(branch_2, depth(96), [3, 3], scope='Conv2d_0b_3x3') branch_2 = slim.conv2d(branch_2, depth(96), [3, 3], scope='Conv2d_0c_3x3') with tf.variable_scope('Branch_3'): branch_3 = slim.avg_pool2d(net, [3, 3], scope='AvgPool_0a_3x3') branch_3 = slim.conv2d(branch_3, depth(64), [1, 1], scope='Conv2d_0b_1x1') net = tf.concat(axis=3, values=[branch_0, branch_1, branch_2, branch_3]) end_points[end_point] = net if end_point == final_endpoint: return net, end_points # mixed_2: 35 x 35 x 288. end_point = 'Mixed_5d' with tf.variable_scope(end_point): with tf.variable_scope('Branch_0'): branch_0 = slim.conv2d(net, depth(64), [1, 1], scope='Conv2d_0a_1x1') with tf.variable_scope('Branch_1'): branch_1 = slim.conv2d(net, depth(48), [1, 1], scope='Conv2d_0a_1x1') branch_1 = slim.conv2d(branch_1, depth(64), [5, 5], scope='Conv2d_0b_5x5') with tf.variable_scope('Branch_2'): branch_2 = slim.conv2d(net, depth(64), [1, 1], scope='Conv2d_0a_1x1') branch_2 = slim.conv2d(branch_2, depth(96), [3, 3], scope='Conv2d_0b_3x3') branch_2 = slim.conv2d(branch_2, depth(96), [3, 3], scope='Conv2d_0c_3x3') with tf.variable_scope('Branch_3'): branch_3 = slim.avg_pool2d(net, [3, 3], scope='AvgPool_0a_3x3') branch_3 = slim.conv2d(branch_3, depth(64), [1, 1], scope='Conv2d_0b_1x1') net = tf.concat(axis=3, values=[branch_0, branch_1, branch_2, branch_3]) end_points[end_point] = net if end_point == final_endpoint: return net, end_points # mixed_3: 17 x 17 x 768. end_point = 'Mixed_6a' with tf.variable_scope(end_point): with tf.variable_scope('Branch_0'): branch_0 = slim.conv2d(net, depth(384), [3, 3], stride=2, padding='VALID', scope='Conv2d_1a_1x1') with tf.variable_scope('Branch_1'): branch_1 = slim.conv2d(net, depth(64), [1, 1], scope='Conv2d_0a_1x1') branch_1 = slim.conv2d(branch_1, depth(96), [3, 3], scope='Conv2d_0b_3x3') branch_1 = slim.conv2d(branch_1, depth(96), [3, 3], stride=2, padding='VALID', scope='Conv2d_1a_1x1') with tf.variable_scope('Branch_2'): branch_2 = slim.max_pool2d(net, [3, 3], stride=2, padding='VALID', scope='MaxPool_1a_3x3') net = tf.concat(axis=3, values=[branch_0, branch_1, branch_2]) end_points[end_point] = net if end_point == final_endpoint: return net, end_points # mixed4: 17 x 17 x 768. end_point = 'Mixed_6b' with tf.variable_scope(end_point): with tf.variable_scope('Branch_0'): branch_0 = slim.conv2d(net, depth(192), [1, 1], scope='Conv2d_0a_1x1') with tf.variable_scope('Branch_1'): branch_1 = slim.conv2d(net, depth(128), [1, 1], scope='Conv2d_0a_1x1') branch_1 = slim.conv2d(branch_1, depth(128), [1, 7], scope='Conv2d_0b_1x7') branch_1 = slim.conv2d(branch_1, depth(192), [7, 1], scope='Conv2d_0c_7x1') with tf.variable_scope('Branch_2'): branch_2 = slim.conv2d(net, depth(128), [1, 1], scope='Conv2d_0a_1x1') branch_2 = slim.conv2d(branch_2, depth(128), [7, 1], scope='Conv2d_0b_7x1') branch_2 = slim.conv2d(branch_2, depth(128), [1, 7], scope='Conv2d_0c_1x7') branch_2 = slim.conv2d(branch_2, depth(128), [7, 1], scope='Conv2d_0d_7x1') branch_2 = slim.conv2d(branch_2, depth(192), [1, 7], scope='Conv2d_0e_1x7') with tf.variable_scope('Branch_3'): branch_3 = slim.avg_pool2d(net, [3, 3], scope='AvgPool_0a_3x3') branch_3 = slim.conv2d(branch_3, depth(192), [1, 1], scope='Conv2d_0b_1x1') net = tf.concat(axis=3, values=[branch_0, branch_1, branch_2, branch_3]) end_points[end_point] = net if end_point == final_endpoint: return net, end_points # mixed_5: 17 x 17 x 768. end_point = 'Mixed_6c' with tf.variable_scope(end_point): with tf.variable_scope('Branch_0'): branch_0 = slim.conv2d(net, depth(192), [1, 1], scope='Conv2d_0a_1x1') with tf.variable_scope('Branch_1'): branch_1 = slim.conv2d(net, depth(160), [1, 1], scope='Conv2d_0a_1x1') branch_1 = slim.conv2d(branch_1, depth(160), [1, 7], scope='Conv2d_0b_1x7') branch_1 = slim.conv2d(branch_1, depth(192), [7, 1], scope='Conv2d_0c_7x1') with tf.variable_scope('Branch_2'): branch_2 = slim.conv2d(net, depth(160), [1, 1], scope='Conv2d_0a_1x1') branch_2 = slim.conv2d(branch_2, depth(160), [7, 1], scope='Conv2d_0b_7x1') branch_2 = slim.conv2d(branch_2, depth(160), [1, 7], scope='Conv2d_0c_1x7') branch_2 = slim.conv2d(branch_2, depth(160), [7, 1], scope='Conv2d_0d_7x1') branch_2 = slim.conv2d(branch_2, depth(192), [1, 7], scope='Conv2d_0e_1x7') with tf.variable_scope('Branch_3'): branch_3 = slim.avg_pool2d(net, [3, 3], scope='AvgPool_0a_3x3') branch_3 = slim.conv2d(branch_3, depth(192), [1, 1], scope='Conv2d_0b_1x1') net = tf.concat(axis=3, values=[branch_0, branch_1, branch_2, branch_3]) end_points[end_point] = net if end_point == final_endpoint: return net, end_points # mixed_6: 17 x 17 x 768. end_point = 'Mixed_6d' with tf.variable_scope(end_point): with tf.variable_scope('Branch_0'): branch_0 = slim.conv2d(net, depth(192), [1, 1], scope='Conv2d_0a_1x1') with tf.variable_scope('Branch_1'): branch_1 = slim.conv2d(net, depth(160), [1, 1], scope='Conv2d_0a_1x1') branch_1 = slim.conv2d(branch_1, depth(160), [1, 7], scope='Conv2d_0b_1x7') branch_1 = slim.conv2d(branch_1, depth(192), [7, 1], scope='Conv2d_0c_7x1') with tf.variable_scope('Branch_2'): branch_2 = slim.conv2d(net, depth(160), [1, 1], scope='Conv2d_0a_1x1') branch_2 = slim.conv2d(branch_2, depth(160), [7, 1], scope='Conv2d_0b_7x1') branch_2 = slim.conv2d(branch_2, depth(160), [1, 7], scope='Conv2d_0c_1x7') branch_2 = slim.conv2d(branch_2, depth(160), [7, 1], scope='Conv2d_0d_7x1') branch_2 = slim.conv2d(branch_2, depth(192), [1, 7], scope='Conv2d_0e_1x7') with tf.variable_scope('Branch_3'): branch_3 = slim.avg_pool2d(net, [3, 3], scope='AvgPool_0a_3x3') branch_3 = slim.conv2d(branch_3, depth(192), [1, 1], scope='Conv2d_0b_1x1') net = tf.concat(axis=3, values=[branch_0, branch_1, branch_2, branch_3]) end_points[end_point] = net if end_point == final_endpoint: return net, end_points # mixed_7: 17 x 17 x 768. end_point = 'Mixed_6e' with tf.variable_scope(end_point): with tf.variable_scope('Branch_0'): branch_0 = slim.conv2d(net, depth(192), [1, 1], scope='Conv2d_0a_1x1') with tf.variable_scope('Branch_1'): branch_1 = slim.conv2d(net, depth(192), [1, 1], scope='Conv2d_0a_1x1') branch_1 = slim.conv2d(branch_1, depth(192), [1, 7], scope='Conv2d_0b_1x7') branch_1 = slim.conv2d(branch_1, depth(192), [7, 1], scope='Conv2d_0c_7x1') with tf.variable_scope('Branch_2'): branch_2 = slim.conv2d(net, depth(192), [1, 1], scope='Conv2d_0a_1x1') branch_2 = slim.conv2d(branch_2, depth(192), [7, 1], scope='Conv2d_0b_7x1') branch_2 = slim.conv2d(branch_2, depth(192), [1, 7], scope='Conv2d_0c_1x7') branch_2 = slim.conv2d(branch_2, depth(192), [7, 1], scope='Conv2d_0d_7x1') branch_2 = slim.conv2d(branch_2, depth(192), [1, 7], scope='Conv2d_0e_1x7') with tf.variable_scope('Branch_3'): branch_3 = slim.avg_pool2d(net, [3, 3], scope='AvgPool_0a_3x3') branch_3 = slim.conv2d(branch_3, depth(192), [1, 1], scope='Conv2d_0b_1x1') net = tf.concat(axis=3, values=[branch_0, branch_1, branch_2, branch_3]) end_points[end_point] = net if end_point == final_endpoint: return net, end_points # mixed_8: 8 x 8 x 1280. end_point = 'Mixed_7a' with tf.variable_scope(end_point): with tf.variable_scope('Branch_0'): branch_0 = slim.conv2d(net, depth(192), [1, 1], scope='Conv2d_0a_1x1') branch_0 = slim.conv2d(branch_0, depth(320), [3, 3], stride=2, padding='VALID', scope='Conv2d_1a_3x3') with tf.variable_scope('Branch_1'): branch_1 = slim.conv2d(net, depth(192), [1, 1], scope='Conv2d_0a_1x1') branch_1 = slim.conv2d(branch_1, depth(192), [1, 7], scope='Conv2d_0b_1x7') branch_1 = slim.conv2d(branch_1, depth(192), [7, 1], scope='Conv2d_0c_7x1') branch_1 = slim.conv2d(branch_1, depth(192), [3, 3], stride=2, padding='VALID', scope='Conv2d_1a_3x3') with tf.variable_scope('Branch_2'): branch_2 = slim.max_pool2d(net, [3, 3], stride=2, padding='VALID', scope='MaxPool_1a_3x3') net = tf.concat(axis=3, values=[branch_0, branch_1, branch_2]) end_points[end_point] = net if end_point == final_endpoint: return net, end_points # mixed_9: 8 x 8 x 2048. end_point = 'Mixed_7b' with tf.variable_scope(end_point): with tf.variable_scope('Branch_0'): branch_0 = slim.conv2d(net, depth(320), [1, 1], scope='Conv2d_0a_1x1') with tf.variable_scope('Branch_1'): branch_1 = slim.conv2d(net, depth(384), [1, 1], scope='Conv2d_0a_1x1') branch_1 = tf.concat(axis=3, values=[ slim.conv2d(branch_1, depth(384), [1, 3], scope='Conv2d_0b_1x3'), slim.conv2d(branch_1, depth(384), [3, 1], scope='Conv2d_0b_3x1')]) with tf.variable_scope('Branch_2'): branch_2 = slim.conv2d(net, depth(448), [1, 1], scope='Conv2d_0a_1x1') branch_2 = slim.conv2d( branch_2, depth(384), [3, 3], scope='Conv2d_0b_3x3') branch_2 = tf.concat(axis=3, values=[ slim.conv2d(branch_2, depth(384), [1, 3], scope='Conv2d_0c_1x3'), slim.conv2d(branch_2, depth(384), [3, 1], scope='Conv2d_0d_3x1')]) with tf.variable_scope('Branch_3'): branch_3 = slim.avg_pool2d(net, [3, 3], scope='AvgPool_0a_3x3') branch_3 = slim.conv2d( branch_3, depth(192), [1, 1], scope='Conv2d_0b_1x1') net = tf.concat(axis=3, values=[branch_0, branch_1, branch_2, branch_3]) end_points[end_point] = net if end_point == final_endpoint: return net, end_points # mixed_10: 8 x 8 x 2048. end_point = 'Mixed_7c' with tf.variable_scope(end_point): with tf.variable_scope('Branch_0'): branch_0 = slim.conv2d(net, depth(320), [1, 1], scope='Conv2d_0a_1x1') with tf.variable_scope('Branch_1'): branch_1 = slim.conv2d(net, depth(384), [1, 1], scope='Conv2d_0a_1x1') branch_1 = tf.concat(axis=3, values=[ slim.conv2d(branch_1, depth(384), [1, 3], scope='Conv2d_0b_1x3'), slim.conv2d(branch_1, depth(384), [3, 1], scope='Conv2d_0c_3x1')]) with tf.variable_scope('Branch_2'): branch_2 = slim.conv2d(net, depth(448), [1, 1], scope='Conv2d_0a_1x1') branch_2 = slim.conv2d( branch_2, depth(384), [3, 3], scope='Conv2d_0b_3x3') branch_2 = tf.concat(axis=3, values=[ slim.conv2d(branch_2, depth(384), [1, 3], scope='Conv2d_0c_1x3'), slim.conv2d(branch_2, depth(384), [3, 1], scope='Conv2d_0d_3x1')]) with tf.variable_scope('Branch_3'): branch_3 = slim.avg_pool2d(net, [3, 3], scope='AvgPool_0a_3x3') branch_3 = slim.conv2d( branch_3, depth(192), [1, 1], scope='Conv2d_0b_1x1') net = tf.concat(axis=3, values=[branch_0, branch_1, branch_2, branch_3]) end_points[end_point] = net if end_point == final_endpoint: return net, end_points raise ValueError('Unknown final endpoint %s' % final_endpoint)
[ "def", "inception_v3_base", "(", "inputs", ",", "final_endpoint", "=", "'Mixed_7c'", ",", "min_depth", "=", "16", ",", "depth_multiplier", "=", "1.0", ",", "scope", "=", "None", ")", ":", "# end_points will collect relevant activations for external use, for example", "#...
https://github.com/andrewekhalel/edafa/blob/122da335fa3aada1e4df6b9bc88411f544a23c22/examples/tensorflow/slim/nets/inception_v3.py#L29-L416
dropbox/nsot
941b11f84f5c0d210f638654a6ed34a5610af22a
nsot/api/filters.py
python
ProtocolFilter.filter_device
(self, queryset, name, value)
Overload to use natural key.
Overload to use natural key.
[ "Overload", "to", "use", "natural", "key", "." ]
def filter_device(self, queryset, name, value): """Overload to use natural key.""" if isinstance(value, int): value = str(value) if value.isdigit(): return queryset.filter(device=value) else: return queryset.filter(device__hostname=value)
[ "def", "filter_device", "(", "self", ",", "queryset", ",", "name", ",", "value", ")", ":", "if", "isinstance", "(", "value", ",", "int", ")", ":", "value", "=", "str", "(", "value", ")", "if", "value", ".", "isdigit", "(", ")", ":", "return", "quer...
https://github.com/dropbox/nsot/blob/941b11f84f5c0d210f638654a6ed34a5610af22a/nsot/api/filters.py#L204-L212
pyg-team/pytorch_geometric
b920e9a3a64e22c8356be55301c88444ff051cae
torch_geometric/nn/to_hetero_with_bases_transformer.py
python
ToHeteroWithBasesTransformer.__init__
( self, module: Module, metadata: Metadata, num_bases: int, in_channels: Optional[Dict[str, int]] = None, input_map: Optional[Dict[str, str]] = None, debug: bool = False, )
[]
def __init__( self, module: Module, metadata: Metadata, num_bases: int, in_channels: Optional[Dict[str, int]] = None, input_map: Optional[Dict[str, str]] = None, debug: bool = False, ): super().__init__(module, input_map, debug) unused_node_types = get_unused_node_types(*metadata) if len(unused_node_types) > 0: warnings.warn( f"There exist node types ({unused_node_types}) whose " f"representations do not get updated during message passing " f"as they do not occur as destination type in any edge type. " f"This may lead to unexpected behaviour.") self.metadata = metadata self.num_bases = num_bases self.in_channels = in_channels or {} assert len(metadata) == 2 assert len(metadata[0]) > 0 and len(metadata[1]) > 0 # Compute IDs for each node and edge type: self.node_type2id = {k: i for i, k in enumerate(metadata[0])} self.edge_type2id = {k: i for i, k in enumerate(metadata[1])}
[ "def", "__init__", "(", "self", ",", "module", ":", "Module", ",", "metadata", ":", "Metadata", ",", "num_bases", ":", "int", ",", "in_channels", ":", "Optional", "[", "Dict", "[", "str", ",", "int", "]", "]", "=", "None", ",", "input_map", ":", "Opt...
https://github.com/pyg-team/pytorch_geometric/blob/b920e9a3a64e22c8356be55301c88444ff051cae/torch_geometric/nn/to_hetero_with_bases_transformer.py#L138-L165
mesonbuild/meson
a22d0f9a0a787df70ce79b05d0c45de90a970048
mesonbuild/dependencies/hdf5.py
python
HDF5ConfigToolDependency.__init__
(self, name: str, environment: 'Environment', kwargs: T.Dict[str, T.Any], language: T.Optional[str] = None)
[]
def __init__(self, name: str, environment: 'Environment', kwargs: T.Dict[str, T.Any], language: T.Optional[str] = None) -> None: language = language or 'c' if language not in {'c', 'cpp', 'fortran'}: raise DependencyException(f'Language {language} is not supported with HDF5.') if language == 'c': cenv = 'CC' tools = ['h5cc', 'h5pcc'] elif language == 'cpp': cenv = 'CXX' tools = ['h5c++', 'h5pc++'] elif language == 'fortran': cenv = 'FC' tools = ['h5fc', 'h5pfc'] else: raise DependencyException('How did you get here?') # We need this before we call super() for_machine = self.get_for_machine_from_kwargs(kwargs) nkwargs = kwargs.copy() nkwargs['tools'] = tools # Override the compiler that the config tools are going to use by # setting the environment variables that they use for the compiler and # linkers. compiler = environment.coredata.compilers[for_machine][language] try: os.environ[f'HDF5_{cenv}'] = join_args(compiler.get_exelist()) os.environ[f'HDF5_{cenv}LINKER'] = join_args(compiler.get_linker_exelist()) super().__init__(name, environment, nkwargs, language) finally: del os.environ[f'HDF5_{cenv}'] del os.environ[f'HDF5_{cenv}LINKER'] if not self.is_found: return # We first need to call the tool with -c to get the compile arguments # and then without -c to get the link arguments. args = self.get_config_value(['-show', '-c'], 'args')[1:] args += self.get_config_value(['-show', '-noshlib' if kwargs.get('static', False) else '-shlib'], 'args')[1:] for arg in args: if arg.startswith(('-I', '-f', '-D')) or arg == '-pthread': self.compile_args.append(arg) elif arg.startswith(('-L', '-l', '-Wl')): self.link_args.append(arg) elif Path(arg).is_file(): self.link_args.append(arg) # If the language is not C we need to add C as a subdependency if language != 'c': nkwargs = kwargs.copy() nkwargs['language'] = 'c' # I'm being too clever for mypy and pylint self.is_found = self._add_sub_dependency(hdf5_factory(environment, for_machine, nkwargs))
[ "def", "__init__", "(", "self", ",", "name", ":", "str", ",", "environment", ":", "'Environment'", ",", "kwargs", ":", "T", ".", "Dict", "[", "str", ",", "T", ".", "Any", "]", ",", "language", ":", "T", ".", "Optional", "[", "str", "]", "=", "Non...
https://github.com/mesonbuild/meson/blob/a22d0f9a0a787df70ce79b05d0c45de90a970048/mesonbuild/dependencies/hdf5.py#L92-L146
returntocorp/bento
05b365da71b65170d41fe92a702480ab76c1d17c
bento/extra/flake8.py
python
Flake8Tool.select_clause
(self)
return f"--select={RULE_PREFIXES}"
Returns a --select argument to identify which checks flake8 should run
Returns a --select argument to identify which checks flake8 should run
[ "Returns", "a", "--", "select", "argument", "to", "identify", "which", "checks", "flake8", "should", "run" ]
def select_clause(self) -> str: """Returns a --select argument to identify which checks flake8 should run""" return f"--select={RULE_PREFIXES}"
[ "def", "select_clause", "(", "self", ")", "->", "str", ":", "return", "f\"--select={RULE_PREFIXES}\"" ]
https://github.com/returntocorp/bento/blob/05b365da71b65170d41fe92a702480ab76c1d17c/bento/extra/flake8.py#L186-L188
lovelylain/pyctp
fd304de4b50c4ddc31a4190b1caaeb5dec66bc5d
option/ctp/ApiStruct.py
python
InvestorPositionCombineDetail.__init__
(self, TradingDay='', OpenDate='', ExchangeID='', SettlementID=0, BrokerID='', InvestorID='', ComTradeID='', TradeID='', InstrumentID='', HedgeFlag=HF_Speculation, Direction=D_Buy, TotalAmt=0, Margin=0.0, ExchMargin=0.0, MarginRateByMoney=0.0, MarginRateByVolume=0.0, LegID=0, LegMultiple=0, CombInstrumentID='', TradeGroupID=0)
[]
def __init__(self, TradingDay='', OpenDate='', ExchangeID='', SettlementID=0, BrokerID='', InvestorID='', ComTradeID='', TradeID='', InstrumentID='', HedgeFlag=HF_Speculation, Direction=D_Buy, TotalAmt=0, Margin=0.0, ExchMargin=0.0, MarginRateByMoney=0.0, MarginRateByVolume=0.0, LegID=0, LegMultiple=0, CombInstrumentID='', TradeGroupID=0): self.TradingDay = 'Date' #交易日, char[9] self.OpenDate = 'Date' #开仓日期, char[9] self.ExchangeID = '' #交易所代码, char[9] self.SettlementID = '' #结算编号, int self.BrokerID = '' #经纪公司代码, char[11] self.InvestorID = '' #投资者代码, char[13] self.ComTradeID = 'TradeID' #组合编号, char[21] self.TradeID = '' #撮合编号, char[21] self.InstrumentID = '' #合约代码, char[31] self.HedgeFlag = '' #投机套保标志, char self.Direction = '' #买卖, char self.TotalAmt = 'Volume' #持仓量, int self.Margin = 'Money' #投资者保证金, double self.ExchMargin = 'Money' #交易所保证金, double self.MarginRateByMoney = 'Ratio' #保证金率, double self.MarginRateByVolume = 'Ratio' #保证金率(按手数), double self.LegID = '' #单腿编号, int self.LegMultiple = '' #单腿乘数, int self.CombInstrumentID = 'InstrumentID' #组合持仓合约编码, char[31] self.TradeGroupID = ''
[ "def", "__init__", "(", "self", ",", "TradingDay", "=", "''", ",", "OpenDate", "=", "''", ",", "ExchangeID", "=", "''", ",", "SettlementID", "=", "0", ",", "BrokerID", "=", "''", ",", "InvestorID", "=", "''", ",", "ComTradeID", "=", "''", ",", "Trade...
https://github.com/lovelylain/pyctp/blob/fd304de4b50c4ddc31a4190b1caaeb5dec66bc5d/option/ctp/ApiStruct.py#L4891-L4911
pytorch/fairseq
1575f30dd0a9f7b3c499db0b4767aa4e9f79056c
fairseq/trainer.py
python
Trainer.checkpoint_suffix
(self)
Suffix to add to the checkpoint file name.
Suffix to add to the checkpoint file name.
[ "Suffix", "to", "add", "to", "the", "checkpoint", "file", "name", "." ]
def checkpoint_suffix(self) -> str: """Suffix to add to the checkpoint file name.""" if self.is_fsdp and self.cfg.distributed_training.use_sharded_state: return self.cfg.checkpoint.checkpoint_suffix + "-shard{0}".format( self.data_parallel_rank ) else: return self.cfg.checkpoint.checkpoint_suffix or ""
[ "def", "checkpoint_suffix", "(", "self", ")", "->", "str", ":", "if", "self", ".", "is_fsdp", "and", "self", ".", "cfg", ".", "distributed_training", ".", "use_sharded_state", ":", "return", "self", ".", "cfg", ".", "checkpoint", ".", "checkpoint_suffix", "+...
https://github.com/pytorch/fairseq/blob/1575f30dd0a9f7b3c499db0b4767aa4e9f79056c/fairseq/trainer.py#L227-L234
celery/celery
95015a1d5a60d94d8e1e02da4b9cf16416c747e2
celery/_state.py
python
set_default_app
(app)
Set default app.
Set default app.
[ "Set", "default", "app", "." ]
def set_default_app(app): """Set default app.""" global default_app default_app = app
[ "def", "set_default_app", "(", "app", ")", ":", "global", "default_app", "default_app", "=", "app" ]
https://github.com/celery/celery/blob/95015a1d5a60d94d8e1e02da4b9cf16416c747e2/celery/_state.py#L86-L89
jachinlin/geektime_dl
36df91d4d072758da142378d62492c187689b324
geektime_dl/data_client/__init__.py
python
DataClient.get_video_collection_content
(self, collection_id: int, force: bool = False, pbar=True, pbar_desc='')
return data
获取每日一课合辑ID 为 collection_id 的所有视频内容
获取每日一课合辑ID 为 collection_id 的所有视频内容
[ "获取每日一课合辑ID", "为", "collection_id", "的所有视频内容" ]
def get_video_collection_content(self, collection_id: int, force: bool = False, pbar=True, pbar_desc='') -> list: """ 获取每日一课合辑ID 为 collection_id 的所有视频内容 """ data = [] v_ids = self._gk.get_video_list_of(collection_id) if pbar: v_ids = tqdm(v_ids) v_ids.set_description(pbar_desc) for v_id in v_ids: v = self.get_daily_content(v_id['article_id'], force=force) data.append(v) return data
[ "def", "get_video_collection_content", "(", "self", ",", "collection_id", ":", "int", ",", "force", ":", "bool", "=", "False", ",", "pbar", "=", "True", ",", "pbar_desc", "=", "''", ")", "->", "list", ":", "data", "=", "[", "]", "v_ids", "=", "self", ...
https://github.com/jachinlin/geektime_dl/blob/36df91d4d072758da142378d62492c187689b324/geektime_dl/data_client/__init__.py#L128-L142
rytilahti/python-miio
b6e53dd16fac77915426e7592e2528b78ef65190
miio/gateway/radio.py
python
Radio.get_mute
(self)
return self._gateway.send("get_mute")
mute of what?
mute of what?
[ "mute", "of", "what?" ]
def get_mute(self): """mute of what?""" return self._gateway.send("get_mute")
[ "def", "get_mute", "(", "self", ")", ":", "return", "self", ".", "_gateway", ".", "send", "(", "\"get_mute\"", ")" ]
https://github.com/rytilahti/python-miio/blob/b6e53dd16fac77915426e7592e2528b78ef65190/miio/gateway/radio.py#L75-L77
csababarta/ntdsxtract
7fa1c8c28cbbf97a42bef40f20009dba85e4c25f
ntds/dsobjects.py
python
dsSupplCredentials.Print
(self, indent="")
[]
def Print(self, indent=""): if self.KerberosNewerKeys != None: print "{0}Kerberos newer keys".format(indent) self.KerberosNewerKeys.Print(indent + " ") if self.KerberosKeys != None: print "{0}Kerberos keys".format(indent) self.KerberosKeys.Print(indent + " ") if self.WDigestHashes != None: print "{0}WDigest hashes".format(indent) for h in self.WDigestHashes: print "{0} {1}".format(indent, hexlify(h)) if self.Packages != None: print "{0}Packages".format(indent) for p in self.Packages: print "{0} {1}".format(indent, p) if self.Password != None: print "{0}Password: {1}".format(indent, self.Password) print "Debug: " print dump(self.Text,16,16)
[ "def", "Print", "(", "self", ",", "indent", "=", "\"\"", ")", ":", "if", "self", ".", "KerberosNewerKeys", "!=", "None", ":", "print", "\"{0}Kerberos newer keys\"", ".", "format", "(", "indent", ")", "self", ".", "KerberosNewerKeys", ".", "Print", "(", "in...
https://github.com/csababarta/ntdsxtract/blob/7fa1c8c28cbbf97a42bef40f20009dba85e4c25f/ntds/dsobjects.py#L508-L526
BlackLight/platypush
a6b552504e2ac327c94f3a28b607061b6b60cf36
platypush/plugins/ping/__init__.py
python
PingPlugin.__init__
(self, executable: str = 'ping', count: int = 1, timeout: float = 5.0, **kwargs)
:param executable: Path to the ``ping`` executable. Default: the first ``ping`` executable found in PATH. :param count: Default number of packets that should be sent (default: 1). :param timeout: Default timeout before failing a ping request (default: 5 seconds).
:param executable: Path to the ``ping`` executable. Default: the first ``ping`` executable found in PATH. :param count: Default number of packets that should be sent (default: 1). :param timeout: Default timeout before failing a ping request (default: 5 seconds).
[ ":", "param", "executable", ":", "Path", "to", "the", "ping", "executable", ".", "Default", ":", "the", "first", "ping", "executable", "found", "in", "PATH", ".", ":", "param", "count", ":", "Default", "number", "of", "packets", "that", "should", "be", "...
def __init__(self, executable: str = 'ping', count: int = 1, timeout: float = 5.0, **kwargs): """ :param executable: Path to the ``ping`` executable. Default: the first ``ping`` executable found in PATH. :param count: Default number of packets that should be sent (default: 1). :param timeout: Default timeout before failing a ping request (default: 5 seconds). """ super().__init__(**kwargs) self.executable = executable self.count = count self.timeout = timeout
[ "def", "__init__", "(", "self", ",", "executable", ":", "str", "=", "'ping'", ",", "count", ":", "int", "=", "1", ",", "timeout", ":", "float", "=", "5.0", ",", "*", "*", "kwargs", ")", ":", "super", "(", ")", ".", "__init__", "(", "*", "*", "k...
https://github.com/BlackLight/platypush/blob/a6b552504e2ac327c94f3a28b607061b6b60cf36/platypush/plugins/ping/__init__.py#L26-L36
materialsproject/pymatgen
8128f3062a334a2edd240e4062b5b9bdd1ae6f58
pymatgen/io/feff/inputs.py
python
Atoms.cluster
(self)
return self._cluster
Returns the atomic cluster as a Molecule object.
Returns the atomic cluster as a Molecule object.
[ "Returns", "the", "atomic", "cluster", "as", "a", "Molecule", "object", "." ]
def cluster(self): """ Returns the atomic cluster as a Molecule object. """ return self._cluster
[ "def", "cluster", "(", "self", ")", ":", "return", "self", ".", "_cluster" ]
https://github.com/materialsproject/pymatgen/blob/8128f3062a334a2edd240e4062b5b9bdd1ae6f58/pymatgen/io/feff/inputs.py#L417-L421
robotlearn/pyrobolearn
9cd7c060723fda7d2779fa255ac998c2c82b8436
pyrobolearn/models/basics/polynomial.py
python
Polynomial.num_parameters
(self)
return self._num_parameters
Return the total number of parameters
Return the total number of parameters
[ "Return", "the", "total", "number", "of", "parameters" ]
def num_parameters(self): """Return the total number of parameters""" return self._num_parameters
[ "def", "num_parameters", "(", "self", ")", ":", "return", "self", ".", "_num_parameters" ]
https://github.com/robotlearn/pyrobolearn/blob/9cd7c060723fda7d2779fa255ac998c2c82b8436/pyrobolearn/models/basics/polynomial.py#L174-L176
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/Python-2.7.9/Tools/bgen/bgen/scantools.py
python
Scanner.destination
(self, type, name, arglist)
return "FunctionGenerator", "functions"
[]
def destination(self, type, name, arglist): return "FunctionGenerator", "functions"
[ "def", "destination", "(", "self", ",", "type", ",", "name", ",", "arglist", ")", ":", "return", "\"FunctionGenerator\"", ",", "\"functions\"" ]
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/Python-2.7.9/Tools/bgen/bgen/scantools.py#L754-L755
pypa/pipenv
b21baade71a86ab3ee1429f71fbc14d4f95fb75d
pipenv/vendor/distlib/resources.py
python
ZipResourceFinder._is_directory
(self, path)
return result
[]
def _is_directory(self, path): path = path[self.prefix_len:] if path and path[-1] != os.sep: path += os.sep i = bisect.bisect(self.index, path) try: result = self.index[i].startswith(path) except IndexError: result = False return result
[ "def", "_is_directory", "(", "self", ",", "path", ")", ":", "path", "=", "path", "[", "self", ".", "prefix_len", ":", "]", "if", "path", "and", "path", "[", "-", "1", "]", "!=", "os", ".", "sep", ":", "path", "+=", "os", ".", "sep", "i", "=", ...
https://github.com/pypa/pipenv/blob/b21baade71a86ab3ee1429f71fbc14d4f95fb75d/pipenv/vendor/distlib/resources.py#L274-L283
Azure/azure-cli
6c1b085a0910c6c2139006fcbd8ade44006eb6dd
src/azure-cli/azure/cli/command_modules/acs/decorator.py
python
AKSContext.get_load_balancer_outbound_ips
(self)
return load_balancer_outbound_ips
Obtain the value of load_balancer_outbound_ips. Note: SDK performs the following validation {'maximum': 16, 'minimum': 1}. :return: string, list of ResourceReference, or None
Obtain the value of load_balancer_outbound_ips.
[ "Obtain", "the", "value", "of", "load_balancer_outbound_ips", "." ]
def get_load_balancer_outbound_ips(self) -> Union[str, List[ResourceReference], None]: """Obtain the value of load_balancer_outbound_ips. Note: SDK performs the following validation {'maximum': 16, 'minimum': 1}. :return: string, list of ResourceReference, or None """ # read the original value passed by the command load_balancer_outbound_ips = self.raw_param.get( "load_balancer_outbound_ips" ) # In create mode, try to read the property value corresponding to the parameter from the `mc` object. if self.decorator_mode == DecoratorMode.CREATE: if ( self.mc and self.mc.network_profile and self.mc.network_profile.load_balancer_profile and self.mc.network_profile.load_balancer_profile.outbound_i_ps and self.mc.network_profile.load_balancer_profile.outbound_i_ps.public_i_ps is not None ): load_balancer_outbound_ips = ( self.mc.network_profile.load_balancer_profile.outbound_i_ps.public_i_ps ) # this parameter does not need dynamic completion # this parameter does not need validation return load_balancer_outbound_ips
[ "def", "get_load_balancer_outbound_ips", "(", "self", ")", "->", "Union", "[", "str", ",", "List", "[", "ResourceReference", "]", ",", "None", "]", ":", "# read the original value passed by the command", "load_balancer_outbound_ips", "=", "self", ".", "raw_param", "."...
https://github.com/Azure/azure-cli/blob/6c1b085a0910c6c2139006fcbd8ade44006eb6dd/src/azure-cli/azure/cli/command_modules/acs/decorator.py#L2176-L2202
imagr/imagr
e54bcf3f0f951babcd2fa153de2dd8556aa3506d
Imagr/gmacpyutil/macdisk.py
python
Disk.SetStartupDisk
(self)
Sets this disk to be the startup disk.
Sets this disk to be the startup disk.
[ "Sets", "this", "disk", "to", "be", "the", "startup", "disk", "." ]
def SetStartupDisk(self): """Sets this disk to be the startup disk.""" self.Refresh() # pylint: disable=no-member if not self.Mounted(): self.EnsureMountedWithRefresh() command = ["/usr/sbin/bless", "--mount", self.mountpoint, "--setBoot"] rc = gmacpyutil.RunProcess(command)[2] if rc == 0: return True
[ "def", "SetStartupDisk", "(", "self", ")", ":", "self", ".", "Refresh", "(", ")", "# pylint: disable=no-member", "if", "not", "self", ".", "Mounted", "(", ")", ":", "self", ".", "EnsureMountedWithRefresh", "(", ")", "command", "=", "[", "\"/usr/sbin/bless\"", ...
https://github.com/imagr/imagr/blob/e54bcf3f0f951babcd2fa153de2dd8556aa3506d/Imagr/gmacpyutil/macdisk.py#L190-L199
mypaint/mypaint
90b36dbc7b8bd2f323383f7edf608a5e0a3a1a33
lib/observable.py
python
observable.__get__
(self, instance, owner)
return wrapper
Creation of the wrapper callable. The descriptor protocol is used for distinguishing between being accessed by class and being accessed by instance. For the purposes of the decorator interface, we return a callable object, which is cached privately within `instance` so that the callable is associated permanently with the method.
Creation of the wrapper callable.
[ "Creation", "of", "the", "wrapper", "callable", "." ]
def __get__(self, instance, owner): """Creation of the wrapper callable. The descriptor protocol is used for distinguishing between being accessed by class and being accessed by instance. For the purposes of the decorator interface, we return a callable object, which is cached privately within `instance` so that the callable is associated permanently with the method. """ # Return the decorator callable when accessed via the class: normal # descriptor protocol behaviour for instance things. if instance is None: return self # For second and subsequent calls, use a cache stored in the observable # object using this class's name mangling. try: wrappers_dict = instance.__wrappers except AttributeError: wrappers_dict = dict() instance.__wrappers = wrappers_dict wrapper = wrappers_dict.get(self.func) if wrapper is None: wrapper = _MethodWithObservers(instance, self.func) wrappers_dict[self.func] = wrapper elif wrapper.instance_weakref() is not instance: # Okay, change of identity. Happens with the standard copy(). self._update_observers(instance) wrappers_dict = instance.__wrappers old_wrapper = wrapper wrapper = wrappers_dict.get(self.func) assert wrapper is not old_wrapper assert wrapper.instance_weakref() == instance assert callable(wrapper) return wrapper
[ "def", "__get__", "(", "self", ",", "instance", ",", "owner", ")", ":", "# Return the decorator callable when accessed via the class: normal", "# descriptor protocol behaviour for instance things.", "if", "instance", "is", "None", ":", "return", "self", "# For second and subseq...
https://github.com/mypaint/mypaint/blob/90b36dbc7b8bd2f323383f7edf608a5e0a3a1a33/lib/observable.py#L139-L173