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
withdk/badusb2-mitm-poc
db2bfdb1dc9ad371aa665b292183c45577adfbaa
GoodFETMAXUSB.py
python
GoodFETMAXUSBHID.type_IN3
(self)
return
Type next letter in buffer.
Type next letter in buffer.
[ "Type", "next", "letter", "in", "buffer", "." ]
def type_IN3(self): """Type next letter in buffer.""" string=self.typestring(); if self.typepos>=len(string): self.typeletter(0); # Send NoEvent to indicate key-up exit(0); self.typepos=0; # Repeat typestring forever! # This would be a great place to enable a typethrough mode so the host operator can control the target else: if self.usbverbose: sys.stdout.write(string[self.typepos]); sys.stdout.flush(); self.typeletter(string[self.typepos]); self.typepos+=1; return;
[ "def", "type_IN3", "(", "self", ")", ":", "string", "=", "self", ".", "typestring", "(", ")", "if", "self", ".", "typepos", ">=", "len", "(", "string", ")", ":", "self", ".", "typeletter", "(", "0", ")", "# Send NoEvent to indicate key-up", "exit", "(", ...
https://github.com/withdk/badusb2-mitm-poc/blob/db2bfdb1dc9ad371aa665b292183c45577adfbaa/GoodFETMAXUSB.py#L1595-L1609
firewalld/firewalld
368e5a1e3eeff21ed55d4f2549836d45d8636ab5
src/firewall/core/logger.py
python
Logger.info
(self, level, _format, *args, **kwargs)
Information log using info level [1..info_max]. There are additional infox functions according to info_max from __init__
Information log using info level [1..info_max]. There are additional infox functions according to info_max from __init__
[ "Information", "log", "using", "info", "level", "[", "1", "..", "info_max", "]", ".", "There", "are", "additional", "infox", "functions", "according", "to", "info_max", "from", "__init__" ]
def info(self, level, _format, *args, **kwargs): """ Information log using info level [1..info_max]. There are additional infox functions according to info_max from __init__""" self._checkLogLevel(level, min_level=1, max_level=self.INFO_MAX) self._checkKWargs(kwargs) kwargs["is_debug"] = 0 self._log(level+self.NO_INFO, _format, *args, **kwargs)
[ "def", "info", "(", "self", ",", "level", ",", "_format", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "_checkLogLevel", "(", "level", ",", "min_level", "=", "1", ",", "max_level", "=", "self", ".", "INFO_MAX", ")", "self", "."...
https://github.com/firewalld/firewalld/blob/368e5a1e3eeff21ed55d4f2549836d45d8636ab5/src/firewall/core/logger.py#L448-L455
allenai/allennlp
a3d71254fcc0f3615910e9c3d48874515edf53e0
allennlp/data/batch.py
python
Batch.as_tensor_dict
( self, padding_lengths: Dict[str, Dict[str, int]] = None, verbose: bool = False, )
return { field_name: field_classes[field_name].batch_tensors(field_tensor_list) for field_name, field_tensor_list in field_tensors.items() }
This method converts this `Batch` into a set of pytorch Tensors that can be passed through a model. In order for the tensors to be valid tensors, all `Instances` in this batch need to be padded to the same lengths wherever padding is necessary, so we do that first, then we combine all of the tensors for each field in each instance into a set of batched tensors for each field. # Parameters padding_lengths : `Dict[str, Dict[str, int]]` If a key is present in this dictionary with a non-`None` value, we will pad to that length instead of the length calculated from the data. This lets you, e.g., set a maximum value for sentence length if you want to throw out long sequences. Entries in this dictionary are keyed first by field name (e.g., "question"), then by padding key (e.g., "num_tokens"). verbose : `bool`, optional (default=`False`) Should we output logging information when we're doing this padding? If the batch is large, this is nice to have, because padding a large batch could take a long time. But if you're doing this inside of a data generator, having all of this output per batch is a bit obnoxious (and really slow). # Returns tensors : `Dict[str, DataArray]` A dictionary of tensors, keyed by field name, suitable for passing as input to a model. This is a `batch` of instances, so, e.g., if the instances have a "question" field and an "answer" field, the "question" fields for all of the instances will be grouped together into a single tensor, and the "answer" fields for all instances will be similarly grouped in a parallel set of tensors, for batched computation. Additionally, for complex `Fields`, the value of the dictionary key is not necessarily a single tensor. For example, with the `TextField`, the output is a dictionary mapping `TokenIndexer` keys to tensors. The number of elements in this sub-dictionary therefore corresponds to the number of `TokenIndexers` used to index the `TextField`. Each `Field` class is responsible for batching its own output.
This method converts this `Batch` into a set of pytorch Tensors that can be passed through a model. In order for the tensors to be valid tensors, all `Instances` in this batch need to be padded to the same lengths wherever padding is necessary, so we do that first, then we combine all of the tensors for each field in each instance into a set of batched tensors for each field.
[ "This", "method", "converts", "this", "Batch", "into", "a", "set", "of", "pytorch", "Tensors", "that", "can", "be", "passed", "through", "a", "model", ".", "In", "order", "for", "the", "tensors", "to", "be", "valid", "tensors", "all", "Instances", "in", ...
def as_tensor_dict( self, padding_lengths: Dict[str, Dict[str, int]] = None, verbose: bool = False, ) -> Dict[str, Union[torch.Tensor, Dict[str, torch.Tensor]]]: # This complex return type is actually predefined elsewhere as a DataArray, # but we can't use it because mypy doesn't like it. """ This method converts this `Batch` into a set of pytorch Tensors that can be passed through a model. In order for the tensors to be valid tensors, all `Instances` in this batch need to be padded to the same lengths wherever padding is necessary, so we do that first, then we combine all of the tensors for each field in each instance into a set of batched tensors for each field. # Parameters padding_lengths : `Dict[str, Dict[str, int]]` If a key is present in this dictionary with a non-`None` value, we will pad to that length instead of the length calculated from the data. This lets you, e.g., set a maximum value for sentence length if you want to throw out long sequences. Entries in this dictionary are keyed first by field name (e.g., "question"), then by padding key (e.g., "num_tokens"). verbose : `bool`, optional (default=`False`) Should we output logging information when we're doing this padding? If the batch is large, this is nice to have, because padding a large batch could take a long time. But if you're doing this inside of a data generator, having all of this output per batch is a bit obnoxious (and really slow). # Returns tensors : `Dict[str, DataArray]` A dictionary of tensors, keyed by field name, suitable for passing as input to a model. This is a `batch` of instances, so, e.g., if the instances have a "question" field and an "answer" field, the "question" fields for all of the instances will be grouped together into a single tensor, and the "answer" fields for all instances will be similarly grouped in a parallel set of tensors, for batched computation. Additionally, for complex `Fields`, the value of the dictionary key is not necessarily a single tensor. For example, with the `TextField`, the output is a dictionary mapping `TokenIndexer` keys to tensors. The number of elements in this sub-dictionary therefore corresponds to the number of `TokenIndexers` used to index the `TextField`. Each `Field` class is responsible for batching its own output. """ padding_lengths = padding_lengths or defaultdict(dict) # First we need to decide _how much_ to pad. To do that, we find the max length for all # relevant padding decisions from the instances themselves. Then we check whether we were # given a max length for a particular field and padding key. If we were, we use that # instead of the instance-based one. if verbose: logger.info(f"Padding batch of size {len(self.instances)} to lengths {padding_lengths}") logger.info("Getting max lengths from instances") instance_padding_lengths = self.get_padding_lengths() if verbose: logger.info(f"Instance max lengths: {instance_padding_lengths}") lengths_to_use: Dict[str, Dict[str, int]] = defaultdict(dict) for field_name, instance_field_lengths in instance_padding_lengths.items(): for padding_key in instance_field_lengths.keys(): if padding_key in padding_lengths[field_name]: lengths_to_use[field_name][padding_key] = padding_lengths[field_name][ padding_key ] else: lengths_to_use[field_name][padding_key] = instance_field_lengths[padding_key] # Now we actually pad the instances to tensors. field_tensors: Dict[str, list] = defaultdict(list) if verbose: logger.info(f"Now actually padding instances to length: {lengths_to_use}") for instance in self.instances: for field, tensors in instance.as_tensor_dict(lengths_to_use).items(): field_tensors[field].append(tensors) # Finally, we combine the tensors that we got for each instance into one big tensor (or set # of tensors) per field. The `Field` classes themselves have the logic for batching the # tensors together, so we grab a dictionary of field_name -> field class from the first # instance in the batch. field_classes = self.instances[0].fields return { field_name: field_classes[field_name].batch_tensors(field_tensor_list) for field_name, field_tensor_list in field_tensors.items() }
[ "def", "as_tensor_dict", "(", "self", ",", "padding_lengths", ":", "Dict", "[", "str", ",", "Dict", "[", "str", ",", "int", "]", "]", "=", "None", ",", "verbose", ":", "bool", "=", "False", ",", ")", "->", "Dict", "[", "str", ",", "Union", "[", "...
https://github.com/allenai/allennlp/blob/a3d71254fcc0f3615910e9c3d48874515edf53e0/allennlp/data/batch.py#L85-L166
dbcli/mssql-cli
6509aa2fc226dde8ce6bab7af9cbb5f03717b936
mssqlcli/jsonrpc/jsonrpcclient.py
python
JsonRpcReader.try_read_headers
(self)
return True
Try to read the Header information from the internal buffer expecting the last header to contain '\r\n\r\n'. Exceptions: LookupError The content-length header was not found. ValueError The content-length contained a invalid literal for int.
Try to read the Header information from the internal buffer expecting the last header to contain '\r\n\r\n'. Exceptions: LookupError The content-length header was not found. ValueError The content-length contained a invalid literal for int.
[ "Try", "to", "read", "the", "Header", "information", "from", "the", "internal", "buffer", "expecting", "the", "last", "header", "to", "contain", "\\", "r", "\\", "n", "\\", "r", "\\", "n", ".", "Exceptions", ":", "LookupError", "The", "content", "-", "le...
def try_read_headers(self): """ Try to read the Header information from the internal buffer expecting the last header to contain '\r\n\r\n'. Exceptions: LookupError The content-length header was not found. ValueError The content-length contained a invalid literal for int. """ # Scan the buffer up until right before the CRLFCRLF. scan_offset = self.read_offset while (scan_offset + 3 < self.buffer_end_offset and (self.buffer[scan_offset] != self.CR or self.buffer[scan_offset + 1] != self.LF or self.buffer[scan_offset + 2] != self.CR or self.buffer[scan_offset + 3] != self.LF)): scan_offset += 1 # if we reached the end if scan_offset + 3 >= self.buffer_end_offset: return False # Split the headers by new line try: headers_read = self.buffer[self.read_offset:scan_offset].decode( u'ascii') for header in headers_read.split(u'\n'): colon_index = header.find(u':') if colon_index == -1: logger.debug( u'JSON RPC Reader encountered missing colons in try_read_headers()') raise KeyError( u'Colon missing from Header: {}.'.format(header)) # Case insensitive. header_key = header[:colon_index].lower() header_value = header[colon_index + 1:] self.headers[header_key] = header_value # Was content-length header found? if 'content-length' not in self.headers: logger.debug( u'JSON RPC Reader did not find Content-Length in the headers') raise LookupError( u'Content-Length was not found in headers received.') self.expected_content_length = int(self.headers[u'content-length']) except ValueError: # Content-length contained invalid literal for int. self.trim_buffer_and_resize(scan_offset + 4) raise # Pushing read pointer past the newline characters. self.read_offset = scan_offset + 4 self.read_state = ReadState.Content return True
[ "def", "try_read_headers", "(", "self", ")", ":", "# Scan the buffer up until right before the CRLFCRLF.", "scan_offset", "=", "self", ".", "read_offset", "while", "(", "scan_offset", "+", "3", "<", "self", ".", "buffer_end_offset", "and", "(", "self", ".", "buffer"...
https://github.com/dbcli/mssql-cli/blob/6509aa2fc226dde8ce6bab7af9cbb5f03717b936/mssqlcli/jsonrpc/jsonrpcclient.py#L334-L394
KalleHallden/AutoTimer
2d954216700c4930baa154e28dbddc34609af7ce
env/lib/python2.7/site-packages/pip/_vendor/html5lib/_tokenizer.py
python
HTMLTokenizer.rcdataEndTagOpenState
(self)
return True
[]
def rcdataEndTagOpenState(self): data = self.stream.char() if data in asciiLetters: self.temporaryBuffer += data self.state = self.rcdataEndTagNameState else: self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "</"}) self.stream.unget(data) self.state = self.rcdataState return True
[ "def", "rcdataEndTagOpenState", "(", "self", ")", ":", "data", "=", "self", ".", "stream", ".", "char", "(", ")", "if", "data", "in", "asciiLetters", ":", "self", ".", "temporaryBuffer", "+=", "data", "self", ".", "state", "=", "self", ".", "rcdataEndTag...
https://github.com/KalleHallden/AutoTimer/blob/2d954216700c4930baa154e28dbddc34609af7ce/env/lib/python2.7/site-packages/pip/_vendor/html5lib/_tokenizer.py#L453-L462
WikidPad/WikidPad
558109638807bc76b4672922686e416ab2d5f79c
WikidPad/lib/pwiki/wikidata/FileStorage.py
python
FileStorage.moveFile
(srcPath, dstPath)
Copy file from srcPath to dstPath. dstPath my be overwritten if existing already.
Copy file from srcPath to dstPath. dstPath my be overwritten if existing already.
[ "Copy", "file", "from", "srcPath", "to", "dstPath", ".", "dstPath", "my", "be", "overwritten", "if", "existing", "already", "." ]
def moveFile(srcPath, dstPath): """ Copy file from srcPath to dstPath. dstPath my be overwritten if existing already. """ moveFile(srcPath, dstPath)
[ "def", "moveFile", "(", "srcPath", ",", "dstPath", ")", ":", "moveFile", "(", "srcPath", ",", "dstPath", ")" ]
https://github.com/WikidPad/WikidPad/blob/558109638807bc76b4672922686e416ab2d5f79c/WikidPad/lib/pwiki/wikidata/FileStorage.py#L318-L323
naftaliharris/tauthon
5587ceec329b75f7caf6d65a036db61ac1bae214
Lib/multiprocessing/sharedctypes.py
python
Array
(typecode_or_type, size_or_initializer, **kwds)
return synchronized(obj, lock)
Return a synchronization wrapper for a RawArray
Return a synchronization wrapper for a RawArray
[ "Return", "a", "synchronization", "wrapper", "for", "a", "RawArray" ]
def Array(typecode_or_type, size_or_initializer, **kwds): ''' Return a synchronization wrapper for a RawArray ''' lock = kwds.pop('lock', None) if kwds: raise ValueError('unrecognized keyword argument(s): %s' % kwds.keys()) obj = RawArray(typecode_or_type, size_or_initializer) if lock is False: return obj if lock in (True, None): lock = RLock() if not hasattr(lock, 'acquire'): raise AttributeError("'%r' has no method 'acquire'" % lock) return synchronized(obj, lock)
[ "def", "Array", "(", "typecode_or_type", ",", "size_or_initializer", ",", "*", "*", "kwds", ")", ":", "lock", "=", "kwds", ".", "pop", "(", "'lock'", ",", "None", ")", "if", "kwds", ":", "raise", "ValueError", "(", "'unrecognized keyword argument(s): %s'", "...
https://github.com/naftaliharris/tauthon/blob/5587ceec329b75f7caf6d65a036db61ac1bae214/Lib/multiprocessing/sharedctypes.py#L113-L127
mne-tools/mne-python
f90b303ce66a8415e64edd4605b09ac0179c1ebf
mne/channels/montage.py
python
compute_dev_head_t
(montage)
return Transform(fro='meg', to='head', trans=trans)
Compute device to head transform from a DigMontage. Parameters ---------- montage : instance of DigMontage The DigMontage must contain the fiducials in head coordinate system and hpi points in both head and meg device coordinate system. Returns ------- dev_head_t : instance of Transform A Device-to-Head transformation matrix.
Compute device to head transform from a DigMontage.
[ "Compute", "device", "to", "head", "transform", "from", "a", "DigMontage", "." ]
def compute_dev_head_t(montage): """Compute device to head transform from a DigMontage. Parameters ---------- montage : instance of DigMontage The DigMontage must contain the fiducials in head coordinate system and hpi points in both head and meg device coordinate system. Returns ------- dev_head_t : instance of Transform A Device-to-Head transformation matrix. """ _, coord_frame = _get_fid_coords(montage.dig) if coord_frame != FIFF.FIFFV_COORD_HEAD: raise ValueError('montage should have been set to head coordinate ' 'system with transform_to_head function.') hpi_head = np.array( [d['r'] for d in montage.dig if (d['kind'] == FIFF.FIFFV_POINT_HPI and d['coord_frame'] == FIFF.FIFFV_COORD_HEAD)], float) hpi_dev = np.array( [d['r'] for d in montage.dig if (d['kind'] == FIFF.FIFFV_POINT_HPI and d['coord_frame'] == FIFF.FIFFV_COORD_DEVICE)], float) if not (len(hpi_head) == len(hpi_dev) and len(hpi_dev) > 0): raise ValueError(( "To compute Device-to-Head transformation, the same number of HPI" " points in device and head coordinates is required. (Got {dev}" " points in device and {head} points in head coordinate systems)" ).format(dev=len(hpi_dev), head=len(hpi_head))) trans = _quat_to_affine(_fit_matched_points(hpi_dev, hpi_head)[0]) return Transform(fro='meg', to='head', trans=trans)
[ "def", "compute_dev_head_t", "(", "montage", ")", ":", "_", ",", "coord_frame", "=", "_get_fid_coords", "(", "montage", ".", "dig", ")", "if", "coord_frame", "!=", "FIFF", ".", "FIFFV_COORD_HEAD", ":", "raise", "ValueError", "(", "'montage should have been set to ...
https://github.com/mne-tools/mne-python/blob/f90b303ce66a8415e64edd4605b09ac0179c1ebf/mne/channels/montage.py#L1408-L1445
TencentCloud/tencentcloud-sdk-python
3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2
tencentcloud/vod/v20180717/models.py
python
SortBy.__init__
(self)
r""" :param Field: 排序字段 :type Field: str :param Order: 排序方式,可选值:Asc(升序)、Desc(降序) :type Order: str
r""" :param Field: 排序字段 :type Field: str :param Order: 排序方式,可选值:Asc(升序)、Desc(降序) :type Order: str
[ "r", ":", "param", "Field", ":", "排序字段", ":", "type", "Field", ":", "str", ":", "param", "Order", ":", "排序方式,可选值:Asc(升序)、Desc(降序)", ":", "type", "Order", ":", "str" ]
def __init__(self): r""" :param Field: 排序字段 :type Field: str :param Order: 排序方式,可选值:Asc(升序)、Desc(降序) :type Order: str """ self.Field = None self.Order = None
[ "def", "__init__", "(", "self", ")", ":", "self", ".", "Field", "=", "None", "self", ".", "Order", "=", "None" ]
https://github.com/TencentCloud/tencentcloud-sdk-python/blob/3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2/tencentcloud/vod/v20180717/models.py#L19832-L19840
scikit-multilearn/scikit-multilearn
4733443b9cbb30f7f1ee7352caf38ce38cfc6163
skmultilearn/adapt/mlknn.py
python
MLkNN._compute_prior
(self, y)
return (prior_prob_true, prior_prob_false)
Helper function to compute for the prior probabilities Parameters ---------- y : numpy.ndarray or scipy.sparse the training labels Returns ------- numpy.ndarray the prior probability given true numpy.ndarray the prior probability given false
Helper function to compute for the prior probabilities
[ "Helper", "function", "to", "compute", "for", "the", "prior", "probabilities" ]
def _compute_prior(self, y): """Helper function to compute for the prior probabilities Parameters ---------- y : numpy.ndarray or scipy.sparse the training labels Returns ------- numpy.ndarray the prior probability given true numpy.ndarray the prior probability given false """ prior_prob_true = np.array((self.s + y.sum(axis=0)) / (self.s * 2 + self._num_instances))[0] prior_prob_false = 1 - prior_prob_true return (prior_prob_true, prior_prob_false)
[ "def", "_compute_prior", "(", "self", ",", "y", ")", ":", "prior_prob_true", "=", "np", ".", "array", "(", "(", "self", ".", "s", "+", "y", ".", "sum", "(", "axis", "=", "0", ")", ")", "/", "(", "self", ".", "s", "*", "2", "+", "self", ".", ...
https://github.com/scikit-multilearn/scikit-multilearn/blob/4733443b9cbb30f7f1ee7352caf38ce38cfc6163/skmultilearn/adapt/mlknn.py#L126-L144
apache/bloodhound
c3e31294e68af99d4e040e64fbdf52394344df9e
trac/trac/util/text.py
python
unicode_unquote
(value)
return unquote(value).decode('utf-8')
A unicode aware version of `urllib.unquote`. :param str: UTF-8 encoded `str` value (for example, as obtained by `unicode_quote`). :rtype: `unicode`
A unicode aware version of `urllib.unquote`.
[ "A", "unicode", "aware", "version", "of", "urllib", ".", "unquote", "." ]
def unicode_unquote(value): """A unicode aware version of `urllib.unquote`. :param str: UTF-8 encoded `str` value (for example, as obtained by `unicode_quote`). :rtype: `unicode` """ return unquote(value).decode('utf-8')
[ "def", "unicode_unquote", "(", "value", ")", ":", "return", "unquote", "(", "value", ")", ".", "decode", "(", "'utf-8'", ")" ]
https://github.com/apache/bloodhound/blob/c3e31294e68af99d4e040e64fbdf52394344df9e/trac/trac/util/text.py#L187-L194
intrig-unicamp/mininet-wifi
3c8a8f63bd4aa043aa9c1ad16f304dec2916f5ba
mn_wifi/sumo/traci/_vehicle.py
python
VehicleDomain.getMinGapLat
(self, vehID)
return self._getUniversal(tc.VAR_MINGAP_LAT, vehID)
getMinGapLat(string) -> double Returns The desired lateral gap of this vehicle at 50km/h in m
getMinGapLat(string) -> double Returns The desired lateral gap of this vehicle at 50km/h in m
[ "getMinGapLat", "(", "string", ")", "-", ">", "double", "Returns", "The", "desired", "lateral", "gap", "of", "this", "vehicle", "at", "50km", "/", "h", "in", "m" ]
def getMinGapLat(self, vehID): """getMinGapLat(string) -> double Returns The desired lateral gap of this vehicle at 50km/h in m """ return self._getUniversal(tc.VAR_MINGAP_LAT, vehID)
[ "def", "getMinGapLat", "(", "self", ",", "vehID", ")", ":", "return", "self", ".", "_getUniversal", "(", "tc", ".", "VAR_MINGAP_LAT", ",", "vehID", ")" ]
https://github.com/intrig-unicamp/mininet-wifi/blob/3c8a8f63bd4aa043aa9c1ad16f304dec2916f5ba/mn_wifi/sumo/traci/_vehicle.py#L421-L425
librahfacebook/Detection
84504d086634950224716f4de0e4c8a684493c34
object_detection/utils/np_mask_ops.py
python
area
(masks)
return np.sum(masks, axis=(1, 2), dtype=np.float32)
Computes area of masks. Args: masks: Numpy array with shape [N, height, width] holding N masks. Masks values are of type np.uint8 and values are in {0,1}. Returns: a numpy array with shape [N*1] representing mask areas. Raises: ValueError: If masks.dtype is not np.uint8
Computes area of masks.
[ "Computes", "area", "of", "masks", "." ]
def area(masks): """Computes area of masks. Args: masks: Numpy array with shape [N, height, width] holding N masks. Masks values are of type np.uint8 and values are in {0,1}. Returns: a numpy array with shape [N*1] representing mask areas. Raises: ValueError: If masks.dtype is not np.uint8 """ if masks.dtype != np.uint8: raise ValueError('Masks type should be np.uint8') return np.sum(masks, axis=(1, 2), dtype=np.float32)
[ "def", "area", "(", "masks", ")", ":", "if", "masks", ".", "dtype", "!=", "np", ".", "uint8", ":", "raise", "ValueError", "(", "'Masks type should be np.uint8'", ")", "return", "np", ".", "sum", "(", "masks", ",", "axis", "=", "(", "1", ",", "2", ")"...
https://github.com/librahfacebook/Detection/blob/84504d086634950224716f4de0e4c8a684493c34/object_detection/utils/np_mask_ops.py#L27-L42
JaniceWuo/MovieRecommend
4c86db64ca45598917d304f535413df3bc9fea65
movierecommend/venv1/Lib/site-packages/django/core/serializers/xml_serializer.py
python
Serializer.handle_fk_field
(self, obj, field)
Called to handle a ForeignKey (we need to treat them slightly differently from regular fields).
Called to handle a ForeignKey (we need to treat them slightly differently from regular fields).
[ "Called", "to", "handle", "a", "ForeignKey", "(", "we", "need", "to", "treat", "them", "slightly", "differently", "from", "regular", "fields", ")", "." ]
def handle_fk_field(self, obj, field): """ Called to handle a ForeignKey (we need to treat them slightly differently from regular fields). """ self._start_relational_field(field) related_att = getattr(obj, field.get_attname()) if related_att is not None: if self.use_natural_foreign_keys and hasattr(field.remote_field.model, 'natural_key'): related = getattr(obj, field.name) # If related object has a natural key, use it related = related.natural_key() # Iterable natural keys are rolled out as subelements for key_value in related: self.xml.startElement("natural", {}) self.xml.characters(force_text(key_value)) self.xml.endElement("natural") else: self.xml.characters(force_text(related_att)) else: self.xml.addQuickElement("None") self.xml.endElement("field")
[ "def", "handle_fk_field", "(", "self", ",", "obj", ",", "field", ")", ":", "self", ".", "_start_relational_field", "(", "field", ")", "related_att", "=", "getattr", "(", "obj", ",", "field", ".", "get_attname", "(", ")", ")", "if", "related_att", "is", "...
https://github.com/JaniceWuo/MovieRecommend/blob/4c86db64ca45598917d304f535413df3bc9fea65/movierecommend/venv1/Lib/site-packages/django/core/serializers/xml_serializer.py#L93-L114
jgagneastro/coffeegrindsize
22661ebd21831dba4cf32bfc6ba59fe3d49f879c
App/dist/coffeegrindsize.app/Contents/Resources/lib/python3.7/matplotlib/mlab.py
python
dist_point_to_segment
(p, s0, s1)
return dist(p, pb)
Get the distance of a point to a segment. *p*, *s0*, *s1* are *xy* sequences This algorithm from http://geomalgorithms.com/a02-_lines.html
Get the distance of a point to a segment.
[ "Get", "the", "distance", "of", "a", "point", "to", "a", "segment", "." ]
def dist_point_to_segment(p, s0, s1): """ Get the distance of a point to a segment. *p*, *s0*, *s1* are *xy* sequences This algorithm from http://geomalgorithms.com/a02-_lines.html """ p = np.asarray(p, float) s0 = np.asarray(s0, float) s1 = np.asarray(s1, float) v = s1 - s0 w = p - s0 c1 = np.dot(w, v) if c1 <= 0: return dist(p, s0) c2 = np.dot(v, v) if c2 <= c1: return dist(p, s1) b = c1 / c2 pb = s0 + b * v return dist(p, pb)
[ "def", "dist_point_to_segment", "(", "p", ",", "s0", ",", "s1", ")", ":", "p", "=", "np", ".", "asarray", "(", "p", ",", "float", ")", "s0", "=", "np", ".", "asarray", "(", "s0", ",", "float", ")", "s1", "=", "np", ".", "asarray", "(", "s1", ...
https://github.com/jgagneastro/coffeegrindsize/blob/22661ebd21831dba4cf32bfc6ba59fe3d49f879c/App/dist/coffeegrindsize.app/Contents/Resources/lib/python3.7/matplotlib/mlab.py#L1904-L1929
python/mypy
17850b3bd77ae9efb5d21f656c4e4e05ac48d894
mypy/semanal_infer.py
python
calculate_return_type
(expr: Expression)
return None
Return the return type if we can calculate it. This only uses information available during semantic analysis so this will sometimes return None because of insufficient information (as type inference hasn't run yet).
Return the return type if we can calculate it.
[ "Return", "the", "return", "type", "if", "we", "can", "calculate", "it", "." ]
def calculate_return_type(expr: Expression) -> Optional[ProperType]: """Return the return type if we can calculate it. This only uses information available during semantic analysis so this will sometimes return None because of insufficient information (as type inference hasn't run yet). """ if isinstance(expr, RefExpr): if isinstance(expr.node, FuncDef): typ = expr.node.type if typ is None: # No signature -> default to Any. return AnyType(TypeOfAny.unannotated) # Explicit Any return? if isinstance(typ, CallableType): return get_proper_type(typ.ret_type) return None elif isinstance(expr.node, Var): return get_proper_type(expr.node.type) elif isinstance(expr, CallExpr): return calculate_return_type(expr.callee) return None
[ "def", "calculate_return_type", "(", "expr", ":", "Expression", ")", "->", "Optional", "[", "ProperType", "]", ":", "if", "isinstance", "(", "expr", ",", "RefExpr", ")", ":", "if", "isinstance", "(", "expr", ".", "node", ",", "FuncDef", ")", ":", "typ", ...
https://github.com/python/mypy/blob/17850b3bd77ae9efb5d21f656c4e4e05ac48d894/mypy/semanal_infer.py#L75-L96
brjathu/deepcaps
c2f3be37c311028a5ef51f3ea5b942cab3a6d069
capslayers.py
python
Conv2DCaps.__init__
(self, ch_j, n_j, kernel_size=(3, 3), strides=(1, 1), r_num=1, b_alphas=[8, 8, 8], padding='same', data_format='channels_last', dilation_rate=(1, 1), kernel_initializer='glorot_uniform', bias_initializer='zeros', kernel_regularizer=None, activity_regularizer=None, kernel_constraint=None, **kwargs)
[]
def __init__(self, ch_j, n_j, kernel_size=(3, 3), strides=(1, 1), r_num=1, b_alphas=[8, 8, 8], padding='same', data_format='channels_last', dilation_rate=(1, 1), kernel_initializer='glorot_uniform', bias_initializer='zeros', kernel_regularizer=None, activity_regularizer=None, kernel_constraint=None, **kwargs): super(Conv2DCaps, self).__init__(**kwargs) rank = 2 self.ch_j = ch_j # Number of capsules in layer J self.n_j = n_j # Number of neurons in a capsule in J self.kernel_size = conv_utils.normalize_tuple(kernel_size, rank, 'kernel_size') self.strides = conv_utils.normalize_tuple(strides, rank, 'strides') self.r_num = r_num self.b_alphas = b_alphas self.padding = conv_utils.normalize_padding(padding) #self.data_format = conv_utils.normalize_data_format(data_format) self.data_format = K.normalize_data_format(data_format) self.dilation_rate = (1, 1) self.kernel_initializer = initializers.get(kernel_initializer) self.bias_initializer = initializers.get(bias_initializer) self.kernel_regularizer = regularizers.get(kernel_regularizer) self.activity_regularizer = regularizers.get(activity_regularizer) self.kernel_constraint = constraints.get(kernel_constraint) self.input_spec = InputSpec(ndim=rank + 3)
[ "def", "__init__", "(", "self", ",", "ch_j", ",", "n_j", ",", "kernel_size", "=", "(", "3", ",", "3", ")", ",", "strides", "=", "(", "1", ",", "1", ")", ",", "r_num", "=", "1", ",", "b_alphas", "=", "[", "8", ",", "8", ",", "8", "]", ",", ...
https://github.com/brjathu/deepcaps/blob/c2f3be37c311028a5ef51f3ea5b942cab3a6d069/capslayers.py#L78-L109
usb-tools/Facedancer
e688fe61dc34087db333432394e1f90e52ac3794
legacy-applets/USBMassStorage.py
python
DiskImage.get_sector_data
(self, address)
Returns the raw binary data for a given sector.
Returns the raw binary data for a given sector.
[ "Returns", "the", "raw", "binary", "data", "for", "a", "given", "sector", "." ]
def get_sector_data(self, address): """ Returns the raw binary data for a given sector. """ raise NotImplementedError()
[ "def", "get_sector_data", "(", "self", ",", "address", ")", ":", "raise", "NotImplementedError", "(", ")" ]
https://github.com/usb-tools/Facedancer/blob/e688fe61dc34087db333432394e1f90e52ac3794/legacy-applets/USBMassStorage.py#L457-L459
makerbot/ReplicatorG
d6f2b07785a5a5f1e172fb87cb4303b17c575d5d
skein_engines/skeinforge-50/fabmetheus_utilities/geometry/geometry_utilities/boolean_solid.py
python
getInsetPointsByInsetLoops
( insetLoops, inside, loops, radius )
return insetPointsByInsetLoops
Get the inset points of the inset loops inside the loops.
Get the inset points of the inset loops inside the loops.
[ "Get", "the", "inset", "points", "of", "the", "inset", "loops", "inside", "the", "loops", "." ]
def getInsetPointsByInsetLoops( insetLoops, inside, loops, radius ): 'Get the inset points of the inset loops inside the loops.' insetPointsByInsetLoops = [] for insetLoop in insetLoops: insetPointsByInsetLoops += getInsetPointsByInsetLoop( insetLoop, inside, loops, radius ) return insetPointsByInsetLoops
[ "def", "getInsetPointsByInsetLoops", "(", "insetLoops", ",", "inside", ",", "loops", ",", "radius", ")", ":", "insetPointsByInsetLoops", "=", "[", "]", "for", "insetLoop", "in", "insetLoops", ":", "insetPointsByInsetLoops", "+=", "getInsetPointsByInsetLoop", "(", "i...
https://github.com/makerbot/ReplicatorG/blob/d6f2b07785a5a5f1e172fb87cb4303b17c575d5d/skein_engines/skeinforge-50/fabmetheus_utilities/geometry/geometry_utilities/boolean_solid.py#L104-L109
edisonlz/fastor
342078a18363ac41d3c6b1ab29dbdd44fdb0b7b3
base/site-packages/gdata/tlslite/mathtls.py
python
MAC_SSL.__init__
(self, key, msg = None, digestmod = None)
Create a new MAC_SSL object. key: key for the keyed hash object. msg: Initial input for the hash, if provided. digestmod: A module supporting PEP 247. Defaults to the md5 module.
Create a new MAC_SSL object.
[ "Create", "a", "new", "MAC_SSL", "object", "." ]
def __init__(self, key, msg = None, digestmod = None): """Create a new MAC_SSL object. key: key for the keyed hash object. msg: Initial input for the hash, if provided. digestmod: A module supporting PEP 247. Defaults to the md5 module. """ if digestmod is None: import md5 digestmod = md5 if key == None: #TREVNEW - for faster copying return #TREVNEW self.digestmod = digestmod self.outer = digestmod.new() self.inner = digestmod.new() self.digest_size = digestmod.digest_size ipad = "\x36" * 40 opad = "\x5C" * 40 self.inner.update(key) self.inner.update(ipad) self.outer.update(key) self.outer.update(opad) if msg is not None: self.update(msg)
[ "def", "__init__", "(", "self", ",", "key", ",", "msg", "=", "None", ",", "digestmod", "=", "None", ")", ":", "if", "digestmod", "is", "None", ":", "import", "md5", "digestmod", "=", "md5", "if", "key", "==", "None", ":", "#TREVNEW - for faster copying",...
https://github.com/edisonlz/fastor/blob/342078a18363ac41d3c6b1ab29dbdd44fdb0b7b3/base/site-packages/gdata/tlslite/mathtls.py#L108-L135
lingtengqiu/Deeperlab-pytorch
5c500780a6655ff343d147477402aa20e0ed7a7c
seg_opr/loss_opr.py
python
SigmoidFocalLoss.__init__
(self, ignore_label, gamma=2.0, alpha=0.25, reduction='mean')
[]
def __init__(self, ignore_label, gamma=2.0, alpha=0.25, reduction='mean'): super(SigmoidFocalLoss, self).__init__() self.ignore_label = ignore_label self.gamma = gamma self.alpha = alpha self.reduction = reduction
[ "def", "__init__", "(", "self", ",", "ignore_label", ",", "gamma", "=", "2.0", ",", "alpha", "=", "0.25", ",", "reduction", "=", "'mean'", ")", ":", "super", "(", "SigmoidFocalLoss", ",", "self", ")", ".", "__init__", "(", ")", "self", ".", "ignore_lab...
https://github.com/lingtengqiu/Deeperlab-pytorch/blob/5c500780a6655ff343d147477402aa20e0ed7a7c/seg_opr/loss_opr.py#L14-L20
apeterswu/RL4NMT
3c66a2d8142abc5ce73db63e05d3cc9bf4663b65
tensor2tensor/utils/usr_dir.py
python
import_usr_dir
(usr_dir)
Import module at usr_dir, if provided.
Import module at usr_dir, if provided.
[ "Import", "module", "at", "usr_dir", "if", "provided", "." ]
def import_usr_dir(usr_dir): """Import module at usr_dir, if provided.""" if not usr_dir: return dir_path = os.path.expanduser(usr_dir) if dir_path[-1] == "/": dir_path = dir_path[:-1] containing_dir, module_name = os.path.split(dir_path) tf.logging.info("Importing user module %s from path %s", module_name, containing_dir) sys.path.insert(0, containing_dir) importlib.import_module(module_name) sys.path.pop(0)
[ "def", "import_usr_dir", "(", "usr_dir", ")", ":", "if", "not", "usr_dir", ":", "return", "dir_path", "=", "os", ".", "path", ".", "expanduser", "(", "usr_dir", ")", "if", "dir_path", "[", "-", "1", "]", "==", "\"/\"", ":", "dir_path", "=", "dir_path",...
https://github.com/apeterswu/RL4NMT/blob/3c66a2d8142abc5ce73db63e05d3cc9bf4663b65/tensor2tensor/utils/usr_dir.py#L30-L42
oaubert/python-vlc
908ffdbd0844dc1849728c456e147788798c99da
generated/2.2/vlc.py
python
MediaListPlayer.retain
(self)
return libvlc_media_list_player_retain(self)
Retain a reference to a media player list object. Use L{release}() to decrement reference count.
Retain a reference to a media player list object. Use L{release}() to decrement reference count.
[ "Retain", "a", "reference", "to", "a", "media", "player", "list", "object", ".", "Use", "L", "{", "release", "}", "()", "to", "decrement", "reference", "count", "." ]
def retain(self): '''Retain a reference to a media player list object. Use L{release}() to decrement reference count. ''' return libvlc_media_list_player_retain(self)
[ "def", "retain", "(", "self", ")", ":", "return", "libvlc_media_list_player_retain", "(", "self", ")" ]
https://github.com/oaubert/python-vlc/blob/908ffdbd0844dc1849728c456e147788798c99da/generated/2.2/vlc.py#L2572-L2576
jjjake/internetarchive
7b0472464b065477101a847a8332d8b4dc1bf74e
internetarchive/api.py
python
get_session
(config=None, config_file=None, debug=None, http_adapter_kwargs=None)
return session.ArchiveSession(config, config_file, debug, http_adapter_kwargs)
Return a new :class:`ArchiveSession` object. The :class:`ArchiveSession` object is the main interface to the ``internetarchive`` lib. It allows you to persist certain parameters across tasks. :type config: dict :param config: (optional) A dictionary used to configure your session. :type config_file: str :param config_file: (optional) A path to a config file used to configure your session. :type http_adapter_kwargs: dict :param http_adapter_kwargs: (optional) Keyword arguments that :py:class:`requests.adapters.HTTPAdapter` takes. :returns: :class:`ArchiveSession` object. Usage: >>> from internetarchive import get_session >>> config = dict(s3=dict(access='foo', secret='bar')) >>> s = get_session(config) >>> s.access_key 'foo' From the session object, you can access all of the functionality of the ``internetarchive`` lib: >>> item = s.get_item('nasa') >>> item.download() nasa: ddddddd - success >>> s.get_tasks(task_ids=31643513)[0].server 'ia311234'
Return a new :class:`ArchiveSession` object. The :class:`ArchiveSession` object is the main interface to the ``internetarchive`` lib. It allows you to persist certain parameters across tasks.
[ "Return", "a", "new", ":", "class", ":", "ArchiveSession", "object", ".", "The", ":", "class", ":", "ArchiveSession", "object", "is", "the", "main", "interface", "to", "the", "internetarchive", "lib", ".", "It", "allows", "you", "to", "persist", "certain", ...
def get_session(config=None, config_file=None, debug=None, http_adapter_kwargs=None): """Return a new :class:`ArchiveSession` object. The :class:`ArchiveSession` object is the main interface to the ``internetarchive`` lib. It allows you to persist certain parameters across tasks. :type config: dict :param config: (optional) A dictionary used to configure your session. :type config_file: str :param config_file: (optional) A path to a config file used to configure your session. :type http_adapter_kwargs: dict :param http_adapter_kwargs: (optional) Keyword arguments that :py:class:`requests.adapters.HTTPAdapter` takes. :returns: :class:`ArchiveSession` object. Usage: >>> from internetarchive import get_session >>> config = dict(s3=dict(access='foo', secret='bar')) >>> s = get_session(config) >>> s.access_key 'foo' From the session object, you can access all of the functionality of the ``internetarchive`` lib: >>> item = s.get_item('nasa') >>> item.download() nasa: ddddddd - success >>> s.get_tasks(task_ids=31643513)[0].server 'ia311234' """ return session.ArchiveSession(config, config_file, debug, http_adapter_kwargs)
[ "def", "get_session", "(", "config", "=", "None", ",", "config_file", "=", "None", ",", "debug", "=", "None", ",", "http_adapter_kwargs", "=", "None", ")", ":", "return", "session", ".", "ArchiveSession", "(", "config", ",", "config_file", ",", "debug", ",...
https://github.com/jjjake/internetarchive/blob/7b0472464b065477101a847a8332d8b4dc1bf74e/internetarchive/api.py#L41-L75
google/grr
8ad8a4d2c5a93c92729206b7771af19d92d4f915
grr/core/grr_response_core/lib/rdfvalues/structs.py
python
ProtoType.SetOwner
(self, owner)
[]
def SetOwner(self, owner): self.owner = owner
[ "def", "SetOwner", "(", "self", ",", "owner", ")", ":", "self", ".", "owner", "=", "owner" ]
https://github.com/google/grr/blob/8ad8a4d2c5a93c92729206b7771af19d92d4f915/grr/core/grr_response_core/lib/rdfvalues/structs.py#L314-L315
ospalh/anki-addons
4ece13423bd541e29d9b40ebe26ca0999a6962b1
play_button/__init__.py
python
reduce_format_qa
(self, text)
return original_format_qa(self, unicode(soup))
Remove elements with a given class before displaying.
Remove elements with a given class before displaying.
[ "Remove", "elements", "with", "a", "given", "class", "before", "displaying", "." ]
def reduce_format_qa(self, text): """Remove elements with a given class before displaying.""" soup = BeautifulSoup(text, 'html.parser') for hide in soup.findAll(True, {'class': re.compile( '\\b' + hide_class_name + '\\b')}): hide.extract() return original_format_qa(self, unicode(soup))
[ "def", "reduce_format_qa", "(", "self", ",", "text", ")", ":", "soup", "=", "BeautifulSoup", "(", "text", ",", "'html.parser'", ")", "for", "hide", "in", "soup", ".", "findAll", "(", "True", ",", "{", "'class'", ":", "re", ".", "compile", "(", "'\\\\b'...
https://github.com/ospalh/anki-addons/blob/4ece13423bd541e29d9b40ebe26ca0999a6962b1/play_button/__init__.py#L125-L131
cloudera/hue
23f02102d4547c17c32bd5ea0eb24e9eadd657a4
desktop/core/ext-py/rsa-3.4.2/rsa/cli.py
python
SignOperation.perform_operation
(self, indata, priv_key, cli_args)
return rsa.sign(indata, priv_key, hash_method)
Signs files.
Signs files.
[ "Signs", "files", "." ]
def perform_operation(self, indata, priv_key, cli_args): """Signs files.""" hash_method = cli_args[1] if hash_method not in HASH_METHODS: raise SystemExit('Invalid hash method, choose one of %s' % ', '.join(HASH_METHODS)) return rsa.sign(indata, priv_key, hash_method)
[ "def", "perform_operation", "(", "self", ",", "indata", ",", "priv_key", ",", "cli_args", ")", ":", "hash_method", "=", "cli_args", "[", "1", "]", "if", "hash_method", "not", "in", "HASH_METHODS", ":", "raise", "SystemExit", "(", "'Invalid hash method, choose on...
https://github.com/cloudera/hue/blob/23f02102d4547c17c32bd5ea0eb24e9eadd657a4/desktop/core/ext-py/rsa-3.4.2/rsa/cli.py#L247-L255
partho-maple/coding-interview-gym
f9b28916da31935a27900794cfb8b91be3b38b9b
leetcode.com/python/70_Climbing_Stairs.py
python
Solution.climbStairsHelper
(self, n, memo)
return oneStepCounter + twoStepCounter
:type n: int :rtype: int
:type n: int :rtype: int
[ ":", "type", "n", ":", "int", ":", "rtype", ":", "int" ]
def climbStairsHelper(self, n, memo): """ :type n: int :rtype: int """ if n == 0: memo[n] = 0 return 0 elif n == 1: memo[n] = 1 return 1 elif n == 2: memo[n] = 2 return 2 if n - 1 in memo: oneStepCounter = memo[n - 1] else: oneStepCounter = self.climbStairsHelper(n - 1, memo) memo[n - 1] = oneStepCounter if n - 2 in memo: twoStepCounter = memo[n - 2] else: twoStepCounter = self.climbStairsHelper(n - 2, memo) memo[n - 2] = twoStepCounter return oneStepCounter + twoStepCounter
[ "def", "climbStairsHelper", "(", "self", ",", "n", ",", "memo", ")", ":", "if", "n", "==", "0", ":", "memo", "[", "n", "]", "=", "0", "return", "0", "elif", "n", "==", "1", ":", "memo", "[", "n", "]", "=", "1", "return", "1", "elif", "n", "...
https://github.com/partho-maple/coding-interview-gym/blob/f9b28916da31935a27900794cfb8b91be3b38b9b/leetcode.com/python/70_Climbing_Stairs.py#L10-L34
datawire/forge
d501be4571dcef5691804c7db7008ee877933c8d
forge/executor.py
python
Result.is_signal
(self, (filename, lineno, funcname, text))
return True
[]
def is_signal(self, (filename, lineno, funcname, text)): noise = {"forge/executor.py": ("run", "do_run", "_capture_stack"), "forge/tasks.py": ("go", "__call__"), "eventlet/greenthread.py": ("main",)} for k, v in noise.items(): if filename.endswith(k) and funcname in v: return False return True
[ "def", "is_signal", "(", "self", ",", "(", "filename", ",", "lineno", ",", "funcname", ",", "text", ")", ")", ":", "noise", "=", "{", "\"forge/executor.py\"", ":", "(", "\"run\"", ",", "\"do_run\"", ",", "\"_capture_stack\"", ")", ",", "\"forge/tasks.py\"", ...
https://github.com/datawire/forge/blob/d501be4571dcef5691804c7db7008ee877933c8d/forge/executor.py#L126-L133
tomplus/kubernetes_asyncio
f028cc793e3a2c519be6a52a49fb77ff0b014c9b
kubernetes_asyncio/client/api/core_v1_api.py
python
CoreV1Api.patch_namespaced_pod_with_http_info
(self, name, namespace, body, **kwargs)
return self.api_client.call_api( '/api/v1/namespaces/{namespace}/pods/{name}', 'PATCH', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1Pod', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats)
patch_namespaced_pod # noqa: E501 partially update the specified Pod # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.patch_namespaced_pod_with_http_info(name, namespace, body, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the Pod (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param object body: (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 str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch). :param bool force: Force is going to \"force\" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests. :param _return_http_data_only: response data without head status code and headers :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: tuple(V1Pod, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread.
patch_namespaced_pod # noqa: E501
[ "patch_namespaced_pod", "#", "noqa", ":", "E501" ]
def patch_namespaced_pod_with_http_info(self, name, namespace, body, **kwargs): # noqa: E501 """patch_namespaced_pod # noqa: E501 partially update the specified Pod # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.patch_namespaced_pod_with_http_info(name, namespace, body, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the Pod (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param object body: (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 str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch). :param bool force: Force is going to \"force\" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests. :param _return_http_data_only: response data without head status code and headers :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: tuple(V1Pod, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ local_var_params = locals() all_params = [ 'name', 'namespace', 'body', 'pretty', 'dry_run', 'field_manager', 'force' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method patch_namespaced_pod" % key ) local_var_params[key] = val del local_var_params['kwargs'] # verify the required parameter 'name' is set if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501 local_var_params['name'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `name` when calling `patch_namespaced_pod`") # noqa: E501 # verify the required parameter 'namespace' is set if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501 local_var_params['namespace'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `namespace` when calling `patch_namespaced_pod`") # noqa: E501 # verify the required parameter 'body' is set if self.api_client.client_side_validation and ('body' not in local_var_params or # noqa: E501 local_var_params['body'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `body` when calling `patch_namespaced_pod`") # noqa: E501 collection_formats = {} path_params = {} if 'name' in local_var_params: path_params['name'] = local_var_params['name'] # noqa: E501 if 'namespace' in local_var_params: path_params['namespace'] = local_var_params['namespace'] # noqa: E501 query_params = [] if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501 query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501 if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501 query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501 if 'field_manager' in local_var_params and local_var_params['field_manager'] is not None: # noqa: E501 query_params.append(('fieldManager', local_var_params['field_manager'])) # noqa: E501 if 'force' in local_var_params and local_var_params['force'] is not None: # noqa: E501 query_params.append(('force', local_var_params['force'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None if 'body' in local_var_params: body_params = local_var_params['body'] # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501 # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 ['application/json-patch+json', 'application/merge-patch+json', 'application/strategic-merge-patch+json', 'application/apply-patch+yaml']) # noqa: E501 # Authentication setting auth_settings = ['BearerToken'] # noqa: E501 return self.api_client.call_api( '/api/v1/namespaces/{namespace}/pods/{name}', 'PATCH', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1Pod', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats)
[ "def", "patch_namespaced_pod_with_http_info", "(", "self", ",", "name", ",", "namespace", ",", "body", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "local_var_params", "=", "locals", "(", ")", "all_params", "=", "[", "'name'", ",", "'namespace'", ",", ...
https://github.com/tomplus/kubernetes_asyncio/blob/f028cc793e3a2c519be6a52a49fb77ff0b014c9b/kubernetes_asyncio/client/api/core_v1_api.py#L19349-L19472
learningequality/ka-lite
571918ea668013dcf022286ea85eff1c5333fb8b
kalite/packages/bundled/django/db/models/query.py
python
QuerySet._fill_cache
(self, num=None)
Fills the result cache with 'num' more entries (or until the results iterator is exhausted).
Fills the result cache with 'num' more entries (or until the results iterator is exhausted).
[ "Fills", "the", "result", "cache", "with", "num", "more", "entries", "(", "or", "until", "the", "results", "iterator", "is", "exhausted", ")", "." ]
def _fill_cache(self, num=None): """ Fills the result cache with 'num' more entries (or until the results iterator is exhausted). """ if self._iter: try: for i in range(num or ITER_CHUNK_SIZE): self._result_cache.append(next(self._iter)) except StopIteration: self._iter = None
[ "def", "_fill_cache", "(", "self", ",", "num", "=", "None", ")", ":", "if", "self", ".", "_iter", ":", "try", ":", "for", "i", "in", "range", "(", "num", "or", "ITER_CHUNK_SIZE", ")", ":", "self", ".", "_result_cache", ".", "append", "(", "next", "...
https://github.com/learningequality/ka-lite/blob/571918ea668013dcf022286ea85eff1c5333fb8b/kalite/packages/bundled/django/db/models/query.py#L919-L929
lmb-freiburg/hand3d
9f0063391e7075cf4ab1e4edd0461d38213a3fd6
utils/canonical_trafo.py
python
_get_rot_mat_x
(angle)
return trafo_matrix
Returns a 3D rotation matrix.
Returns a 3D rotation matrix.
[ "Returns", "a", "3D", "rotation", "matrix", "." ]
def _get_rot_mat_x(angle): """ Returns a 3D rotation matrix. """ one_vec = tf.ones_like(angle) zero_vec = one_vec*0.0 trafo_matrix = _stitch_mat_from_vecs([one_vec, zero_vec, zero_vec, zero_vec, tf.cos(angle), tf.sin(angle), zero_vec, -tf.sin(angle), tf.cos(angle)]) return trafo_matrix
[ "def", "_get_rot_mat_x", "(", "angle", ")", ":", "one_vec", "=", "tf", ".", "ones_like", "(", "angle", ")", "zero_vec", "=", "one_vec", "*", "0.0", "trafo_matrix", "=", "_stitch_mat_from_vecs", "(", "[", "one_vec", ",", "zero_vec", ",", "zero_vec", ",", "z...
https://github.com/lmb-freiburg/hand3d/blob/9f0063391e7075cf4ab1e4edd0461d38213a3fd6/utils/canonical_trafo.py#L64-L71
SPFlow/SPFlow
68ce7dac0f41bd3cf86ccb56555a29ef1368fe69
src/spn/experiments/RandomSPNs_layerwise/train_mnist.py
python
make_spn
(S, I, R, D, dropout, device)
return model
Construct the RatSpn
Construct the RatSpn
[ "Construct", "the", "RatSpn" ]
def make_spn(S, I, R, D, dropout, device) -> RatSpn: """Construct the RatSpn""" # Setup RatSpnConfig config = RatSpnConfig() config.F = 28 ** 2 config.R = R config.D = D config.I = I config.S = S config.C = 10 config.dropout = dropout config.leaf_base_class = RatNormal config.leaf_base_kwargs = {} # Construct RatSpn from config model = RatSpn(config) model = model.to(device) model.train() print("Using device:", device) return model
[ "def", "make_spn", "(", "S", ",", "I", ",", "R", ",", "D", ",", "dropout", ",", "device", ")", "->", "RatSpn", ":", "# Setup RatSpnConfig", "config", "=", "RatSpnConfig", "(", ")", "config", ".", "F", "=", "28", "**", "2", "config", ".", "R", "=", ...
https://github.com/SPFlow/SPFlow/blob/68ce7dac0f41bd3cf86ccb56555a29ef1368fe69/src/spn/experiments/RandomSPNs_layerwise/train_mnist.py#L87-L109
facebookresearch/ParlAI
e4d59c30eef44f1f67105961b82a83fd28d7d78b
parlai/core/metrics.py
python
Metrics.clear
(self)
Clear all the metrics.
Clear all the metrics.
[ "Clear", "all", "the", "metrics", "." ]
def clear(self): """ Clear all the metrics. """ self._data.clear() self._recent_data.clear()
[ "def", "clear", "(", "self", ")", ":", "self", ".", "_data", ".", "clear", "(", ")", "self", ".", "_recent_data", ".", "clear", "(", ")" ]
https://github.com/facebookresearch/ParlAI/blob/e4d59c30eef44f1f67105961b82a83fd28d7d78b/parlai/core/metrics.py#L928-L933
sagemath/sage
f9b2db94f675ff16963ccdefba4f1a3393b3fe0d
src/sage/schemes/toric/variety.py
python
CohomologyRing._repr_
(self)
return f'Rational cohomology ring of a {self._variety._repr_()}'
r""" Return a string representation of the cohomology ring. OUTPUT: A string. EXAMPLES:: sage: toric_varieties.P2().cohomology_ring()._repr_() 'Rational cohomology ring of a 2-d CPR-Fano toric variety covered by 3 affine patches'
r""" Return a string representation of the cohomology ring.
[ "r", "Return", "a", "string", "representation", "of", "the", "cohomology", "ring", "." ]
def _repr_(self): r""" Return a string representation of the cohomology ring. OUTPUT: A string. EXAMPLES:: sage: toric_varieties.P2().cohomology_ring()._repr_() 'Rational cohomology ring of a 2-d CPR-Fano toric variety covered by 3 affine patches' """ return f'Rational cohomology ring of a {self._variety._repr_()}'
[ "def", "_repr_", "(", "self", ")", ":", "return", "f'Rational cohomology ring of a {self._variety._repr_()}'" ]
https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/schemes/toric/variety.py#L3165-L3178
cltk/cltk
1a8c2f5ef72389e2579dfce1fa5af8e59ebc9ec1
src/cltk/prosody/lat/verse_scanner.py
python
VerseScanner.transform_i_to_j
(self, line: str)
return "".join(char_list)
Transform instances of consonantal i to j :param line: :return: >>> print(VerseScanner().transform_i_to_j("iactātus")) jactātus >>> print(VerseScanner().transform_i_to_j("bracchia")) bracchia
Transform instances of consonantal i to j :param line: :return:
[ "Transform", "instances", "of", "consonantal", "i", "to", "j", ":", "param", "line", ":", ":", "return", ":" ]
def transform_i_to_j(self, line: str) -> str: """ Transform instances of consonantal i to j :param line: :return: >>> print(VerseScanner().transform_i_to_j("iactātus")) jactātus >>> print(VerseScanner().transform_i_to_j("bracchia")) bracchia """ words = line.split(" ") space_list = string_utils.space_list(line) corrected_words = [] for word in words: found = False for prefix in self.constants.PREFIXES: if word.startswith(prefix) and word != prefix: corrected_words.append( self.syllabifier.convert_consonantal_i(prefix) ) corrected_words.append( self.syllabifier.convert_consonantal_i(word[len(prefix) :]) ) found = True break if not found: corrected_words.append(self.syllabifier.convert_consonantal_i(word)) new_line = string_utils.join_syllables_spaces(corrected_words, space_list) char_list = string_utils.overwrite( list(new_line), r"\b[iī][{}]".format( self.constants.VOWELS + self.constants.ACCENTED_VOWELS ), "j", ) char_list = string_utils.overwrite( char_list, r"\b[I][{}]".format(self.constants.VOWELS_WO_I), "J" ) char_list = string_utils.overwrite( char_list, r"[{}][i][{}]".format(self.constants.VOWELS_WO_I, self.constants.VOWELS), "j", 1, ) return "".join(char_list)
[ "def", "transform_i_to_j", "(", "self", ",", "line", ":", "str", ")", "->", "str", ":", "words", "=", "line", ".", "split", "(", "\" \"", ")", "space_list", "=", "string_utils", ".", "space_list", "(", "line", ")", "corrected_words", "=", "[", "]", "fo...
https://github.com/cltk/cltk/blob/1a8c2f5ef72389e2579dfce1fa5af8e59ebc9ec1/src/cltk/prosody/lat/verse_scanner.py#L61-L107
evilhero/mylar
dbee01d7e48e8c717afa01b2de1946c5d0b956cb
lib/transmissionrpc/client.py
python
Client.get_files
(self, ids=None, timeout=None)
return result
Get list of files for provided torrent id(s). If ids is empty, information for all torrents are fetched. This function returns a dictionary for each requested torrent id holding the information about the files. :: { <torrent id>: { <file id>: { 'name': <file name>, 'size': <file size in bytes>, 'completed': <bytes completed>, 'priority': <priority ('high'|'normal'|'low')>, 'selected': <selected for download (True|False)> } ... } ... }
Get list of files for provided torrent id(s). If ids is empty, information for all torrents are fetched. This function returns a dictionary for each requested torrent id holding the information about the files.
[ "Get", "list", "of", "files", "for", "provided", "torrent", "id", "(", "s", ")", ".", "If", "ids", "is", "empty", "information", "for", "all", "torrents", "are", "fetched", ".", "This", "function", "returns", "a", "dictionary", "for", "each", "requested", ...
def get_files(self, ids=None, timeout=None): """ Get list of files for provided torrent id(s). If ids is empty, information for all torrents are fetched. This function returns a dictionary for each requested torrent id holding the information about the files. :: { <torrent id>: { <file id>: { 'name': <file name>, 'size': <file size in bytes>, 'completed': <bytes completed>, 'priority': <priority ('high'|'normal'|'low')>, 'selected': <selected for download (True|False)> } ... } ... } """ fields = ['id', 'name', 'hashString', 'files', 'priorities', 'wanted'] request_result = self._request('torrent-get', {'fields': fields}, ids, timeout=timeout) result = {} for tid, torrent in iteritems(request_result): result[tid] = torrent.files() return result
[ "def", "get_files", "(", "self", ",", "ids", "=", "None", ",", "timeout", "=", "None", ")", ":", "fields", "=", "[", "'id'", ",", "'name'", ",", "'hashString'", ",", "'files'", ",", "'priorities'", ",", "'wanted'", "]", "request_result", "=", "self", "...
https://github.com/evilhero/mylar/blob/dbee01d7e48e8c717afa01b2de1946c5d0b956cb/lib/transmissionrpc/client.py#L610-L639
spack/spack
675210bd8bd1c5d32ad1cc83d898fb43b569ed74
lib/spack/external/jinja2/compiler.py
python
DependencyFinderVisitor.visit_Block
(self, node)
Stop visiting at blocks.
Stop visiting at blocks.
[ "Stop", "visiting", "at", "blocks", "." ]
def visit_Block(self, node): """Stop visiting at blocks."""
[ "def", "visit_Block", "(", "self", ",", "node", ")", ":" ]
https://github.com/spack/spack/blob/675210bd8bd1c5d32ad1cc83d898fb43b569ed74/lib/spack/external/jinja2/compiler.py#L214-L215
python-gino/gino
968e8da3e92dfc071390261e6ab7e274bf0c3268
src/gino/transaction.py
python
GinoTransaction.commit
(self)
Only available in manual mode: manually commit this transaction.
Only available in manual mode: manually commit this transaction.
[ "Only", "available", "in", "manual", "mode", ":", "manually", "commit", "this", "transaction", "." ]
async def commit(self): """ Only available in manual mode: manually commit this transaction. """ if self._managed: raise AssertionError( "Illegal in managed mode, " "use `raise_commit` instead." ) await self._tx.commit()
[ "async", "def", "commit", "(", "self", ")", ":", "if", "self", ".", "_managed", ":", "raise", "AssertionError", "(", "\"Illegal in managed mode, \"", "\"use `raise_commit` instead.\"", ")", "await", "self", ".", "_tx", ".", "commit", "(", ")" ]
https://github.com/python-gino/gino/blob/968e8da3e92dfc071390261e6ab7e274bf0c3268/src/gino/transaction.py#L121-L130
home-assistant/core
265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1
homeassistant/helpers/entity_registry.py
python
async_get_registry
(hass: HomeAssistant)
return async_get(hass)
Get entity registry. This is deprecated and will be removed in the future. Use async_get instead.
Get entity registry.
[ "Get", "entity", "registry", "." ]
async def async_get_registry(hass: HomeAssistant) -> EntityRegistry: """Get entity registry. This is deprecated and will be removed in the future. Use async_get instead. """ return async_get(hass)
[ "async", "def", "async_get_registry", "(", "hass", ":", "HomeAssistant", ")", "->", "EntityRegistry", ":", "return", "async_get", "(", "hass", ")" ]
https://github.com/home-assistant/core/blob/265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1/homeassistant/helpers/entity_registry.py#L677-L682
google/grr
8ad8a4d2c5a93c92729206b7771af19d92d4f915
grr/client/grr_response_client/streaming.py
python
MemoryReader.offset
(self)
return self._offset
[]
def offset(self): return self._offset
[ "def", "offset", "(", "self", ")", ":", "return", "self", ".", "_offset" ]
https://github.com/google/grr/blob/8ad8a4d2c5a93c92729206b7771af19d92d4f915/grr/client/grr_response_client/streaming.py#L277-L278
cloudera/hue
23f02102d4547c17c32bd5ea0eb24e9eadd657a4
desktop/core/ext-py/urllib3-1.25.8/src/urllib3/util/timeout.py
python
Timeout.get_connect_duration
(self)
return current_time() - self._start_connect
Gets the time elapsed since the call to :meth:`start_connect`. :return: Elapsed time in seconds. :rtype: float :raises urllib3.exceptions.TimeoutStateError: if you attempt to get duration for a timer that hasn't been started.
Gets the time elapsed since the call to :meth:`start_connect`.
[ "Gets", "the", "time", "elapsed", "since", "the", "call", "to", ":", "meth", ":", "start_connect", "." ]
def get_connect_duration(self): """ Gets the time elapsed since the call to :meth:`start_connect`. :return: Elapsed time in seconds. :rtype: float :raises urllib3.exceptions.TimeoutStateError: if you attempt to get duration for a timer that hasn't been started. """ if self._start_connect is None: raise TimeoutStateError( "Can't get connect duration for timer that has not started." ) return current_time() - self._start_connect
[ "def", "get_connect_duration", "(", "self", ")", ":", "if", "self", ".", "_start_connect", "is", "None", ":", "raise", "TimeoutStateError", "(", "\"Can't get connect duration for timer that has not started.\"", ")", "return", "current_time", "(", ")", "-", "self", "."...
https://github.com/cloudera/hue/blob/23f02102d4547c17c32bd5ea0eb24e9eadd657a4/desktop/core/ext-py/urllib3-1.25.8/src/urllib3/util/timeout.py#L196-L208
home-assistant/core
265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1
homeassistant/components/waze_travel_time/sensor.py
python
WazeTravelTime.__init__
(self, unique_id, name, origin, destination, waze_data)
Initialize the Waze travel time sensor.
Initialize the Waze travel time sensor.
[ "Initialize", "the", "Waze", "travel", "time", "sensor", "." ]
def __init__(self, unique_id, name, origin, destination, waze_data): """Initialize the Waze travel time sensor.""" self._attr_unique_id = unique_id self._waze_data = waze_data self._attr_name = name self._attr_icon = "mdi:car" self._state = None self._origin_entity_id = None self._destination_entity_id = None cmpl_re = re.compile(ENTITY_ID_PATTERN) if cmpl_re.fullmatch(origin): _LOGGER.debug("Found origin source entity %s", origin) self._origin_entity_id = origin else: self._waze_data.origin = origin if cmpl_re.fullmatch(destination): _LOGGER.debug("Found destination source entity %s", destination) self._destination_entity_id = destination else: self._waze_data.destination = destination
[ "def", "__init__", "(", "self", ",", "unique_id", ",", "name", ",", "origin", ",", "destination", ",", "waze_data", ")", ":", "self", ".", "_attr_unique_id", "=", "unique_id", "self", ".", "_waze_data", "=", "waze_data", "self", ".", "_attr_name", "=", "na...
https://github.com/home-assistant/core/blob/265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1/homeassistant/components/waze_travel_time/sensor.py#L117-L138
django-mptt/django-mptt
7a6a54c6d2572a45ea63bd639c25507108fff3e6
mptt/managers.py
python
TreeManager.disable_mptt_updates
(self)
Context manager. Disables mptt updates. NOTE that this context manager causes inconsistencies! MPTT model methods are not guaranteed to return the correct results. When to use this method: If used correctly, this method can be used to speed up bulk updates. This doesn't do anything clever. It *will* mess up your tree. You should follow this method with a call to ``TreeManager.rebuild()`` to ensure your tree stays sane, and you should wrap both calls in a transaction. This is best for updates that span a large part of the table. If you are doing localised changes (one tree, or a few trees) consider using ``delay_mptt_updates``. If you are making only minor changes to your tree, just let the updates happen. Transactions: This doesn't enforce any transactional behavior. You should wrap this in a transaction to ensure database consistency. If updates are already disabled on the model, this is a noop. Usage:: with transaction.atomic(): with MyNode.objects.disable_mptt_updates(): ## bulk updates. MyNode.objects.rebuild()
Context manager. Disables mptt updates.
[ "Context", "manager", ".", "Disables", "mptt", "updates", "." ]
def disable_mptt_updates(self): """ Context manager. Disables mptt updates. NOTE that this context manager causes inconsistencies! MPTT model methods are not guaranteed to return the correct results. When to use this method: If used correctly, this method can be used to speed up bulk updates. This doesn't do anything clever. It *will* mess up your tree. You should follow this method with a call to ``TreeManager.rebuild()`` to ensure your tree stays sane, and you should wrap both calls in a transaction. This is best for updates that span a large part of the table. If you are doing localised changes (one tree, or a few trees) consider using ``delay_mptt_updates``. If you are making only minor changes to your tree, just let the updates happen. Transactions: This doesn't enforce any transactional behavior. You should wrap this in a transaction to ensure database consistency. If updates are already disabled on the model, this is a noop. Usage:: with transaction.atomic(): with MyNode.objects.disable_mptt_updates(): ## bulk updates. MyNode.objects.rebuild() """ # Error cases: if self.model._meta.abstract: # an abstract model. Design decision needed - do we disable # updates for all concrete models that derive from this model? I # vote no - that's a bit implicit and it's a weird use-case # anyway. Open to further discussion :) raise CantDisableUpdates( "You can't disable/delay mptt updates on %s," " it's an abstract model" % self.model.__name__ ) elif self.model._meta.proxy: # a proxy model. disabling updates would implicitly affect other # models using the db table. Caller should call this on the # manager for the concrete model instead, to make the behavior # explicit. raise CantDisableUpdates( "You can't disable/delay mptt updates on %s, it's a proxy" " model. Call the concrete model instead." % self.model.__name__ ) elif self.tree_model is not self.model: # a multiple-inheritance child of an MPTTModel. Disabling # updates may affect instances of other models in the tree. raise CantDisableUpdates( "You can't disable/delay mptt updates on %s, it doesn't" " contain the mptt fields." % self.model.__name__ ) if not self.model._mptt_updates_enabled: # already disabled, noop. yield else: self.model._set_mptt_updates_enabled(False) try: yield finally: self.model._set_mptt_updates_enabled(True)
[ "def", "disable_mptt_updates", "(", "self", ")", ":", "# Error cases:", "if", "self", ".", "model", ".", "_meta", ".", "abstract", ":", "# an abstract model. Design decision needed - do we disable", "# updates for all concrete models that derive from this model? I", "# vote n...
https://github.com/django-mptt/django-mptt/blob/7a6a54c6d2572a45ea63bd639c25507108fff3e6/mptt/managers.py#L213-L284
espnet/espnet
ea411f3f627b8f101c211e107d0ff7053344ac80
espnet2/asr/encoder/conformer_encoder.py
python
ConformerEncoder.forward
( self, xs_pad: torch.Tensor, ilens: torch.Tensor, prev_states: torch.Tensor = None, )
return xs_pad, olens, None
Calculate forward propagation. Args: xs_pad (torch.Tensor): Input tensor (#batch, L, input_size). ilens (torch.Tensor): Input length (#batch). prev_states (torch.Tensor): Not to be used now. Returns: torch.Tensor: Output tensor (#batch, L, output_size). torch.Tensor: Output length (#batch). torch.Tensor: Not to be used now.
Calculate forward propagation.
[ "Calculate", "forward", "propagation", "." ]
def forward( self, xs_pad: torch.Tensor, ilens: torch.Tensor, prev_states: torch.Tensor = None, ) -> Tuple[torch.Tensor, torch.Tensor, Optional[torch.Tensor]]: """Calculate forward propagation. Args: xs_pad (torch.Tensor): Input tensor (#batch, L, input_size). ilens (torch.Tensor): Input length (#batch). prev_states (torch.Tensor): Not to be used now. Returns: torch.Tensor: Output tensor (#batch, L, output_size). torch.Tensor: Output length (#batch). torch.Tensor: Not to be used now. """ masks = (~make_pad_mask(ilens)[:, None, :]).to(xs_pad.device) if ( isinstance(self.embed, Conv2dSubsampling) or isinstance(self.embed, Conv2dSubsampling2) or isinstance(self.embed, Conv2dSubsampling6) or isinstance(self.embed, Conv2dSubsampling8) ): short_status, limit_size = check_short_utt(self.embed, xs_pad.size(1)) if short_status: raise TooShortUttError( f"has {xs_pad.size(1)} frames and is too short for subsampling " + f"(it needs more than {limit_size} frames), return empty results", xs_pad.size(1), limit_size, ) xs_pad, masks = self.embed(xs_pad, masks) else: xs_pad = self.embed(xs_pad) xs_pad, masks = self.encoders(xs_pad, masks) if isinstance(xs_pad, tuple): xs_pad = xs_pad[0] if self.normalize_before: xs_pad = self.after_norm(xs_pad) olens = masks.squeeze(1).sum(1) return xs_pad, olens, None
[ "def", "forward", "(", "self", ",", "xs_pad", ":", "torch", ".", "Tensor", ",", "ilens", ":", "torch", ".", "Tensor", ",", "prev_states", ":", "torch", ".", "Tensor", "=", "None", ",", ")", "->", "Tuple", "[", "torch", ".", "Tensor", ",", "torch", ...
https://github.com/espnet/espnet/blob/ea411f3f627b8f101c211e107d0ff7053344ac80/espnet2/asr/encoder/conformer_encoder.py#L268-L313
huanghoujing/AlignedReID-Re-Production-Pytorch
2e2d45450d69a3a81e15d18fe85c2eebbde742e4
aligned_reid/utils/utils.py
python
to_scalar
(vt)
Transform a length-1 pytorch Variable or Tensor to scalar. Suppose tx is a torch Tensor with shape tx.size() = torch.Size([1]), then npx = tx.cpu().numpy() has shape (1,), not 1.
Transform a length-1 pytorch Variable or Tensor to scalar. Suppose tx is a torch Tensor with shape tx.size() = torch.Size([1]), then npx = tx.cpu().numpy() has shape (1,), not 1.
[ "Transform", "a", "length", "-", "1", "pytorch", "Variable", "or", "Tensor", "to", "scalar", ".", "Suppose", "tx", "is", "a", "torch", "Tensor", "with", "shape", "tx", ".", "size", "()", "=", "torch", ".", "Size", "(", "[", "1", "]", ")", "then", "...
def to_scalar(vt): """Transform a length-1 pytorch Variable or Tensor to scalar. Suppose tx is a torch Tensor with shape tx.size() = torch.Size([1]), then npx = tx.cpu().numpy() has shape (1,), not 1.""" if isinstance(vt, Variable): return vt.data.cpu().numpy().flatten()[0] if torch.is_tensor(vt): return vt.cpu().numpy().flatten()[0] raise TypeError('Input should be a variable or tensor')
[ "def", "to_scalar", "(", "vt", ")", ":", "if", "isinstance", "(", "vt", ",", "Variable", ")", ":", "return", "vt", ".", "data", ".", "cpu", "(", ")", ".", "numpy", "(", ")", ".", "flatten", "(", ")", "[", "0", "]", "if", "torch", ".", "is_tenso...
https://github.com/huanghoujing/AlignedReID-Re-Production-Pytorch/blob/2e2d45450d69a3a81e15d18fe85c2eebbde742e4/aligned_reid/utils/utils.py#L44-L52
freewizard/SublimeFormatSQL
88771e4b77ab186a09560b495294d11c29cd878c
sqlparse/lexer.py
python
combined.__new__
(cls, *args)
return tuple.__new__(cls, args)
[]
def __new__(cls, *args): return tuple.__new__(cls, args)
[ "def", "__new__", "(", "cls", ",", "*", "args", ")", ":", "return", "tuple", ".", "__new__", "(", "cls", ",", "args", ")" ]
https://github.com/freewizard/SublimeFormatSQL/blob/88771e4b77ab186a09560b495294d11c29cd878c/sqlparse/lexer.py#L29-L30
HackerShackOfficial/Tracking-Turret
2d80171c82c88e13d15276b1ef18e6301ad9540a
turret.py
python
Turret.interactive
(self)
Starts an interactive session. Key presses determine movement. :return:
Starts an interactive session. Key presses determine movement. :return:
[ "Starts", "an", "interactive", "session", ".", "Key", "presses", "determine", "movement", ".", ":", "return", ":" ]
def interactive(self): """ Starts an interactive session. Key presses determine movement. :return: """ Turret.move_forward(self.sm_x, 1) Turret.move_forward(self.sm_y, 1) print 'Commands: Pivot with (a) and (d). Tilt with (w) and (s). Exit with (q)\n' with raw_mode(sys.stdin): try: while True: ch = sys.stdin.read(1) if not ch or ch == "q": break if ch == "w": if MOTOR_Y_REVERSED: Turret.move_forward(self.sm_y, 5) else: Turret.move_backward(self.sm_y, 5) elif ch == "s": if MOTOR_Y_REVERSED: Turret.move_backward(self.sm_y, 5) else: Turret.move_forward(self.sm_y, 5) elif ch == "a": if MOTOR_X_REVERSED: Turret.move_backward(self.sm_x, 5) else: Turret.move_forward(self.sm_x, 5) elif ch == "d": if MOTOR_X_REVERSED: Turret.move_forward(self.sm_x, 5) else: Turret.move_backward(self.sm_x, 5) elif ch == "\n": Turret.fire() except (KeyboardInterrupt, EOFError): pass
[ "def", "interactive", "(", "self", ")", ":", "Turret", ".", "move_forward", "(", "self", ".", "sm_x", ",", "1", ")", "Turret", ".", "move_forward", "(", "self", ".", "sm_y", ",", "1", ")", "print", "'Commands: Pivot with (a) and (d). Tilt with (w) and (s). Exit ...
https://github.com/HackerShackOfficial/Tracking-Turret/blob/2d80171c82c88e13d15276b1ef18e6301ad9540a/turret.py#L331-L372
sagemath/sage
f9b2db94f675ff16963ccdefba4f1a3393b3fe0d
src/sage/schemes/elliptic_curves/ell_point.py
python
EllipticCurvePoint_finite_field.discrete_log
(self, Q, ord=None)
r""" Returns discrete log of `Q` with respect to `P` =self. INPUT: - ``Q`` (point) -- another point on the same curve as self. - ``ord`` (integer or ``None`` (default)) -- the order of self. OUTPUT: (integer) -- The discrete log of `Q` with respect to `P`, which is an integer `m` with `0\le m<o(P)` such that `mP=Q`, if one exists. A ValueError is raised if there is no solution. .. NOTE:: The order of self is computed if not supplied. AUTHOR: - John Cremona. Adapted to use generic functions 2008-04-05. EXAMPLES:: sage: F = GF((3,6),'a') sage: a = F.gen() sage: E = EllipticCurve([0,1,1,a,a]) sage: E.cardinality() 762 sage: A = E.abelian_group() sage: P = A.gen(0).element() sage: Q = 400*P sage: P.discrete_log(Q) 400
r""" Returns discrete log of `Q` with respect to `P` =self.
[ "r", "Returns", "discrete", "log", "of", "Q", "with", "respect", "to", "P", "=", "self", "." ]
def discrete_log(self, Q, ord=None): r""" Returns discrete log of `Q` with respect to `P` =self. INPUT: - ``Q`` (point) -- another point on the same curve as self. - ``ord`` (integer or ``None`` (default)) -- the order of self. OUTPUT: (integer) -- The discrete log of `Q` with respect to `P`, which is an integer `m` with `0\le m<o(P)` such that `mP=Q`, if one exists. A ValueError is raised if there is no solution. .. NOTE:: The order of self is computed if not supplied. AUTHOR: - John Cremona. Adapted to use generic functions 2008-04-05. EXAMPLES:: sage: F = GF((3,6),'a') sage: a = F.gen() sage: E = EllipticCurve([0,1,1,a,a]) sage: E.cardinality() 762 sage: A = E.abelian_group() sage: P = A.gen(0).element() sage: Q = 400*P sage: P.discrete_log(Q) 400 """ if ord is None: ord = self.order() try: return generic.discrete_log(Q, self, ord, operation='+') except Exception: raise ValueError("ECDLog problem has no solution")
[ "def", "discrete_log", "(", "self", ",", "Q", ",", "ord", "=", "None", ")", ":", "if", "ord", "is", "None", ":", "ord", "=", "self", ".", "order", "(", ")", "try", ":", "return", "generic", ".", "discrete_log", "(", "Q", ",", "self", ",", "ord", ...
https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/schemes/elliptic_curves/ell_point.py#L3441-L3483
hatRiot/zarp
2e772350a01c2aeed3f4da9685cd0cc5d6b3ecad
src/lib/scapy/crypto/cert.py
python
CRL.verify
(self, anchors)
return "verify OK" in cmdres
Return True if the CRL is signed by one of the provided anchors. False on error (invalid signature, missing anchorand, ...)
Return True if the CRL is signed by one of the provided anchors. False on error (invalid signature, missing anchorand, ...)
[ "Return", "True", "if", "the", "CRL", "is", "signed", "by", "one", "of", "the", "provided", "anchors", ".", "False", "on", "error", "(", "invalid", "signature", "missing", "anchorand", "...", ")" ]
def verify(self, anchors): """ Return True if the CRL is signed by one of the provided anchors. False on error (invalid signature, missing anchorand, ...) """ cafile = create_temporary_ca_file(anchors) if cafile is None: return False try: cmd = self.osslcmdbase + '-noout -CAfile %s 2>&1' % cafile cmdres = self._apply_ossl_cmd(cmd, self.rawcrl) except: os.unlink(cafile) return False os.unlink(cafile) return "verify OK" in cmdres
[ "def", "verify", "(", "self", ",", "anchors", ")", ":", "cafile", "=", "create_temporary_ca_file", "(", "anchors", ")", "if", "cafile", "is", "None", ":", "return", "False", "try", ":", "cmd", "=", "self", ".", "osslcmdbase", "+", "'-noout -CAfile %s 2>&1'",...
https://github.com/hatRiot/zarp/blob/2e772350a01c2aeed3f4da9685cd0cc5d6b3ecad/src/lib/scapy/crypto/cert.py#L2451-L2466
GeoStat-Framework/PyKrige
f5b39204b18a552f5f162a3c07caeec78c2b8520
pykrige/ok3d.py
python
OrdinaryKriging3D.switch_verbose
(self)
Allows user to switch code talk-back on/off. Takes no arguments.
Allows user to switch code talk-back on/off. Takes no arguments.
[ "Allows", "user", "to", "switch", "code", "talk", "-", "back", "on", "/", "off", ".", "Takes", "no", "arguments", "." ]
def switch_verbose(self): """Allows user to switch code talk-back on/off. Takes no arguments.""" self.verbose = not self.verbose
[ "def", "switch_verbose", "(", "self", ")", ":", "self", ".", "verbose", "=", "not", "self", ".", "verbose" ]
https://github.com/GeoStat-Framework/PyKrige/blob/f5b39204b18a552f5f162a3c07caeec78c2b8520/pykrige/ok3d.py#L563-L565
spyder-ide/spyder
55da47c032dfcf519600f67f8b30eab467f965e7
spyder/plugins/editor/widgets/status.py
python
VCSStatus.get_tooltip
(self)
return _("Git branch")
Return localized tool tip for widget.
Return localized tool tip for widget.
[ "Return", "localized", "tool", "tip", "for", "widget", "." ]
def get_tooltip(self): """Return localized tool tip for widget.""" return _("Git branch")
[ "def", "get_tooltip", "(", "self", ")", ":", "return", "_", "(", "\"Git branch\"", ")" ]
https://github.com/spyder-ide/spyder/blob/55da47c032dfcf519600f67f8b30eab467f965e7/spyder/plugins/editor/widgets/status.py#L136-L138
INK-USC/KagNet
b386661ac5841774b9d17cc132e991a7bef3c5ef
baselines/extract_csqa_bert.py
python
SwagExample.__init__
(self, swag_id, context_sentence, start_ending, ending_0, ending_1, ending_2, ending_3, ending_4, label=None)
[]
def __init__(self, swag_id, context_sentence, start_ending, ending_0, ending_1, ending_2, ending_3, ending_4, label=None): self.swag_id = swag_id self.context_sentence = context_sentence self.start_ending = start_ending self.endings = [ ending_0, ending_1, ending_2, ending_3, ending_4, ] self.label = label
[ "def", "__init__", "(", "self", ",", "swag_id", ",", "context_sentence", ",", "start_ending", ",", "ending_0", ",", "ending_1", ",", "ending_2", ",", "ending_3", ",", "ending_4", ",", "label", "=", "None", ")", ":", "self", ".", "swag_id", "=", "swag_id", ...
https://github.com/INK-USC/KagNet/blob/b386661ac5841774b9d17cc132e991a7bef3c5ef/baselines/extract_csqa_bert.py#L34-L54
exodrifter/unity-python
bef6e4e9ddfbbf1eaf7acbbb973e9aa3dd64a20d
Lib/multiprocessing/__init__.py
python
freeze_support
()
Check whether this is a fake forked process in a frozen executable. If so then run code specified by commandline and exit.
Check whether this is a fake forked process in a frozen executable. If so then run code specified by commandline and exit.
[ "Check", "whether", "this", "is", "a", "fake", "forked", "process", "in", "a", "frozen", "executable", ".", "If", "so", "then", "run", "code", "specified", "by", "commandline", "and", "exit", "." ]
def freeze_support(): ''' Check whether this is a fake forked process in a frozen executable. If so then run code specified by commandline and exit. ''' if sys.platform == 'win32' and getattr(sys, 'frozen', False): from multiprocessing.forking import freeze_support freeze_support()
[ "def", "freeze_support", "(", ")", ":", "if", "sys", ".", "platform", "==", "'win32'", "and", "getattr", "(", "sys", ",", "'frozen'", ",", "False", ")", ":", "from", "multiprocessing", ".", "forking", "import", "freeze_support", "freeze_support", "(", ")" ]
https://github.com/exodrifter/unity-python/blob/bef6e4e9ddfbbf1eaf7acbbb973e9aa3dd64a20d/Lib/multiprocessing/__init__.py#L142-L149
nerdvegas/rez
d392c65bf63b4bca8106f938cec49144ba54e770
src/rez/vendor/pika/channel.py
python
Channel.open
(self)
Open the channel
Open the channel
[ "Open", "the", "channel" ]
def open(self): """Open the channel""" self._set_state(self.OPENING) self._add_callbacks() self._rpc(spec.Channel.Open(), self._on_openok, [spec.Channel.OpenOk])
[ "def", "open", "(", "self", ")", ":", "self", ".", "_set_state", "(", "self", ".", "OPENING", ")", "self", ".", "_add_callbacks", "(", ")", "self", ".", "_rpc", "(", "spec", ".", "Channel", ".", "Open", "(", ")", ",", "self", ".", "_on_openok", ","...
https://github.com/nerdvegas/rez/blob/d392c65bf63b4bca8106f938cec49144ba54e770/src/rez/vendor/pika/channel.py#L755-L759
Eniac-Xie/faster-rcnn-resnet
aba743e8404b47fc9bcccba4920846d1068c7e3c
tools/demo.py
python
demo
(net, image_name)
Detect object classes in an image using pre-computed object proposals.
Detect object classes in an image using pre-computed object proposals.
[ "Detect", "object", "classes", "in", "an", "image", "using", "pre", "-", "computed", "object", "proposals", "." ]
def demo(net, image_name): """Detect object classes in an image using pre-computed object proposals.""" # Load the demo image im_file = os.path.join(cfg.DATA_DIR, 'demo', image_name) im = cv2.imread(im_file) # Detect all object classes and regress object bounds timer = Timer() timer.tic() scores, boxes = im_detect(net, im) timer.toc() print ('Detection took {:.3f}s for ' '{:d} object proposals').format(timer.total_time, boxes.shape[0]) # Visualize detections for each class CONF_THRESH = 0.8 NMS_THRESH = 0.3 for cls_ind, cls in enumerate(CLASSES[1:]): cls_ind += 1 # because we skipped background cls_boxes = boxes[:, 4*cls_ind:4*(cls_ind + 1)] cls_scores = scores[:, cls_ind] dets = np.hstack((cls_boxes, cls_scores[:, np.newaxis])).astype(np.float32) keep = nms(dets, NMS_THRESH) dets = dets[keep, :] vis_detections(im, cls, dets, thresh=CONF_THRESH)
[ "def", "demo", "(", "net", ",", "image_name", ")", ":", "# Load the demo image", "im_file", "=", "os", ".", "path", ".", "join", "(", "cfg", ".", "DATA_DIR", ",", "'demo'", ",", "image_name", ")", "im", "=", "cv2", ".", "imread", "(", "im_file", ")", ...
https://github.com/Eniac-Xie/faster-rcnn-resnet/blob/aba743e8404b47fc9bcccba4920846d1068c7e3c/tools/demo.py#L72-L98
ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework
cb692f527e4e819b6c228187c5702d990a180043
bin/x86/Debug/scripting_engine/Lib/sysconfig.py
python
get_config_var
(name)
return get_config_vars().get(name)
Return the value of a single variable using the dictionary returned by 'get_config_vars()'. Equivalent to get_config_vars().get(name)
Return the value of a single variable using the dictionary returned by 'get_config_vars()'.
[ "Return", "the", "value", "of", "a", "single", "variable", "using", "the", "dictionary", "returned", "by", "get_config_vars", "()", "." ]
def get_config_var(name): """Return the value of a single variable using the dictionary returned by 'get_config_vars()'. Equivalent to get_config_vars().get(name) """ return get_config_vars().get(name)
[ "def", "get_config_var", "(", "name", ")", ":", "return", "get_config_vars", "(", ")", ".", "get", "(", "name", ")" ]
https://github.com/ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework/blob/cb692f527e4e819b6c228187c5702d990a180043/bin/x86/Debug/scripting_engine/Lib/sysconfig.py#L516-L522
Yelp/kafka-utils
74831206648512db1a29426c6ebb428b33820d04
kafka_utils/kafka_corruption_check/main.py
python
ssh_client
(host)
return ssh
Start an ssh client. :param host: the host :type host: str :returns: ssh client :rtype: Paramiko client
Start an ssh client.
[ "Start", "an", "ssh", "client", "." ]
def ssh_client(host): """Start an ssh client. :param host: the host :type host: str :returns: ssh client :rtype: Paramiko client """ ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(host) return ssh
[ "def", "ssh_client", "(", "host", ")", ":", "ssh", "=", "paramiko", ".", "SSHClient", "(", ")", "ssh", ".", "set_missing_host_key_policy", "(", "paramiko", ".", "AutoAddPolicy", "(", ")", ")", "ssh", ".", "connect", "(", "host", ")", "return", "ssh" ]
https://github.com/Yelp/kafka-utils/blob/74831206648512db1a29426c6ebb428b33820d04/kafka_utils/kafka_corruption_check/main.py#L58-L69
bachya/smart-home
536b989e0d7057c7a8a65b2ac9bbffd4b826cce7
hass/settings/custom_components/hacs/helpers/functions/store.py
python
async_load_from_store
(hass, key)
return await get_store_for_key(hass, key).async_load() or {}
Load the retained data from store and return de-serialized data.
Load the retained data from store and return de-serialized data.
[ "Load", "the", "retained", "data", "from", "store", "and", "return", "de", "-", "serialized", "data", "." ]
async def async_load_from_store(hass, key): """Load the retained data from store and return de-serialized data.""" return await get_store_for_key(hass, key).async_load() or {}
[ "async", "def", "async_load_from_store", "(", "hass", ",", "key", ")", ":", "return", "await", "get_store_for_key", "(", "hass", ",", "key", ")", ".", "async_load", "(", ")", "or", "{", "}" ]
https://github.com/bachya/smart-home/blob/536b989e0d7057c7a8a65b2ac9bbffd4b826cce7/hass/settings/custom_components/hacs/helpers/functions/store.py#L40-L42
buke/GreenOdoo
3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df
runtime/python/lib/python2.7/site-packages/_xmlplus/parsers/xmlproc/xmldtd.py
python
ElementType.get_content_model
(self)
return self.content_model_structure
Returns the element content model in (sep,cont,mod) format, where cont is a list of (name,mod) and (sep,cont,mod) tuples. ANY content models are represented as None, and EMPTYs as ("",[],"").
Returns the element content model in (sep,cont,mod) format, where cont is a list of (name,mod) and (sep,cont,mod) tuples. ANY content models are represented as None, and EMPTYs as ("",[],"").
[ "Returns", "the", "element", "content", "model", "in", "(", "sep", "cont", "mod", ")", "format", "where", "cont", "is", "a", "list", "of", "(", "name", "mod", ")", "and", "(", "sep", "cont", "mod", ")", "tuples", ".", "ANY", "content", "models", "are...
def get_content_model(self): """Returns the element content model in (sep,cont,mod) format, where cont is a list of (name,mod) and (sep,cont,mod) tuples. ANY content models are represented as None, and EMPTYs as ("",[],"").""" return self.content_model_structure
[ "def", "get_content_model", "(", "self", ")", ":", "return", "self", ".", "content_model_structure" ]
https://github.com/buke/GreenOdoo/blob/3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df/runtime/python/lib/python2.7/site-packages/_xmlplus/parsers/xmlproc/xmldtd.py#L356-L360
mozilla/elasticutils
b880cc5d51fb1079b0581255ec664c1ec934656e
elasticutils/contrib/django/__init__.py
python
MappingType.search
(cls)
return S(cls)
Returns a typed S for this class. :returns: an `S` for this DjangoMappingType
Returns a typed S for this class.
[ "Returns", "a", "typed", "S", "for", "this", "class", "." ]
def search(cls): """Returns a typed S for this class. :returns: an `S` for this DjangoMappingType """ return S(cls)
[ "def", "search", "(", "cls", ")", ":", "return", "S", "(", "cls", ")" ]
https://github.com/mozilla/elasticutils/blob/b880cc5d51fb1079b0581255ec664c1ec934656e/elasticutils/contrib/django/__init__.py#L265-L271
MingtaoFu/gliding_vertex
c4470140265140e118725b80a81efe68e44e10af
maskrcnn_benchmark/utils/comm.py
python
synchronize
()
Helper function to synchronize (barrier) among all processes when using distributed training
Helper function to synchronize (barrier) among all processes when using distributed training
[ "Helper", "function", "to", "synchronize", "(", "barrier", ")", "among", "all", "processes", "when", "using", "distributed", "training" ]
def synchronize(): """ Helper function to synchronize (barrier) among all processes when using distributed training """ if not dist.is_available(): return if not dist.is_initialized(): return world_size = dist.get_world_size() if world_size == 1: return dist.barrier()
[ "def", "synchronize", "(", ")", ":", "if", "not", "dist", ".", "is_available", "(", ")", ":", "return", "if", "not", "dist", ".", "is_initialized", "(", ")", ":", "return", "world_size", "=", "dist", ".", "get_world_size", "(", ")", "if", "world_size", ...
https://github.com/MingtaoFu/gliding_vertex/blob/c4470140265140e118725b80a81efe68e44e10af/maskrcnn_benchmark/utils/comm.py#L33-L45
tendenci/tendenci
0f2c348cc0e7d41bc56f50b00ce05544b083bf1d
tendenci/apps/memberships/management/commands/clean_memberships.py
python
Command.handle
(self, *args, **kwargs)
[]
def handle(self, *args, **kwargs): from datetime import datetime from dateutil.relativedelta import relativedelta from tendenci.apps.profiles.models import Profile from tendenci.apps.memberships.models import MembershipDefault, MembershipType from tendenci.apps.user_groups.models import GroupMembership for membership_type in MembershipType.objects.all(): grace_period = membership_type.expiration_grace_period # get expired memberships out of grace period # we can't move the expiration date, but we can # move todays day back. memberships = MembershipDefault.objects.filter( membership_type=membership_type, expire_dt__lt=datetime.now() - relativedelta(days=grace_period), status=True).filter(status_detail='active') for membership in memberships: membership.status_detail = 'expired' membership.save() # update profile # added try-except block due to error encountered # on a site that might also be replicated tendenci wide try: membership.user.profile.refresh_member_number() except Profile.DoesNotExist: pass # remove from group GroupMembership.objects.filter( member=membership.user, group=membership.membership_type.group ).delete() # Check directory and set to inactive if membership.directory: membership.directory.status_detail = 'inactive' membership.directory.save()
[ "def", "handle", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "from", "datetime", "import", "datetime", "from", "dateutil", ".", "relativedelta", "import", "relativedelta", "from", "tendenci", ".", "apps", ".", "profiles", ".", "models...
https://github.com/tendenci/tendenci/blob/0f2c348cc0e7d41bc56f50b00ce05544b083bf1d/tendenci/apps/memberships/management/commands/clean_memberships.py#L10-L49
nooperpudd/ctpwrapper
8ea7b7c4ab913fea971b756556d5c18c7a194414
ctpwrapper/Md.py
python
MdApiPy.OnRspUnSubMarketData
(self, pSpecificInstrument, pRspInfo, nRequestID, bIsLast)
取消订阅行情应答 :param pSpecificInstrument: :param pRspInfo: :param nRequestID: :param bIsLast: :return:
取消订阅行情应答 :param pSpecificInstrument: :param pRspInfo: :param nRequestID: :param bIsLast: :return:
[ "取消订阅行情应答", ":", "param", "pSpecificInstrument", ":", ":", "param", "pRspInfo", ":", ":", "param", "nRequestID", ":", ":", "param", "bIsLast", ":", ":", "return", ":" ]
def OnRspUnSubMarketData(self, pSpecificInstrument, pRspInfo, nRequestID, bIsLast) -> None: """ 取消订阅行情应答 :param pSpecificInstrument: :param pRspInfo: :param nRequestID: :param bIsLast: :return: """ pass
[ "def", "OnRspUnSubMarketData", "(", "self", ",", "pSpecificInstrument", ",", "pRspInfo", ",", "nRequestID", ",", "bIsLast", ")", "->", "None", ":", "pass" ]
https://github.com/nooperpudd/ctpwrapper/blob/8ea7b7c4ab913fea971b756556d5c18c7a194414/ctpwrapper/Md.py#L238-L247
andrewf/pcap2har
b13c49ee91c4c4933f18c8fe38d5bffe6c82fd4e
pcap2har/mediatype.py
python
MediaType.__init__
(self, data)
Args: data = string, the media type string
Args: data = string, the media type string
[ "Args", ":", "data", "=", "string", "the", "media", "type", "string" ]
def __init__(self, data): ''' Args: data = string, the media type string ''' if not data: logging.warning( 'Setting empty media type to x-unknown-content-type') self.set_unknown() return match = self.mediatype_re.match(data) if match: # get type/subtype self.type = match.group(1).lower() self.subtype = match.group(2).lower() # params self.params = {} param_str = match.group(3) # we know this is well-formed, except for extra whitespace for pair in param_str.split(';'): pair = pair.strip() if pair: pairmatch = self.nvpair_re.match(pair) if not pairmatch: raise Exception('MediaType.__init__: invalid pair: "' + pair + '"') self.params[pairmatch.group(1)] = pairmatch.group(2) pass else: logging.warning('Invalid media type string: "%s"' % data) self.set_unknown()
[ "def", "__init__", "(", "self", ",", "data", ")", ":", "if", "not", "data", ":", "logging", ".", "warning", "(", "'Setting empty media type to x-unknown-content-type'", ")", "self", ".", "set_unknown", "(", ")", "return", "match", "=", "self", ".", "mediatype_...
https://github.com/andrewf/pcap2har/blob/b13c49ee91c4c4933f18c8fe38d5bffe6c82fd4e/pcap2har/mediatype.py#L27-L54
dimagi/commcare-hq
d67ff1d3b4c51fa050c19e60c3253a79d3452a39
corehq/util/bounced_email_manager.py
python
BouncedEmailManager.logout
(self)
[]
def logout(self): self.mail.close() self.mail.logout()
[ "def", "logout", "(", "self", ")", ":", "self", ".", "mail", ".", "close", "(", ")", "self", ".", "mail", ".", "logout", "(", ")" ]
https://github.com/dimagi/commcare-hq/blob/d67ff1d3b4c51fa050c19e60c3253a79d3452a39/corehq/util/bounced_email_manager.py#L337-L339
JiYou/openstack
8607dd488bde0905044b303eb6e52bdea6806923
packages/source/cinder/cinder/api/xmlutil.py
python
Template.serialize
(self, obj, *args, **kwargs)
return etree.tostring(elem, *args, **kwargs)
Serialize an object. Serializes an object against the template. Returns a string with the serialized XML. Positional and keyword arguments are passed to etree.tostring(). :param obj: The object to serialize.
Serialize an object.
[ "Serialize", "an", "object", "." ]
def serialize(self, obj, *args, **kwargs): """Serialize an object. Serializes an object against the template. Returns a string with the serialized XML. Positional and keyword arguments are passed to etree.tostring(). :param obj: The object to serialize. """ elem = self.make_tree(obj) if elem is None: return '' for k, v in self.serialize_options.items(): kwargs.setdefault(k, v) # Serialize it into XML return etree.tostring(elem, *args, **kwargs)
[ "def", "serialize", "(", "self", ",", "obj", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "elem", "=", "self", ".", "make_tree", "(", "obj", ")", "if", "elem", "is", "None", ":", "return", "''", "for", "k", ",", "v", "in", "self", ".", ...
https://github.com/JiYou/openstack/blob/8607dd488bde0905044b303eb6e52bdea6806923/packages/source/cinder/cinder/api/xmlutil.py#L578-L596
suavecode/SUAVE
4f83c467c5662b6cc611ce2ab6c0bdd25fd5c0a5
trunk/SUAVE/Components/Energy/Converters/Motor_Lo_Fid.py
python
Motor_Lo_Fid.current
(self,conditions)
return i
Calculates the motor's rotation rate Assumptions: Cp (power coefficient) is constant Source: N/A Inputs: self.inputs.voltage [V] Outputs: self.outputs.current [A] conditions. propulsion.etam [-] i [A] Properties Used: self. gear_ratio [-] speed_constant [radian/s/V] resistance [ohm] omega(conditions) [radian/s] (calls the function) gearbox_efficiency [-] expected_current [A] no_load_current [A]
Calculates the motor's rotation rate Assumptions: Cp (power coefficient) is constant Source: N/A Inputs: self.inputs.voltage [V] Outputs: self.outputs.current [A] conditions. propulsion.etam [-] i [A] Properties Used: self. gear_ratio [-] speed_constant [radian/s/V] resistance [ohm] omega(conditions) [radian/s] (calls the function) gearbox_efficiency [-] expected_current [A] no_load_current [A]
[ "Calculates", "the", "motor", "s", "rotation", "rate", "Assumptions", ":", "Cp", "(", "power", "coefficient", ")", "is", "constant", "Source", ":", "N", "/", "A", "Inputs", ":", "self", ".", "inputs", ".", "voltage", "[", "V", "]", "Outputs", ":", "sel...
def current(self,conditions): """Calculates the motor's rotation rate Assumptions: Cp (power coefficient) is constant Source: N/A Inputs: self.inputs.voltage [V] Outputs: self.outputs.current [A] conditions. propulsion.etam [-] i [A] Properties Used: self. gear_ratio [-] speed_constant [radian/s/V] resistance [ohm] omega(conditions) [radian/s] (calls the function) gearbox_efficiency [-] expected_current [A] no_load_current [A] """ # Unpack G = self.gear_ratio Kv = self.speed_constant Res = self.resistance v = self.inputs.voltage omeg = self.omega(conditions)*G etaG = self.gearbox_efficiency exp_i = self.expected_current io = self.no_load_current + exp_i*(1-etaG) i=(v-omeg/Kv)/Res # This line means the motor cannot recharge the battery i[i < 0.0] = 0.0 # Pack self.outputs.current = i etam=(1-io/i)*(1-i*Res/v) conditions.propulsion.etam = etam return i
[ "def", "current", "(", "self", ",", "conditions", ")", ":", "# Unpack", "G", "=", "self", ".", "gear_ratio", "Kv", "=", "self", ".", "speed_constant", "Res", "=", "self", ".", "resistance", "v", "=", "self", ".", "inputs", ".", "voltage", "omeg", "=", ...
https://github.com/suavecode/SUAVE/blob/4f83c467c5662b6cc611ce2ab6c0bdd25fd5c0a5/trunk/SUAVE/Components/Energy/Converters/Motor_Lo_Fid.py#L122-L172
Blueqat/Blueqat
b676f30489b71767419fd20503403d290d4950b5
blueqat/gate.py
python
CCZGate.n_qargs
(self)
return 3
[]
def n_qargs(self): return 3
[ "def", "n_qargs", "(", "self", ")", ":", "return", "3" ]
https://github.com/Blueqat/Blueqat/blob/b676f30489b71767419fd20503403d290d4950b5/blueqat/gate.py#L646-L647
TencentCloud/tencentcloud-sdk-python
3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2
tencentcloud/ecm/v20190719/models.py
python
ReplaceRouteTableAssociationRequest.__init__
(self)
r""" :param SubnetId: 子网实例ID,例如:subnet-3x5lf5q0。可通过DescribeSubnets接口查询。 :type SubnetId: str :param RouteTableId: 路由表实例ID,例如:rtb-azd4dt1c。 :type RouteTableId: str :param EcmRegion: ECM 地域 :type EcmRegion: str
r""" :param SubnetId: 子网实例ID,例如:subnet-3x5lf5q0。可通过DescribeSubnets接口查询。 :type SubnetId: str :param RouteTableId: 路由表实例ID,例如:rtb-azd4dt1c。 :type RouteTableId: str :param EcmRegion: ECM 地域 :type EcmRegion: str
[ "r", ":", "param", "SubnetId", ":", "子网实例ID,例如:subnet", "-", "3x5lf5q0。可通过DescribeSubnets接口查询。", ":", "type", "SubnetId", ":", "str", ":", "param", "RouteTableId", ":", "路由表实例ID,例如:rtb", "-", "azd4dt1c。", ":", "type", "RouteTableId", ":", "str", ":", "param", "E...
def __init__(self): r""" :param SubnetId: 子网实例ID,例如:subnet-3x5lf5q0。可通过DescribeSubnets接口查询。 :type SubnetId: str :param RouteTableId: 路由表实例ID,例如:rtb-azd4dt1c。 :type RouteTableId: str :param EcmRegion: ECM 地域 :type EcmRegion: str """ self.SubnetId = None self.RouteTableId = None self.EcmRegion = None
[ "def", "__init__", "(", "self", ")", ":", "self", ".", "SubnetId", "=", "None", "self", ".", "RouteTableId", "=", "None", "self", ".", "EcmRegion", "=", "None" ]
https://github.com/TencentCloud/tencentcloud-sdk-python/blob/3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2/tencentcloud/ecm/v20190719/models.py#L10225-L10236
pwnieexpress/pwn_plug_sources
1a23324f5dc2c3de20f9c810269b6a29b2758cad
src/voiper/sulley/vmcontrol.py
python
vmcontrol_pedrpc_server.start
(self)
return self.vmcommand(command)
[]
def start (self): self.log("starting image", 2) command = self.vmrun + " start " + self.vmx return self.vmcommand(command)
[ "def", "start", "(", "self", ")", ":", "self", ".", "log", "(", "\"starting image\"", ",", "2", ")", "command", "=", "self", ".", "vmrun", "+", "\" start \"", "+", "self", ".", "vmx", "return", "self", ".", "vmcommand", "(", "command", ")" ]
https://github.com/pwnieexpress/pwn_plug_sources/blob/1a23324f5dc2c3de20f9c810269b6a29b2758cad/src/voiper/sulley/vmcontrol.py#L255-L259
lbolla/EMpy
6296882a9c69a9f652943d235cd65df028c3d2b3
scripts/FDTD.py
python
Input.__init__
(self, filename)
Set the input filename.
Set the input filename.
[ "Set", "the", "input", "filename", "." ]
def __init__(self, filename): """Set the input filename.""" self.filename = filename
[ "def", "__init__", "(", "self", ",", "filename", ")", ":", "self", ".", "filename", "=", "filename" ]
https://github.com/lbolla/EMpy/blob/6296882a9c69a9f652943d235cd65df028c3d2b3/scripts/FDTD.py#L19-L21
iiau-tracker/SPLT
a196e603798e9be969d9d985c087c11cad1cda43
core/man_meta_arch.py
python
MANMetaArch._add_box_predictions_to_feature_maps
(self, feature_maps,reuse=None)
return box_encodings, class_predictions_with_background
Adds box predictors to each feature map and returns concatenated results. Args: feature_maps: a list of tensors where the ith tensor has shape [batch, height_i, width_i, depth_i] Returns: box_encodings: 4-D float tensor of shape [batch_size, num_anchors, box_code_dimension] containing predicted boxes. class_predictions_with_background: 2-D float tensor of shape [batch_size, num_anchors, num_classes+1] containing class predictions (logits) for each of the anchors. Note that this tensor *includes* background class predictions (at class index 0). Raises: RuntimeError: if the number of feature maps extracted via the extract_features method does not match the length of the num_anchors_per_locations list that was passed to the constructor. RuntimeError: if box_encodings from the box_predictor does not have shape of the form [batch_size, num_anchors, 1, code_size].
Adds box predictors to each feature map and returns concatenated results.
[ "Adds", "box", "predictors", "to", "each", "feature", "map", "and", "returns", "concatenated", "results", "." ]
def _add_box_predictions_to_feature_maps(self, feature_maps,reuse=None): """Adds box predictors to each feature map and returns concatenated results. Args: feature_maps: a list of tensors where the ith tensor has shape [batch, height_i, width_i, depth_i] Returns: box_encodings: 4-D float tensor of shape [batch_size, num_anchors, box_code_dimension] containing predicted boxes. class_predictions_with_background: 2-D float tensor of shape [batch_size, num_anchors, num_classes+1] containing class predictions (logits) for each of the anchors. Note that this tensor *includes* background class predictions (at class index 0). Raises: RuntimeError: if the number of feature maps extracted via the extract_features method does not match the length of the num_anchors_per_locations list that was passed to the constructor. RuntimeError: if box_encodings from the box_predictor does not have shape of the form [batch_size, num_anchors, 1, code_size]. """ num_anchors_per_location_list = ( self._anchor_generator.num_anchors_per_location()) if len(feature_maps) != len(num_anchors_per_location_list): raise RuntimeError('the number of feature maps must match the ' 'length of self.anchors.NumAnchorsPerLocation().') box_encodings_list = [] cls_predictions_with_background_list = [] for idx, (feature_map, num_anchors_per_location ) in enumerate(zip(feature_maps, num_anchors_per_location_list)): box_predictor_scope = 'BoxPredictor' box_predictions = self._box_predictor.predict(feature_map, num_anchors_per_location, box_predictor_scope,reuse=reuse) box_encodings = box_predictions[bpredictor.BOX_ENCODINGS] cls_predictions_with_background = box_predictions[ bpredictor.CLASS_PREDICTIONS_WITH_BACKGROUND] box_encodings_shape = box_encodings.get_shape().as_list() if len(box_encodings_shape) != 4 or box_encodings_shape[2] != 1: raise RuntimeError('box_encodings from the box_predictor must be of ' 'shape `[batch_size, num_anchors, 1, code_size]`; ' 'actual shape', box_encodings_shape) box_encodings = tf.squeeze(box_encodings, axis=2) box_encodings_list.append(box_encodings) cls_predictions_with_background_list.append( cls_predictions_with_background) num_predictions = sum( [tf.shape(box_encodings)[1] for box_encodings in box_encodings_list]) num_anchors = self.anchors.num_boxes() anchors_assert = tf.assert_equal(num_anchors, num_predictions, [ 'Mismatch: number of anchors vs number of predictions', num_anchors, num_predictions ]) with tf.control_dependencies([anchors_assert]): box_encodings = tf.concat(box_encodings_list, 1) class_predictions_with_background = tf.concat( cls_predictions_with_background_list, 1) return box_encodings, class_predictions_with_background
[ "def", "_add_box_predictions_to_feature_maps", "(", "self", ",", "feature_maps", ",", "reuse", "=", "None", ")", ":", "num_anchors_per_location_list", "=", "(", "self", ".", "_anchor_generator", ".", "num_anchors_per_location", "(", ")", ")", "if", "len", "(", "fe...
https://github.com/iiau-tracker/SPLT/blob/a196e603798e9be969d9d985c087c11cad1cda43/core/man_meta_arch.py#L154-L214
PacktPublishing/Clean-Code-in-Python
3c4b4a2fde2ccf28d2e0ec5002b2e1921704164e
Chapter03/exceptions_2.py
python
connect_with_retry
(connector, retry_n_times, retry_threshold=5)
Tries to establish the connection of <connector> retrying <retry_n_times>. If it can connect, returns the connection object. If it's not possible after the retries, raises ConnectionError :param connector: An object with a `.connect()` method. :param retry_n_times int: The number of times to try to call ``connector.connect()``. :param retry_threshold int: The time lapse between retry calls.
Tries to establish the connection of <connector> retrying <retry_n_times>.
[ "Tries", "to", "establish", "the", "connection", "of", "<connector", ">", "retrying", "<retry_n_times", ">", "." ]
def connect_with_retry(connector, retry_n_times, retry_threshold=5): """Tries to establish the connection of <connector> retrying <retry_n_times>. If it can connect, returns the connection object. If it's not possible after the retries, raises ConnectionError :param connector: An object with a `.connect()` method. :param retry_n_times int: The number of times to try to call ``connector.connect()``. :param retry_threshold int: The time lapse between retry calls. """ for _ in range(retry_n_times): try: return connector.connect() except ConnectionError as e: logger.info( "%s: attempting new connection in %is", e, retry_threshold ) time.sleep(retry_threshold) exc = ConnectionError(f"Couldn't connect after {retry_n_times} times") logger.exception(exc) raise exc
[ "def", "connect_with_retry", "(", "connector", ",", "retry_n_times", ",", "retry_threshold", "=", "5", ")", ":", "for", "_", "in", "range", "(", "retry_n_times", ")", ":", "try", ":", "return", "connector", ".", "connect", "(", ")", "except", "ConnectionErro...
https://github.com/PacktPublishing/Clean-Code-in-Python/blob/3c4b4a2fde2ccf28d2e0ec5002b2e1921704164e/Chapter03/exceptions_2.py#L31-L54
rembo10/headphones
b3199605be1ebc83a7a8feab6b1e99b64014187c
lib/requests/cookies.py
python
RequestsCookieJar.set_cookie
(self, cookie, *args, **kwargs)
return super(RequestsCookieJar, self).set_cookie(cookie, *args, **kwargs)
[]
def set_cookie(self, cookie, *args, **kwargs): if hasattr(cookie.value, 'startswith') and cookie.value.startswith('"') and cookie.value.endswith('"'): cookie.value = cookie.value.replace('\\"', '') return super(RequestsCookieJar, self).set_cookie(cookie, *args, **kwargs)
[ "def", "set_cookie", "(", "self", ",", "cookie", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "hasattr", "(", "cookie", ".", "value", ",", "'startswith'", ")", "and", "cookie", ".", "value", ".", "startswith", "(", "'\"'", ")", "and", ...
https://github.com/rembo10/headphones/blob/b3199605be1ebc83a7a8feab6b1e99b64014187c/lib/requests/cookies.py#L297-L300
JPaulMora/Pyrit
f0f1913c645b445dd391fb047b812b5ba511782c
cpyrit/cpyrit.py
python
CPyrit.__init__
(self)
Create a new instance that blocks calls to .enqueue() when more than the given amount of passwords are currently waiting to be scheduled to the hardware.
Create a new instance that blocks calls to .enqueue() when more than the given amount of passwords are currently waiting to be scheduled to the hardware.
[ "Create", "a", "new", "instance", "that", "blocks", "calls", "to", ".", "enqueue", "()", "when", "more", "than", "the", "given", "amount", "of", "passwords", "are", "currently", "waiting", "to", "be", "scheduled", "to", "the", "hardware", "." ]
def __init__(self): """Create a new instance that blocks calls to .enqueue() when more than the given amount of passwords are currently waiting to be scheduled to the hardware. """ self.inqueue = [] self.outqueue = {} self.workunits = [] self.slices = {} self.in_idx = self.out_idx = 0 self.cores = [] self.CUDAs = [] self.OpCL = [] self.all = [] self.cv = threading.Condition() # CUDA if config.cfg['use_CUDA'] == 'true' and 'cpyrit._cpyrit_cuda' in sys.modules and config.cfg['use_OpenCL'] == 'false': CUDA = _cpyrit_cuda.listDevices() for dev_idx, device in enumerate(CUDA): self.CUDAs.append(CUDACore(queue=self, dev_idx=dev_idx)) # OpenCL if config.cfg['use_OpenCL'] == 'true' and 'cpyrit._cpyrit_opencl' in sys.modules: for platform_idx in range(_cpyrit_opencl.numPlatforms): p = _cpyrit_opencl.OpenCLPlatform(platform_idx) for dev_idx in range(p.numDevices): dev = _cpyrit_opencl.OpenCLDevice(platform_idx, dev_idx) if dev.deviceType in ('GPU', 'ACCELERATOR'): core = OpenCLCore(self, platform_idx, dev_idx) self.OpCL.append(core) # CAL++ if 'cpyrit._cpyrit_calpp' in sys.modules: for dev_idx, device in enumerate(_cpyrit_calpp.listDevices()): self.cores.append(CALCore(queue=self, dev_idx=dev_idx)) # CPUs for i in xrange(util.ncpus): self.cores.append(CPUCore(queue=self)) # Network if config.cfg['rpc_server'] == 'true': for port in xrange(17935, 18000): try: ncore = NetworkCore(queue=self, port=port) except socket.error: pass else: self.ncore_uuid = ncore.uuid self.cores.append(ncore) if config.cfg['rpc_announce'] == 'true': cl = config.cfg['rpc_knownclients'].split(' ') cl = filter(lambda x: len(x) > 0, map(str.strip, cl)) bcst = config.cfg['rpc_announce_broadcast'] == 'true' self.announcer = network.NetworkAnnouncer(port=port, \ clients=cl, \ broadcast=bcst) break else: self.ncore_uuid = None else: self.ncore_uuid = None for core in self.cores: self.all.append(core) for OCL in self.OpCL: self.all.append(OCL) for CD in self.CUDAs: self.all.append(CD)
[ "def", "__init__", "(", "self", ")", ":", "self", ".", "inqueue", "=", "[", "]", "self", ".", "outqueue", "=", "{", "}", "self", ".", "workunits", "=", "[", "]", "self", ".", "slices", "=", "{", "}", "self", ".", "in_idx", "=", "self", ".", "ou...
https://github.com/JPaulMora/Pyrit/blob/f0f1913c645b445dd391fb047b812b5ba511782c/cpyrit/cpyrit.py#L420-L496
timgaripov/TensorNet-TF
76299ad4726370bb5e75589017208d7eae7d8666
experiments/cifar-10/conv-Ultimate-Tensorization/nets/conv-fc.py
python
evaluation
(logits, labels)
return tf.cast(correct_flags, tf.int32)
Evaluate the quality of the logits at predicting the label. Args: logits: Logits tensor, float - [batch_size, NUM_CLASSES]. labels: Labels tensor, int32 - [batch_size], with values in the range [0, NUM_CLASSES). Returns: A scalar int32 tensor with the number of examples (out of batch_size) that were predicted correctly.
Evaluate the quality of the logits at predicting the label. Args: logits: Logits tensor, float - [batch_size, NUM_CLASSES]. labels: Labels tensor, int32 - [batch_size], with values in the range [0, NUM_CLASSES). Returns: A scalar int32 tensor with the number of examples (out of batch_size) that were predicted correctly.
[ "Evaluate", "the", "quality", "of", "the", "logits", "at", "predicting", "the", "label", ".", "Args", ":", "logits", ":", "Logits", "tensor", "float", "-", "[", "batch_size", "NUM_CLASSES", "]", ".", "labels", ":", "Labels", "tensor", "int32", "-", "[", ...
def evaluation(logits, labels): """Evaluate the quality of the logits at predicting the label. Args: logits: Logits tensor, float - [batch_size, NUM_CLASSES]. labels: Labels tensor, int32 - [batch_size], with values in the range [0, NUM_CLASSES). Returns: A scalar int32 tensor with the number of examples (out of batch_size) that were predicted correctly. """ # For a classifier model, we can use the in_top_k Op. # It returns a bool tensor with shape [batch_size] that is true for # the examples where the label's is was in the top k (here k=1) # of all logits for that example. correct_flags = tf.nn.in_top_k(logits, labels, 1) # Return the number of true entries. return tf.cast(correct_flags, tf.int32)
[ "def", "evaluation", "(", "logits", ",", "labels", ")", ":", "# For a classifier model, we can use the in_top_k Op.", "# It returns a bool tensor with shape [batch_size] that is true for", "# the examples where the label's is was in the top k (here k=1)", "# of all logits for that example.", ...
https://github.com/timgaripov/TensorNet-TF/blob/76299ad4726370bb5e75589017208d7eae7d8666/experiments/cifar-10/conv-Ultimate-Tensorization/nets/conv-fc.py#L206-L222
zaxlct/imooc-django
daf1ced745d3d21989e8191b658c293a511b37fd
extra_apps/xadmin/views/dashboard.py
python
BaseWidget.setup
(self)
[]
def setup(self): helper = FormHelper() helper.form_tag = False helper.include_media = False self.helper = helper self.id = self.cleaned_data['id'] self.title = self.cleaned_data['title'] or self.base_title if not (self.user.is_superuser or self.has_perm()): raise PermissionDenied
[ "def", "setup", "(", "self", ")", ":", "helper", "=", "FormHelper", "(", ")", "helper", ".", "form_tag", "=", "False", "helper", ".", "include_media", "=", "False", "self", ".", "helper", "=", "helper", "self", ".", "id", "=", "self", ".", "cleaned_dat...
https://github.com/zaxlct/imooc-django/blob/daf1ced745d3d21989e8191b658c293a511b37fd/extra_apps/xadmin/views/dashboard.py#L202-L212
sagemath/sage
f9b2db94f675ff16963ccdefba4f1a3393b3fe0d
src/sage/combinat/permutation.py
python
Permutation.foata_bijection
(self)
return Permutations()(M)
r""" Return the image of the permutation ``self`` under the Foata bijection `\phi`. The bijection shows that `\mathrm{maj}` (the major index) and `\mathrm{inv}` (the number of inversions) are equidistributed: if `\phi(P) = Q`, then `\mathrm{maj}(P) = \mathrm{inv}(Q)`. The Foata bijection `\phi` is a bijection on the set of words with no two equal letters. It can be defined by induction on the size of the word: Given a word `w_1 w_2 \cdots w_n`, start with `\phi(w_1) = w_1`. At the `i`-th step, if `\phi(w_1 w_2 \cdots w_i) = v_1 v_2 \cdots v_i`, we define `\phi(w_1 w_2 \cdots w_i w_{i+1})` by placing `w_{i+1}` on the end of the word `v_1 v_2 \cdots v_i` and breaking the word up into blocks as follows. If `w_{i+1} > v_i`, place a vertical line to the right of each `v_k` for which `w_{i+1} > v_k`. Otherwise, if `w_{i+1} < v_i`, place a vertical line to the right of each `v_k` for which `w_{i+1} < v_k`. In either case, place a vertical line at the start of the word as well. Now, within each block between vertical lines, cyclically shift the entries one place to the right. For instance, to compute `\phi([1,4,2,5,3])`, the sequence of words is * `1`, * `|1|4 \to 14`, * `|14|2 \to 412`, * `|4|1|2|5 \to 4125`, * `|4|125|3 \to 45123`. So `\phi([1,4,2,5,3]) = [4,5,1,2,3]`. See section 2 of [FS1978]_, and the proof of Proposition 1.4.6 in [EnumComb1]_. .. SEEALSO:: :meth:`foata_bijection_inverse` for the inverse map. EXAMPLES:: sage: Permutation([1,2,4,3]).foata_bijection() [4, 1, 2, 3] sage: Permutation([2,5,1,3,4]).foata_bijection() [2, 1, 3, 5, 4] sage: P = Permutation([2,5,1,3,4]) sage: P.major_index() == P.foata_bijection().number_of_inversions() True sage: all( P.major_index() == P.foata_bijection().number_of_inversions() ....: for P in Permutations(4) ) True The example from [FS1978]_:: sage: Permutation([7,4,9,2,6,1,5,8,3]).foata_bijection() [4, 7, 2, 6, 1, 9, 5, 8, 3] Border cases:: sage: Permutation([]).foata_bijection() [] sage: Permutation([1]).foata_bijection() [1]
r""" Return the image of the permutation ``self`` under the Foata bijection `\phi`.
[ "r", "Return", "the", "image", "of", "the", "permutation", "self", "under", "the", "Foata", "bijection", "\\", "phi", "." ]
def foata_bijection(self) -> Permutation: r""" Return the image of the permutation ``self`` under the Foata bijection `\phi`. The bijection shows that `\mathrm{maj}` (the major index) and `\mathrm{inv}` (the number of inversions) are equidistributed: if `\phi(P) = Q`, then `\mathrm{maj}(P) = \mathrm{inv}(Q)`. The Foata bijection `\phi` is a bijection on the set of words with no two equal letters. It can be defined by induction on the size of the word: Given a word `w_1 w_2 \cdots w_n`, start with `\phi(w_1) = w_1`. At the `i`-th step, if `\phi(w_1 w_2 \cdots w_i) = v_1 v_2 \cdots v_i`, we define `\phi(w_1 w_2 \cdots w_i w_{i+1})` by placing `w_{i+1}` on the end of the word `v_1 v_2 \cdots v_i` and breaking the word up into blocks as follows. If `w_{i+1} > v_i`, place a vertical line to the right of each `v_k` for which `w_{i+1} > v_k`. Otherwise, if `w_{i+1} < v_i`, place a vertical line to the right of each `v_k` for which `w_{i+1} < v_k`. In either case, place a vertical line at the start of the word as well. Now, within each block between vertical lines, cyclically shift the entries one place to the right. For instance, to compute `\phi([1,4,2,5,3])`, the sequence of words is * `1`, * `|1|4 \to 14`, * `|14|2 \to 412`, * `|4|1|2|5 \to 4125`, * `|4|125|3 \to 45123`. So `\phi([1,4,2,5,3]) = [4,5,1,2,3]`. See section 2 of [FS1978]_, and the proof of Proposition 1.4.6 in [EnumComb1]_. .. SEEALSO:: :meth:`foata_bijection_inverse` for the inverse map. EXAMPLES:: sage: Permutation([1,2,4,3]).foata_bijection() [4, 1, 2, 3] sage: Permutation([2,5,1,3,4]).foata_bijection() [2, 1, 3, 5, 4] sage: P = Permutation([2,5,1,3,4]) sage: P.major_index() == P.foata_bijection().number_of_inversions() True sage: all( P.major_index() == P.foata_bijection().number_of_inversions() ....: for P in Permutations(4) ) True The example from [FS1978]_:: sage: Permutation([7,4,9,2,6,1,5,8,3]).foata_bijection() [4, 7, 2, 6, 1, 9, 5, 8, 3] Border cases:: sage: Permutation([]).foata_bijection() [] sage: Permutation([1]).foata_bijection() [1] """ M: list[int] = [] for e in self: k = len(M) if k <= 1: M.append(e) continue a = M[-1] M_prime = [0]*(k + 1) # Locate the positions of the vertical lines. if a > e: index_list = [-1] + [i for i, val in enumerate(M) if val > e] else: index_list = [-1] + [i for i, val in enumerate(M) if val < e] for j in range(1, len(index_list)): start = index_list[j-1] + 1 end = index_list[j] M_prime[start] = M[end] for x in range(start + 1, end + 1): M_prime[x] = M[x-1] M_prime[k] = e M = M_prime return Permutations()(M)
[ "def", "foata_bijection", "(", "self", ")", "->", "Permutation", ":", "M", ":", "list", "[", "int", "]", "=", "[", "]", "for", "e", "in", "self", ":", "k", "=", "len", "(", "M", ")", "if", "k", "<=", "1", ":", "M", ".", "append", "(", "e", ...
https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/combinat/permutation.py#L2313-L2406
sympy/sympy
d822fcba181155b85ff2b29fe525adbafb22b448
sympy/integrals/rubi/utility_function.py
python
Length
(expr)
return len(expr.args)
Returns number of elements in the expression just as SymPy's len. Examples ======== >>> from sympy.integrals.rubi.utility_function import Length >>> from sympy.abc import x, a, b >>> from sympy import cos, sin >>> Length(a + b) 2 >>> Length(sin(a)*cos(a)) 2
Returns number of elements in the expression just as SymPy's len.
[ "Returns", "number", "of", "elements", "in", "the", "expression", "just", "as", "SymPy", "s", "len", "." ]
def Length(expr): """ Returns number of elements in the expression just as SymPy's len. Examples ======== >>> from sympy.integrals.rubi.utility_function import Length >>> from sympy.abc import x, a, b >>> from sympy import cos, sin >>> Length(a + b) 2 >>> Length(sin(a)*cos(a)) 2 """ if isinstance(expr, list): return len(expr) return len(expr.args)
[ "def", "Length", "(", "expr", ")", ":", "if", "isinstance", "(", "expr", ",", "list", ")", ":", "return", "len", "(", "expr", ")", "return", "len", "(", "expr", ".", "args", ")" ]
https://github.com/sympy/sympy/blob/d822fcba181155b85ff2b29fe525adbafb22b448/sympy/integrals/rubi/utility_function.py#L832-L850
Jeff-sjtu/CrowdPose
86fe5e11e570cad02d553db52ec72545578cd1c8
crowdpose-api/PythonAPI/crowdposetools/cocoeval.py
python
COCOeval.accumulate
(self, p=None)
Accumulate per image evaluation results and store the result in self.eval :param p: input params for evaluation :return: None
Accumulate per image evaluation results and store the result in self.eval :param p: input params for evaluation :return: None
[ "Accumulate", "per", "image", "evaluation", "results", "and", "store", "the", "result", "in", "self", ".", "eval", ":", "param", "p", ":", "input", "params", "for", "evaluation", ":", "return", ":", "None" ]
def accumulate(self, p=None): ''' Accumulate per image evaluation results and store the result in self.eval :param p: input params for evaluation :return: None ''' print('Accumulating evaluation results...') tic = time.time() if not self.evalImgs: print('Please run evaluate() first') # allows input customized parameters if p is None: p = self.params p.catIds = p.catIds if p.useCats == 1 else [-1] T = len(p.iouThrs) R = len(p.recThrs) K = len(p.catIds) if p.useCats else 1 A = len(p.areaRng) M = len(p.maxDets) # -1 for the precision of absent categories precision = -np.ones((T, R, K, A, M)) recall = -np.ones((T, K, A, M)) scores = -np.ones((T, R, K, A, M)) # create dictionary for future indexing _pe = self._paramsEval catIds = _pe.catIds if _pe.useCats else [-1] setK = set(catIds) setA = set(map(tuple, _pe.areaRng)) setM = set(_pe.maxDets) setI = set(_pe.imgIds) # get inds to evaluate k_list = [n for n, k in enumerate(p.catIds) if k in setK] m_list = [m for n, m in enumerate(p.maxDets) if m in setM] a_list = [n for n, a in enumerate( map(lambda x: tuple(x), p.areaRng)) if a in setA] i_list = [n for n, i in enumerate(p.imgIds) if i in setI] I0 = len(_pe.imgIds) A0 = len(_pe.areaRng) # retrieve E at each category, area range, and max number of detections for k, k0 in enumerate(k_list): Nk = k0*A0*I0 for a, a0 in enumerate(a_list): Na = a0*I0 for m, maxDet in enumerate(m_list): E = [self.evalImgs[Nk + Na + i] for i in i_list] E = [e for e in E if not e is None] if len(E) == 0: continue dtScores = np.concatenate( [e['dtScores'][0:maxDet] for e in E]) # different sorting method generates slightly different results. # mergesort is used to be consistent as Matlab implementation. inds = np.argsort(-dtScores, kind='mergesort') dtScoresSorted = dtScores[inds] dtm = np.concatenate([e['dtMatches'][:, 0:maxDet] for e in E], axis=1)[:, inds] dtIg = np.concatenate( [e['dtIgnore'][:, 0:maxDet] for e in E], axis=1)[:, inds] gtIg = np.concatenate([e['gtIgnore'] for e in E]) npig = np.count_nonzero(gtIg == 0) if npig == 0: continue tps = np.logical_and(dtm, np.logical_not(dtIg)) fps = np.logical_and( np.logical_not(dtm), np.logical_not(dtIg)) tp_sum = np.cumsum(tps, axis=1).astype(dtype=np.float) fp_sum = np.cumsum(fps, axis=1).astype(dtype=np.float) for t, (tp, fp) in enumerate(zip(tp_sum, fp_sum)): tp = np.array(tp) fp = np.array(fp) nd = len(tp) rc = tp / npig pr = tp / (fp+tp+np.spacing(1)) q = np.zeros((R,)) ss = np.zeros((R,)) if nd: recall[t, k, a, m] = rc[-1] else: recall[t, k, a, m] = 0 # numpy is slow without cython optimization for accessing elements # use python array gets significant speed improvement pr = pr.tolist() q = q.tolist() for i in range(nd-1, 0, -1): if pr[i] > pr[i-1]: pr[i-1] = pr[i] inds = np.searchsorted(rc, p.recThrs, side='left') try: for ri, pi in enumerate(inds): q[ri] = pr[pi] ss[ri] = dtScoresSorted[pi] except: pass precision[t, :, k, a, m] = np.array(q) scores[t, :, k, a, m] = np.array(ss) self.eval = { 'params': p, 'counts': [T, R, K, A, M], 'date': datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'), 'precision': precision, 'recall': recall, 'scores': scores, } toc = time.time() print('DONE (t={:0.2f}s).'.format(toc-tic))
[ "def", "accumulate", "(", "self", ",", "p", "=", "None", ")", ":", "print", "(", "'Accumulating evaluation results...'", ")", "tic", "=", "time", ".", "time", "(", ")", "if", "not", "self", ".", "evalImgs", ":", "print", "(", "'Please run evaluate() first'",...
https://github.com/Jeff-sjtu/CrowdPose/blob/86fe5e11e570cad02d553db52ec72545578cd1c8/crowdpose-api/PythonAPI/crowdposetools/cocoeval.py#L350-L462
kuri65536/python-for-android
26402a08fc46b09ef94e8d7a6bbc3a54ff9d0891
python-modules/twisted/twisted/internet/task.py
python
LoopingCall._reschedule
(self)
Schedule the next iteration of this looping call.
Schedule the next iteration of this looping call.
[ "Schedule", "the", "next", "iteration", "of", "this", "looping", "call", "." ]
def _reschedule(self): """ Schedule the next iteration of this looping call. """ if self.interval == 0: self.call = self.clock.callLater(0, self) return currentTime = self.clock.seconds() # Find how long is left until the interval comes around again. untilNextTime = (self._expectNextCallAt - currentTime) % self.interval # Make sure it is in the future, in case more than one interval worth # of time passed since the previous call was made. nextTime = max( self._expectNextCallAt + self.interval, currentTime + untilNextTime) # If the interval falls on the current time exactly, skip it and # schedule the call for the next interval. if nextTime == currentTime: nextTime += self.interval self._expectNextCallAt = nextTime self.call = self.clock.callLater(nextTime - currentTime, self)
[ "def", "_reschedule", "(", "self", ")", ":", "if", "self", ".", "interval", "==", "0", ":", "self", ".", "call", "=", "self", ".", "clock", ".", "callLater", "(", "0", ",", "self", ")", "return", "currentTime", "=", "self", ".", "clock", ".", "seco...
https://github.com/kuri65536/python-for-android/blob/26402a08fc46b09ef94e8d7a6bbc3a54ff9d0891/python-modules/twisted/twisted/internet/task.py#L199-L219
dfd-tud/deda
23e84e1a027263b7296a670b615c16dab1bdedd9
libdeda/print_parser.py
python
PrintParser.getAllTdms
(self)
TDMs where redundance check passed or failed
TDMs where redundance check passed or failed
[ "TDMs", "where", "redundance", "check", "passed", "or", "failed" ]
def getAllTdms(self): """ TDMs where redundance check passed or failed """ for tdm in self.allTDMs: yield tdm
[ "def", "getAllTdms", "(", "self", ")", ":", "for", "tdm", "in", "self", ".", "allTDMs", ":", "yield", "tdm" ]
https://github.com/dfd-tud/deda/blob/23e84e1a027263b7296a670b615c16dab1bdedd9/libdeda/print_parser.py#L176-L179
leo-editor/leo-editor
383d6776d135ef17d73d935a2f0ecb3ac0e99494
leo/plugins/viewrendered3.py
python
ViewRenderedController3.plot_2d
(self)
r""" #@+<< docstring >> #@+node:tom.20211104105903.2: *5* << docstring >> Show a plot of x-y data in the selected node. The data can be either a one-column or two-column list of rows. Columns are separated by whitespace. Optionally, the node may contain a config file-like set of sections that define the labels, and plot styling. Optionally, the data can be read from a file instead of taken from the selected node. The matplotlib package is required for plotting. #@+others #@+node:tom.20211104105903.3: *6* Data Format Data Format ------------ Data must be in one or two columns separated by whitespace Here is an example of two-column data:: 1 1 2 2 3 4 # comment ; comment 4 16 5 32 Comment lines start with one of ";", "#". Comment, non-numeric, and blank lines are ignored. Here is an example of one-column data - the missing first column will assigned integers starting with 0:: 1 .5 6 # comment ; comment 16 32 Whether the data contains one or two columns is determined from the first non-comment, non-blank, all numeric row. If one-column, an implicit first column is added starting with zero. #@+node:tom.20211108101908.1: *6* Configuration Sections Configuration Sections ----------------------- The labeling, styling, and data source for the plot can be specified in configuration sections. Each section starts with a *[name]*, has zero or more lines in the form *key = value*, and must end with a blank line or the end of the node. Sections may be placed anywhere in the selected node. The *[sectionname]* must be left-justified. Currently the following sections are recognized:: [style] [labels] [source] #@+node:tom.20211108100421.1: *6* Optional Data Source Optional Data Source --------------------- Data to be plotted can be read from a file. The selected node must contain a section *[source]* with a *file* key, like this:: [source] file = c:\example\datafile.txt If the file exists, it will be used as the data source instead of the selected Leo node. All configuration sections in the selected nodes will still take effect. #@+node:tom.20211104105903.4: *6* Graph And Data Labels Graph And Data Labels ---------------------- A figure title and axis labels can optionally be added. These are specified by the configuration section *[labels]*. Here is an example:: [labels] title = Plot Example xaxis = Days yaxis = Values Any or all of the entries may be omitted. #@+node:tom.20211104183046.1: *6* Plot Styling Plot Styling ------------- The appearance of the plot can optionally be changed in several ways. By default, a certain Matplotlib style file will be used if present (see below), or default Matplotlib styling will be applied. If the data node has a section *[style]*, one of two styling methods can be used: 1. A named style. Matplotlib has a number of named styles, such as *ggplot*. One of these built-in style names can be specified by the *stylename* key. The style *xkcd* can also be used even though it is not one of the named styles. 2. A Matplotlib style file. The name of this file is specified by the *stylefile* key. The file can be located Leo's home directory, typically *~/.leo* or its equivalent in Windows. Here is an example *[data]* section, with explanatory comments added:: [style] # For VR3 "Plot 2D", only one of these # will be used. "stylename" has priority # over "stylefile". stylename = ggplot #stylefile = styles.mpl The section may be placed anywhere in the node. The Default Style File ........................ When no *[data]* section is present, a style file named *local_mplstyle* will be used if found. It will first be looked for in Leo's home directory, and then in the *site.userbase()* directory. On Windows, this is usually the *%APPDATA%\\Python* directory. On Linux, this is usually *~/.local*. When no style file can be found, Matplotlib will use its default styling, as modified by a *matplotlibrc* file if Matplotlib can find one. #@-others #@-<< docstring >>
r""" #@+<< docstring >> #@+node:tom.20211104105903.2: *5* << docstring >> Show a plot of x-y data in the selected node.
[ "r", "#@", "+", "<<", "docstring", ">>", "#@", "+", "node", ":", "tom", ".", "20211104105903", ".", "2", ":", "*", "5", "*", "<<", "docstring", ">>", "Show", "a", "plot", "of", "x", "-", "y", "data", "in", "the", "selected", "node", "." ]
def plot_2d(self): r""" #@+<< docstring >> #@+node:tom.20211104105903.2: *5* << docstring >> Show a plot of x-y data in the selected node. The data can be either a one-column or two-column list of rows. Columns are separated by whitespace. Optionally, the node may contain a config file-like set of sections that define the labels, and plot styling. Optionally, the data can be read from a file instead of taken from the selected node. The matplotlib package is required for plotting. #@+others #@+node:tom.20211104105903.3: *6* Data Format Data Format ------------ Data must be in one or two columns separated by whitespace Here is an example of two-column data:: 1 1 2 2 3 4 # comment ; comment 4 16 5 32 Comment lines start with one of ";", "#". Comment, non-numeric, and blank lines are ignored. Here is an example of one-column data - the missing first column will assigned integers starting with 0:: 1 .5 6 # comment ; comment 16 32 Whether the data contains one or two columns is determined from the first non-comment, non-blank, all numeric row. If one-column, an implicit first column is added starting with zero. #@+node:tom.20211108101908.1: *6* Configuration Sections Configuration Sections ----------------------- The labeling, styling, and data source for the plot can be specified in configuration sections. Each section starts with a *[name]*, has zero or more lines in the form *key = value*, and must end with a blank line or the end of the node. Sections may be placed anywhere in the selected node. The *[sectionname]* must be left-justified. Currently the following sections are recognized:: [style] [labels] [source] #@+node:tom.20211108100421.1: *6* Optional Data Source Optional Data Source --------------------- Data to be plotted can be read from a file. The selected node must contain a section *[source]* with a *file* key, like this:: [source] file = c:\example\datafile.txt If the file exists, it will be used as the data source instead of the selected Leo node. All configuration sections in the selected nodes will still take effect. #@+node:tom.20211104105903.4: *6* Graph And Data Labels Graph And Data Labels ---------------------- A figure title and axis labels can optionally be added. These are specified by the configuration section *[labels]*. Here is an example:: [labels] title = Plot Example xaxis = Days yaxis = Values Any or all of the entries may be omitted. #@+node:tom.20211104183046.1: *6* Plot Styling Plot Styling ------------- The appearance of the plot can optionally be changed in several ways. By default, a certain Matplotlib style file will be used if present (see below), or default Matplotlib styling will be applied. If the data node has a section *[style]*, one of two styling methods can be used: 1. A named style. Matplotlib has a number of named styles, such as *ggplot*. One of these built-in style names can be specified by the *stylename* key. The style *xkcd* can also be used even though it is not one of the named styles. 2. A Matplotlib style file. The name of this file is specified by the *stylefile* key. The file can be located Leo's home directory, typically *~/.leo* or its equivalent in Windows. Here is an example *[data]* section, with explanatory comments added:: [style] # For VR3 "Plot 2D", only one of these # will be used. "stylename" has priority # over "stylefile". stylename = ggplot #stylefile = styles.mpl The section may be placed anywhere in the node. The Default Style File ........................ When no *[data]* section is present, a style file named *local_mplstyle* will be used if found. It will first be looked for in Leo's home directory, and then in the *site.userbase()* directory. On Windows, this is usually the *%APPDATA%\\Python* directory. On Linux, this is usually *~/.local*. When no style file can be found, Matplotlib will use its default styling, as modified by a *matplotlibrc* file if Matplotlib can find one. #@-others #@-<< docstring >> """ if not matplotlib: g.es('VR3 -- Matplotlib is needed to plot 2D data') return page = self.c.p.b page_lines = page.split('\n') data_lines = [] #@+others #@+node:tom.20211104105903.5: *5* declarations ENCODING = 'utf-8' STYLEFILE = 'local_mplstyle' # Must be in site.getuserbase() SECTION_RE = re.compile(r'^\[([a-zA-Z0-9]+)\]') #@+node:tom.20211104105903.6: *5* functions #@+node:tom.20211104105903.7: *6* has_config_section() def has_config_section(pagelines): """Find config-like sections in the data page. Sections are defined by: 1. A left-justified term in [brackets]. 2. A blank line or the end of the list of lines. ARGUMENT pagelines -- a list of text lines. RETURNS a dictionary keyed by section label: {label: line_num, ...} """ sections = {} for i, line in enumerate(pagelines): m = SECTION_RE.match(line) if m: sections[m[1]] = i return sections #@+node:tom.20211104105903.8: *6* set custom_style() #@@pagewidth 65 def set_custom_style(): r"""Apply custom matplotlib styles from a file. The style file has the name given by STYLEFILE. The .leo directory (usually ~/.leo) will be checked first for the style file. If not found, the site.getuserbase() directory will be checked for the style file. On Windows, this is usually the %APPDATA%\Python directory. On Linux, this is usually at /home/tom/.local. """ found_styles = False lm = g.app.loadManager style_dir = lm.computeHomeLeoDir() if g.isWindows: style_dir = style_dir.replace('/', '\\') style_file=os.path.join(style_dir, STYLEFILE) if os.path.exists(style_file): plt.style.use(style_file) found_styles = True else: style_dir=site.getuserbase() style_file=os.path.join(style_dir, STYLEFILE) if os.path.exists(style_file): plt.style.use(style_file) found_styles = True if not found_styles: g.es(f'Pyplot style file "{style_file}" not found, using default styles') #@+node:tom.20211104105903.12: *6* plot_plain_data() def plot_plain_data(pagelines): """Plot 1- or 2- column data. Ignore all non-numeric lines.""" # from leo.plugins import viewrendered3 as vr3 # from leo.plugins import viewrendered as vr # Helper functions #@+<< is_numeric >> #@+node:tom.20211104105903.13: *7* << is_numeric >> def is_numeric(line): """Test if first or 1st and 2nd cols are numeric""" fields = line.split() numfields = len(fields) fields = line.split() numfields = len(fields) numeric = False try: _ = float(fields[0]) if numfields > 1: _ = float(fields[1]) numeric = True except ValueError: pass return numeric #@-<< is_numeric >> #@+<< get_data >> #@+node:tom.20211104105903.14: *7* << get_data >> def get_data(pagelines): num_cols = 0 # Skip lines starting with """ or ''' lines = [line.replace('"""', '') for line in pagelines] lines = [line.replace("'''", '') for line in lines] # Skip blank lines lines = [line for line in lines if line.strip()] # skip non-data lines (first or 2nd col is not a number) t = [] for line in lines: line = line.replace(',', '') # remove formatting commas if is_numeric(line): t.append(line.strip()) # Check if first all-numeric row has one or more fields if not num_cols: num_cols = min(len(t[0].split()), 2) if not t: return None, None # Extract x, y values into separate lists; ignore columns after col. 2 if num_cols == 1: x = [i for i in range(len(t))] y = [float(b.strip()) for b in t] else: xy = [line.split()[:2] for line in t] xs, ys = zip(*xy) x = [float(a) for a in xs] y = [float(b) for b in ys] return x, y #@-<< get_data >> x, y = get_data(pagelines) if not x: g.es('VR3 -- cannot find data') return plt.plot(x,y) plt.show() # try: # plot2d(page) # except Exception as e: # g.es('VR3:', e) #@+node:tom.20211104155447.1: *6* set_user_style() #@@pagewidth 65 def set_user_style(style_config_lines): """Set special plot styles. If the data node has a section [style], then if there is a key "stylename", apply that named style; otherwise if there is a key "stylefile", look for a file of that name ins the user's Leo home directory (usually ~/.leo) and use those styles. The stylename must be one of the built-in style names, such as "ggplot". "xkcd" also works even though it is not actually one of the style names. ARGUMENT style_config_lines -- a sequence of lines starting at the [style] section of the data node. RETURNS True if a style was set. """ set_style = False for line in style_config_lines: if not line.strip: break fields = line.split('=') if len(fields) < 2: continue kind, val = fields[0].strip(), fields[1].strip() if kind == 'stylename': if val == 'xkcd': plt.xkcd() else: plt.style.use(val) set_style = True break if not set_style: for line in style_config_lines: if not line.strip: break fields = line.split('=') if len(fields) < 2: continue kind, val = fields[0].strip(), fields[1].strip() if kind == 'stylefile': lm = g.app.loadManager style_dir = lm.computeHomeLeoDir() if g.isWindows: style_dir = style_dir.replace('/', '\\') style_file = os.path.join(style_dir, val) if os.path.exists(style_file): plt.style.use(style_file) set_style = True break return set_style #@-others config_sections = has_config_section(page_lines) source_start = config_sections.get('source', -1) if source_start > 0: #@+<< set_data >> #@+node:tom.20211106174814.1: *5* << set_data >> for line in page_lines[source_start:]: if not line.strip: break fields = line.split('=') if len(fields) < 2: continue kind, val = fields[0].strip(), fields[1].strip() if kind == 'file': _, filename = fields[0].strip(), fields[1].strip() g.es(filename) if os.path.exists(filename): with open(filename, encoding = ENCODING) as f: data_lines = f.readlines() if not data_lines: g.es(f'VR3 -- no data in file {filename}') else: g.es(f'VR3 -- cannot open data file {filename}') #@-<< set_data >> else: data_lines = page_lines if not data_lines: return style_start = config_sections.get('style', -1) if style_start >= 0: if not set_user_style(page_lines[style_start:]): set_custom_style() else: set_custom_style() plt.ion() fig, ax = plt.subplots() fig.clear() label_start = config_sections.get('labels', -1) if label_start >= 0: #@+<< configure labels >> #@+node:tom.20211104105903.11: *5* << configure labels >> # Get lines for the labels section for line in page_lines[label_start:]: if not line.strip: break fields = line.split('=') if len(fields) < 2: continue kind, val = fields[0].strip(), fields[1].strip() if kind == 'title': plt.title(val) elif kind == 'xaxis': plt.xlabel(val) elif kind == 'yaxis': plt.ylabel(val) #@-<< configure labels >> plot_plain_data(data_lines) plt.rcdefaults()
[ "def", "plot_2d", "(", "self", ")", ":", "if", "not", "matplotlib", ":", "g", ".", "es", "(", "'VR3 -- Matplotlib is needed to plot 2D data'", ")", "return", "page", "=", "self", ".", "c", ".", "p", ".", "b", "page_lines", "=", "page", ".", "split", "(",...
https://github.com/leo-editor/leo-editor/blob/383d6776d135ef17d73d935a2f0ecb3ac0e99494/leo/plugins/viewrendered3.py#L1924-L2336
cloudera/hue
23f02102d4547c17c32bd5ea0eb24e9eadd657a4
desktop/core/ext-py/nose-1.3.7/nose/plugins/allmodules.py
python
AllModules.wantModule
(self, module)
return True
Override return True for all modules
Override return True for all modules
[ "Override", "return", "True", "for", "all", "modules" ]
def wantModule(self, module): """Override return True for all modules""" return True
[ "def", "wantModule", "(", "self", ",", "module", ")", ":", "return", "True" ]
https://github.com/cloudera/hue/blob/23f02102d4547c17c32bd5ea0eb24e9eadd657a4/desktop/core/ext-py/nose-1.3.7/nose/plugins/allmodules.py#L43-L45
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/lib/python2.7/site-packages/pygments/filters/__init__.py
python
TokenMergeFilter.filter
(self, lexer, stream)
[]
def filter(self, lexer, stream): current_type = None current_value = None for ttype, value in stream: if ttype is current_type: current_value += value else: if current_type is not None: yield current_type, current_value current_type = ttype current_value = value if current_type is not None: yield current_type, current_value
[ "def", "filter", "(", "self", ",", "lexer", ",", "stream", ")", ":", "current_type", "=", "None", "current_value", "=", "None", "for", "ttype", ",", "value", "in", "stream", ":", "if", "ttype", "is", "current_type", ":", "current_value", "+=", "value", "...
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/lib/python2.7/site-packages/pygments/filters/__init__.py#L327-L339
dragonfly/dragonfly
a579b5eadf452e23b07d4caf27b402703b0012b7
examples/salsa/salsa_estimator.py
python
get_salsa_estimator_from_data_and_hyperparams
(X_tr, Y_tr, kernel_type, add_order, kernel_scale, bandwidths, l2_reg)
return salsa_obj.eval
Returns an estimator using the data.
Returns an estimator using the data.
[ "Returns", "an", "estimator", "using", "the", "data", "." ]
def get_salsa_estimator_from_data_and_hyperparams(X_tr, Y_tr, kernel_type, add_order, kernel_scale, bandwidths, l2_reg): """ Returns an estimator using the data. """ problem_dim = np.array(X_tr).shape[1] kernel = get_salsa_kernel_from_params(kernel_type, add_order, kernel_scale, bandwidths, problem_dim) def _get_mean_func(_mean_func_const_value): """ Returns the mean function from the constant value. """ return lambda x: np.array([_mean_func_const_value] * len(x)) mean_func = _get_mean_func(np.median(Y_tr)) salsa_obj = SALSA(X_tr, Y_tr, kernel, mean_func, l2_reg) return salsa_obj.eval
[ "def", "get_salsa_estimator_from_data_and_hyperparams", "(", "X_tr", ",", "Y_tr", ",", "kernel_type", ",", "add_order", ",", "kernel_scale", ",", "bandwidths", ",", "l2_reg", ")", ":", "problem_dim", "=", "np", ".", "array", "(", "X_tr", ")", ".", "shape", "["...
https://github.com/dragonfly/dragonfly/blob/a579b5eadf452e23b07d4caf27b402703b0012b7/examples/salsa/salsa_estimator.py#L355-L366
shaypal5/cachier
ea7906fb5f5ae8d89d76fb39d2ce86002103b50b
cachier/_version.py
python
git_get_keywords
(versionfile_abs)
return keywords
Extract version information from the given file.
Extract version information from the given file.
[ "Extract", "version", "information", "from", "the", "given", "file", "." ]
def git_get_keywords(versionfile_abs): """Extract version information from the given file.""" # the code embedded in _version.py can just fetch the value of these # keywords. When used from setup.py, we don't want to import _version.py, # so we do it with a regexp instead. This function is not used from # _version.py. keywords = {} try: f = open(versionfile_abs, "r") for line in f.readlines(): if line.strip().startswith("git_refnames ="): mo = re.search(r'=\s*"(.*)"', line) if mo: keywords["refnames"] = mo.group(1) if line.strip().startswith("git_full ="): mo = re.search(r'=\s*"(.*)"', line) if mo: keywords["full"] = mo.group(1) f.close() except EnvironmentError: pass return keywords
[ "def", "git_get_keywords", "(", "versionfile_abs", ")", ":", "# the code embedded in _version.py can just fetch the value of these", "# keywords. When used from setup.py, we don't want to import _version.py,", "# so we do it with a regexp instead. This function is not used from", "# _version.py.",...
https://github.com/shaypal5/cachier/blob/ea7906fb5f5ae8d89d76fb39d2ce86002103b50b/cachier/_version.py#L121-L142
IlyaGusev/rupo
83a5fac0dddd480a401181e5465f0e3c94ad2dcc
rupo/stress/predictor.py
python
DictStressPredictor.__init__
(self, language="ru", raw_dict_path=None, trie_path=None, zalyzniak_dict=ZALYZNYAK_DICT, cmu_dict=CMU_DICT)
[]
def __init__(self, language="ru", raw_dict_path=None, trie_path=None, zalyzniak_dict=ZALYZNYAK_DICT, cmu_dict=CMU_DICT): self.stress_dict = StressDict(language, raw_dict_path=raw_dict_path, trie_path=trie_path, zalyzniak_dict=zalyzniak_dict, cmu_dict=cmu_dict)
[ "def", "__init__", "(", "self", ",", "language", "=", "\"ru\"", ",", "raw_dict_path", "=", "None", ",", "trie_path", "=", "None", ",", "zalyzniak_dict", "=", "ZALYZNYAK_DICT", ",", "cmu_dict", "=", "CMU_DICT", ")", ":", "self", ".", "stress_dict", "=", "St...
https://github.com/IlyaGusev/rupo/blob/83a5fac0dddd480a401181e5465f0e3c94ad2dcc/rupo/stress/predictor.py#L21-L24
intel/virtual-storage-manager
00706ab9701acbd0d5e04b19cc80c6b66a2973b8
source/vsm/vsm/utils.py
python
generate_glance_url
()
return "http://%s:%d" % (FLAGS.glance_host, FLAGS.glance_port)
Generate the URL to glance.
Generate the URL to glance.
[ "Generate", "the", "URL", "to", "glance", "." ]
def generate_glance_url(): """Generate the URL to glance.""" # TODO(jk0): This will eventually need to take SSL into consideration # when supported in glance. return "http://%s:%d" % (FLAGS.glance_host, FLAGS.glance_port)
[ "def", "generate_glance_url", "(", ")", ":", "# TODO(jk0): This will eventually need to take SSL into consideration", "# when supported in glance.", "return", "\"http://%s:%d\"", "%", "(", "FLAGS", ".", "glance_host", ",", "FLAGS", ".", "glance_port", ")" ]
https://github.com/intel/virtual-storage-manager/blob/00706ab9701acbd0d5e04b19cc80c6b66a2973b8/source/vsm/vsm/utils.py#L973-L977
redis/redis-py
0affa0ed3f3cbcb6dec29b34a580f769f69ae9f7
redis/commands/core.py
python
StreamCommands.xreadgroup
( self, groupname, consumername, streams, count=None, block=None, noack=False )
return self.execute_command("XREADGROUP", *pieces)
Read from a stream via a consumer group. groupname: name of the consumer group. consumername: name of the requesting consumer. streams: a dict of stream names to stream IDs, where IDs indicate the last ID already seen. count: if set, only return this many items, beginning with the earliest available. block: number of milliseconds to wait, if nothing already present. noack: do not add messages to the PEL For more information check https://redis.io/commands/xreadgroup
Read from a stream via a consumer group. groupname: name of the consumer group. consumername: name of the requesting consumer. streams: a dict of stream names to stream IDs, where IDs indicate the last ID already seen. count: if set, only return this many items, beginning with the earliest available. block: number of milliseconds to wait, if nothing already present. noack: do not add messages to the PEL
[ "Read", "from", "a", "stream", "via", "a", "consumer", "group", ".", "groupname", ":", "name", "of", "the", "consumer", "group", ".", "consumername", ":", "name", "of", "the", "requesting", "consumer", ".", "streams", ":", "a", "dict", "of", "stream", "n...
def xreadgroup( self, groupname, consumername, streams, count=None, block=None, noack=False ): """ Read from a stream via a consumer group. groupname: name of the consumer group. consumername: name of the requesting consumer. streams: a dict of stream names to stream IDs, where IDs indicate the last ID already seen. count: if set, only return this many items, beginning with the earliest available. block: number of milliseconds to wait, if nothing already present. noack: do not add messages to the PEL For more information check https://redis.io/commands/xreadgroup """ pieces = [b"GROUP", groupname, consumername] if count is not None: if not isinstance(count, int) or count < 1: raise DataError("XREADGROUP count must be a positive integer") pieces.append(b"COUNT") pieces.append(str(count)) if block is not None: if not isinstance(block, int) or block < 0: raise DataError("XREADGROUP block must be a non-negative " "integer") pieces.append(b"BLOCK") pieces.append(str(block)) if noack: pieces.append(b"NOACK") if not isinstance(streams, dict) or len(streams) == 0: raise DataError("XREADGROUP streams must be a non empty dict") pieces.append(b"STREAMS") pieces.extend(streams.keys()) pieces.extend(streams.values()) return self.execute_command("XREADGROUP", *pieces)
[ "def", "xreadgroup", "(", "self", ",", "groupname", ",", "consumername", ",", "streams", ",", "count", "=", "None", ",", "block", "=", "None", ",", "noack", "=", "False", ")", ":", "pieces", "=", "[", "b\"GROUP\"", ",", "groupname", ",", "consumername", ...
https://github.com/redis/redis-py/blob/0affa0ed3f3cbcb6dec29b34a580f769f69ae9f7/redis/commands/core.py#L2924-L2958
aiidateam/aiida-core
c743a335480f8bb3a5e4ebd2463a31f9f3b9f9b2
aiida/orm/computers.py
python
Computer._transport_type_validator
(cls, transport_type: str)
Validates the transport string.
Validates the transport string.
[ "Validates", "the", "transport", "string", "." ]
def _transport_type_validator(cls, transport_type: str) -> None: """ Validates the transport string. """ from aiida.plugins.entry_point import get_entry_point_names if transport_type not in get_entry_point_names('aiida.transports'): raise exceptions.ValidationError('The specified transport is not a valid one')
[ "def", "_transport_type_validator", "(", "cls", ",", "transport_type", ":", "str", ")", "->", "None", ":", "from", "aiida", ".", "plugins", ".", "entry_point", "import", "get_entry_point_names", "if", "transport_type", "not", "in", "get_entry_point_names", "(", "'...
https://github.com/aiidateam/aiida-core/blob/c743a335480f8bb3a5e4ebd2463a31f9f3b9f9b2/aiida/orm/computers.py#L151-L157
PacktPublishing/Advanced-Deep-Learning-with-Keras
099980731ba4f4e1a847506adf693247e41ef0cb
chapter13-mi-unsupervised/mine-13.8.1.py
python
MINE.eval
(self)
Evaluate the accuracy of the current model weights
Evaluate the accuracy of the current model weights
[ "Evaluate", "the", "accuracy", "of", "the", "current", "model", "weights" ]
def eval(self): """Evaluate the accuracy of the current model weights """ # generate clustering predictions fr test data y_pred = self._encoder.predict(self.x_test) # train a linear classifier # input: clustered data # output: ground truth labels self._classifier.train(y_pred, self.y_test) accuracy = self._classifier.eval(y_pred, self.y_test) info = "Accuracy: %0.2f%%" if self.accuracy > 0: info += ", Old best accuracy: %0.2f%%" data = (accuracy, self.accuracy) else: data = (accuracy) print(info % data) # if accuracy improves during training, # save the model weights on a file if accuracy > self.accuracy \ and self.args.save_weights is not None: folder = self.args.save_dir os.makedirs(folder, exist_ok=True) args = (self.latent_dim, self.args.save_weights) filename = "%d-dim-%s" % args path = os.path.join(folder, filename) print("Saving weights... ", path) self._model.save_weights(path) if accuracy > self.accuracy: self.accuracy = accuracy
[ "def", "eval", "(", "self", ")", ":", "# generate clustering predictions fr test data", "y_pred", "=", "self", ".", "_encoder", ".", "predict", "(", "self", ".", "x_test", ")", "# train a linear classifier", "# input: clustered data", "# output: ground truth labels", "sel...
https://github.com/PacktPublishing/Advanced-Deep-Learning-with-Keras/blob/099980731ba4f4e1a847506adf693247e41ef0cb/chapter13-mi-unsupervised/mine-13.8.1.py#L419-L450
oilshell/oil
94388e7d44a9ad879b12615f6203b38596b5a2d3
Python-2.7.13/Lib/HTMLParser.py
python
HTMLParser.parse_html_declaration
(self, i)
[]
def parse_html_declaration(self, i): rawdata = self.rawdata if rawdata[i:i+2] != '<!': self.error('unexpected call to parse_html_declaration()') if rawdata[i:i+4] == '<!--': # this case is actually already handled in goahead() return self.parse_comment(i) elif rawdata[i:i+3] == '<![': return self.parse_marked_section(i) elif rawdata[i:i+9].lower() == '<!doctype': # find the closing > gtpos = rawdata.find('>', i+9) if gtpos == -1: return -1 self.handle_decl(rawdata[i+2:gtpos]) return gtpos+1 else: return self.parse_bogus_comment(i)
[ "def", "parse_html_declaration", "(", "self", ",", "i", ")", ":", "rawdata", "=", "self", ".", "rawdata", "if", "rawdata", "[", "i", ":", "i", "+", "2", "]", "!=", "'<!'", ":", "self", ".", "error", "(", "'unexpected call to parse_html_declaration()'", ")"...
https://github.com/oilshell/oil/blob/94388e7d44a9ad879b12615f6203b38596b5a2d3/Python-2.7.13/Lib/HTMLParser.py#L237-L254
translate/virtaal
8b0a6fbf764ed92cc44a189499dec399c6423761
virtaal/plugins/tm/tmcontroller.py
python
TMController.send_tm_query
(self, unit=None)
Send a new query to the TM engine. (This method is used as Controller-Model communications)
Send a new query to the TM engine. (This method is used as Controller-Model communications)
[ "Send", "a", "new", "query", "to", "the", "TM", "engine", ".", "(", "This", "method", "is", "used", "as", "Controller", "-", "Model", "communications", ")" ]
def send_tm_query(self, unit=None): """Send a new query to the TM engine. (This method is used as Controller-Model communications)""" if unit is not None: self.unit = unit self.current_query = self.unit.source self.matches = [] self.view.clear() self.emit('start-query', self.unit)
[ "def", "send_tm_query", "(", "self", ",", "unit", "=", "None", ")", ":", "if", "unit", "is", "not", "None", ":", "self", ".", "unit", "=", "unit", "self", ".", "current_query", "=", "self", ".", "unit", ".", "source", "self", ".", "matches", "=", "...
https://github.com/translate/virtaal/blob/8b0a6fbf764ed92cc44a189499dec399c6423761/virtaal/plugins/tm/tmcontroller.py#L169-L178
twitter/zktraffic
82db04d9aafa13f694d4f5c7265069db42c0307c
zktraffic/zab/quorum_packet.py
python
QuorumPacket.zxid_literal
(self)
return self.zxid if self.zxid == -1 else "0x%x" % self.zxid
[]
def zxid_literal(self): return self.zxid if self.zxid == -1 else "0x%x" % self.zxid
[ "def", "zxid_literal", "(", "self", ")", ":", "return", "self", ".", "zxid", "if", "self", ".", "zxid", "==", "-", "1", "else", "\"0x%x\"", "%", "self", ".", "zxid" ]
https://github.com/twitter/zktraffic/blob/82db04d9aafa13f694d4f5c7265069db42c0307c/zktraffic/zab/quorum_packet.py#L121-L122
aqlaboratory/rgn
0133213eea9aa95900d1f16c0c6b9febbeb394cb
model/model.py
python
RGNModel._evaluate
(self, session, pretty=True)
Evaluates loss(es) and returns dicts with the relevant loss(es).
Evaluates loss(es) and returns dicts with the relevant loss(es).
[ "Evaluates", "loss", "(", "es", ")", "and", "returns", "dicts", "with", "the", "relevant", "loss", "(", "es", ")", "." ]
def _evaluate(self, session, pretty=True): """ Evaluates loss(es) and returns dicts with the relevant loss(es). """ if RGNModel._is_started: # evaluate num_invocations = self.config.queueing['num_evaluation_invocations'] for invocation in range(num_invocations): if invocation < num_invocations - 1: evaluation_dict = ops_to_dict(session, self._evaluation_ops) else: evaluation_dict = ops_to_dict(session, merge_dicts(self._evaluation_ops, self._last_evaluation_ops)) # write event summaries to disk if self.config.io['log_model_summaries']: self._summary_writer.add_summary(evaluation_dict['merged_summaries_op'], global_step=evaluation_dict['global_step']) # remove non-user facing ops if pretty: [evaluation_dict.pop(k) for k in evaluation_dict.keys() if 'op' in k] return evaluation_dict else: raise RuntimeError('Model has not been started or has already finished.')
[ "def", "_evaluate", "(", "self", ",", "session", ",", "pretty", "=", "True", ")", ":", "if", "RGNModel", ".", "_is_started", ":", "# evaluate", "num_invocations", "=", "self", ".", "config", ".", "queueing", "[", "'num_evaluation_invocations'", "]", "for", "...
https://github.com/aqlaboratory/rgn/blob/0133213eea9aa95900d1f16c0c6b9febbeb394cb/model/model.py#L293-L314
biolab/orange3
41685e1c7b1d1babe680113685a2d44bcc9fec0b
Orange/preprocess/preprocess.py
python
Randomize.randomize
(table, rand_state=None)
return table
[]
def randomize(table, rand_state=None): rstate = np.random.RandomState(rand_state) if sp.issparse(table): table = table.tocsc() # type: sp.spmatrix for i in range(table.shape[1]): permutation = rstate.permutation(table.shape[0]) col_indices = \ table.indices[table.indptr[i]: table.indptr[i + 1]] col_indices[:] = permutation[col_indices] elif len(table.shape) > 1: for i in range(table.shape[1]): rstate.shuffle(table[:, i]) else: rstate.shuffle(table) return table
[ "def", "randomize", "(", "table", ",", "rand_state", "=", "None", ")", ":", "rstate", "=", "np", ".", "random", ".", "RandomState", "(", "rand_state", ")", "if", "sp", ".", "issparse", "(", "table", ")", ":", "table", "=", "table", ".", "tocsc", "(",...
https://github.com/biolab/orange3/blob/41685e1c7b1d1babe680113685a2d44bcc9fec0b/Orange/preprocess/preprocess.py#L428-L442
tensorflow/tensorboard
61d11d99ef034c30ba20b6a7840c8eededb9031c
tensorboard/plugins/image/images_plugin.py
python
ImagesPlugin._serve_individual_image
(self, request)
return http_util.Respond(request, data, content_type)
Serves an individual image.
Serves an individual image.
[ "Serves", "an", "individual", "image", "." ]
def _serve_individual_image(self, request): """Serves an individual image.""" try: ctx = plugin_util.context(request.environ) blob_key = request.args["blob_key"] data = self._get_generic_data_individual_image(ctx, blob_key) except (KeyError, IndexError): return http_util.Respond( request, "Invalid run, tag, index, or sample", "text/plain", code=400, ) image_type = imghdr.what(None, data) content_type = _IMGHDR_TO_MIMETYPE.get( image_type, _DEFAULT_IMAGE_MIMETYPE ) return http_util.Respond(request, data, content_type)
[ "def", "_serve_individual_image", "(", "self", ",", "request", ")", ":", "try", ":", "ctx", "=", "plugin_util", ".", "context", "(", "request", ".", "environ", ")", "blob_key", "=", "request", ".", "args", "[", "\"blob_key\"", "]", "data", "=", "self", "...
https://github.com/tensorflow/tensorboard/blob/61d11d99ef034c30ba20b6a7840c8eededb9031c/tensorboard/plugins/image/images_plugin.py#L233-L250
saltstack/salt
fae5bc757ad0f1716483ce7ae180b451545c2058
salt/modules/cisconso.py
python
apply_rollback
(datastore, name)
return _proxy_cmd("apply_rollback", datastore, name)
Apply a system rollback :param datastore: The datastore, e.g. running, operational. One of the NETCONF store IETF types :type datastore: :class:`DatastoreType` (``str`` enum). :param name: an ID of the rollback to restore :type name: ``str`` .. code-block:: bash salt cisco-nso cisconso.apply_rollback 52
Apply a system rollback
[ "Apply", "a", "system", "rollback" ]
def apply_rollback(datastore, name): """ Apply a system rollback :param datastore: The datastore, e.g. running, operational. One of the NETCONF store IETF types :type datastore: :class:`DatastoreType` (``str`` enum). :param name: an ID of the rollback to restore :type name: ``str`` .. code-block:: bash salt cisco-nso cisconso.apply_rollback 52 """ return _proxy_cmd("apply_rollback", datastore, name)
[ "def", "apply_rollback", "(", "datastore", ",", "name", ")", ":", "return", "_proxy_cmd", "(", "\"apply_rollback\"", ",", "datastore", ",", "name", ")" ]
https://github.com/saltstack/salt/blob/fae5bc757ad0f1716483ce7ae180b451545c2058/salt/modules/cisconso.py#L116-L131