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
ganeti/ganeti
d340a9ddd12f501bef57da421b5f9b969a4ba905
lib/client/gnt_network.py
python
RenameNetwork
(opts, args)
Rename a network. @param opts: the command line options selected by the user @type args: list @param args: a list of length 2, [old_name, new_name] @rtype: int @return: the desired exit code
Rename a network.
[ "Rename", "a", "network", "." ]
def RenameNetwork(opts, args): """Rename a network. @param opts: the command line options selected by the user @type args: list @param args: a list of length 2, [old_name, new_name] @rtype: int @return: the desired exit code """ network_name, new_name = args op = opcodes.OpNetworkRename(network_name=network_name, new_name=new_name) SubmitOrSend(op, opts)
[ "def", "RenameNetwork", "(", "opts", ",", "args", ")", ":", "network_name", ",", "new_name", "=", "args", "op", "=", "opcodes", ".", "OpNetworkRename", "(", "network_name", "=", "network_name", ",", "new_name", "=", "new_name", ")", "SubmitOrSend", "(", "op"...
https://github.com/ganeti/ganeti/blob/d340a9ddd12f501bef57da421b5f9b969a4ba905/lib/client/gnt_network.py#L325-L337
oracle/oci-python-sdk
3c1604e4e212008fb6718e2f68cdb5ef71fd5793
examples/container_engine.py
python
update_node_pool
(ce_client, node_pool_id)
return
update_node_pool Currently there are a number of features that can be updated in the node pool. This example will only update the name. Please see the documentation for the other features which can be updated
update_node_pool
[ "update_node_pool" ]
def update_node_pool(ce_client, node_pool_id): """ update_node_pool Currently there are a number of features that can be updated in the node pool. This example will only update the name. Please see the documentation for the other features which can be updated """ update_node_pool_details = oci.container_engine.models.UpdateNodePoolDetails(name="PythonSDK_noodpool_1") ce_composite_ops = oci.container_engine.ContainerEngineClientCompositeOperations(ce_client) response = ce_composite_ops.update_node_pool_and_wait_for_state(node_pool_id, update_node_pool_details, wait_for_states=[oci.container_engine.models.WorkRequest.STATUS_SUCCEEDED, oci.container_engine.models.WorkRequest.STATUS_FAILED]) if response.data.status == oci.container_engine.models.WorkRequest.STATUS_FAILED: get_work_request_errors(ce_client, compartment_id, response.data.id) else: print("Update node pool succeeded") return
[ "def", "update_node_pool", "(", "ce_client", ",", "node_pool_id", ")", ":", "update_node_pool_details", "=", "oci", ".", "container_engine", ".", "models", ".", "UpdateNodePoolDetails", "(", "name", "=", "\"PythonSDK_noodpool_1\"", ")", "ce_composite_ops", "=", "oci",...
https://github.com/oracle/oci-python-sdk/blob/3c1604e4e212008fb6718e2f68cdb5ef71fd5793/examples/container_engine.py#L198-L221
hzy46/Deep-Learning-21-Examples
15c2d9edccad090cd67b033f24a43c544e5cba3e
chapter_6/src/models/inception_resnet_v2.py
python
inception_resnet_v2
(inputs, is_training=True, dropout_keep_prob=0.8, bottleneck_layer_size=128, reuse=None, scope='InceptionResnetV2')
return net, end_points
Creates the Inception Resnet V2 model. Args: inputs: a 4-D tensor of size [batch_size, height, width, 3]. num_classes: number of predicted classes. is_training: whether is training or not. dropout_keep_prob: float, the fraction to keep before final layer. reuse: whether or not the network and its variables should be reused. To be able to reuse 'scope' must be given. scope: Optional variable_scope. Returns: logits: the logits outputs of the model. end_points: the set of end_points from the inception model.
Creates the Inception Resnet V2 model. Args: inputs: a 4-D tensor of size [batch_size, height, width, 3]. num_classes: number of predicted classes. is_training: whether is training or not. dropout_keep_prob: float, the fraction to keep before final layer. reuse: whether or not the network and its variables should be reused. To be able to reuse 'scope' must be given. scope: Optional variable_scope. Returns: logits: the logits outputs of the model. end_points: the set of end_points from the inception model.
[ "Creates", "the", "Inception", "Resnet", "V2", "model", ".", "Args", ":", "inputs", ":", "a", "4", "-", "D", "tensor", "of", "size", "[", "batch_size", "height", "width", "3", "]", ".", "num_classes", ":", "number", "of", "predicted", "classes", ".", "...
def inception_resnet_v2(inputs, is_training=True, dropout_keep_prob=0.8, bottleneck_layer_size=128, reuse=None, scope='InceptionResnetV2'): """Creates the Inception Resnet V2 model. Args: inputs: a 4-D tensor of size [batch_size, height, width, 3]. num_classes: number of predicted classes. is_training: whether is training or not. dropout_keep_prob: float, the fraction to keep before final layer. reuse: whether or not the network and its variables should be reused. To be able to reuse 'scope' must be given. scope: Optional variable_scope. Returns: logits: the logits outputs of the model. end_points: the set of end_points from the inception model. """ end_points = {} with tf.variable_scope(scope, 'InceptionResnetV2', [inputs], reuse=reuse): with slim.arg_scope([slim.batch_norm, slim.dropout], is_training=is_training): with slim.arg_scope([slim.conv2d, slim.max_pool2d, slim.avg_pool2d], stride=1, padding='SAME'): # 149 x 149 x 32 net = slim.conv2d(inputs, 32, 3, stride=2, padding='VALID', scope='Conv2d_1a_3x3') end_points['Conv2d_1a_3x3'] = net # 147 x 147 x 32 net = slim.conv2d(net, 32, 3, padding='VALID', scope='Conv2d_2a_3x3') end_points['Conv2d_2a_3x3'] = net # 147 x 147 x 64 net = slim.conv2d(net, 64, 3, scope='Conv2d_2b_3x3') end_points['Conv2d_2b_3x3'] = net # 73 x 73 x 64 net = slim.max_pool2d(net, 3, stride=2, padding='VALID', scope='MaxPool_3a_3x3') end_points['MaxPool_3a_3x3'] = net # 73 x 73 x 80 net = slim.conv2d(net, 80, 1, padding='VALID', scope='Conv2d_3b_1x1') end_points['Conv2d_3b_1x1'] = net # 71 x 71 x 192 net = slim.conv2d(net, 192, 3, padding='VALID', scope='Conv2d_4a_3x3') end_points['Conv2d_4a_3x3'] = net # 35 x 35 x 192 net = slim.max_pool2d(net, 3, stride=2, padding='VALID', scope='MaxPool_5a_3x3') end_points['MaxPool_5a_3x3'] = net # 35 x 35 x 320 with tf.variable_scope('Mixed_5b'): with tf.variable_scope('Branch_0'): tower_conv = slim.conv2d(net, 96, 1, scope='Conv2d_1x1') with tf.variable_scope('Branch_1'): tower_conv1_0 = slim.conv2d(net, 48, 1, scope='Conv2d_0a_1x1') tower_conv1_1 = slim.conv2d(tower_conv1_0, 64, 5, scope='Conv2d_0b_5x5') with tf.variable_scope('Branch_2'): tower_conv2_0 = slim.conv2d(net, 64, 1, scope='Conv2d_0a_1x1') tower_conv2_1 = slim.conv2d(tower_conv2_0, 96, 3, scope='Conv2d_0b_3x3') tower_conv2_2 = slim.conv2d(tower_conv2_1, 96, 3, scope='Conv2d_0c_3x3') with tf.variable_scope('Branch_3'): tower_pool = slim.avg_pool2d(net, 3, stride=1, padding='SAME', scope='AvgPool_0a_3x3') tower_pool_1 = slim.conv2d(tower_pool, 64, 1, scope='Conv2d_0b_1x1') net = tf.concat([tower_conv, tower_conv1_1, tower_conv2_2, tower_pool_1], 3) end_points['Mixed_5b'] = net net = slim.repeat(net, 10, block35, scale=0.17) # 17 x 17 x 1024 with tf.variable_scope('Mixed_6a'): with tf.variable_scope('Branch_0'): tower_conv = slim.conv2d(net, 384, 3, stride=2, padding='VALID', scope='Conv2d_1a_3x3') with tf.variable_scope('Branch_1'): tower_conv1_0 = slim.conv2d(net, 256, 1, scope='Conv2d_0a_1x1') tower_conv1_1 = slim.conv2d(tower_conv1_0, 256, 3, scope='Conv2d_0b_3x3') tower_conv1_2 = slim.conv2d(tower_conv1_1, 384, 3, stride=2, padding='VALID', scope='Conv2d_1a_3x3') with tf.variable_scope('Branch_2'): tower_pool = slim.max_pool2d(net, 3, stride=2, padding='VALID', scope='MaxPool_1a_3x3') net = tf.concat([tower_conv, tower_conv1_2, tower_pool], 3) end_points['Mixed_6a'] = net net = slim.repeat(net, 20, block17, scale=0.10) with tf.variable_scope('Mixed_7a'): with tf.variable_scope('Branch_0'): tower_conv = slim.conv2d(net, 256, 1, scope='Conv2d_0a_1x1') tower_conv_1 = slim.conv2d(tower_conv, 384, 3, stride=2, padding='VALID', scope='Conv2d_1a_3x3') with tf.variable_scope('Branch_1'): tower_conv1 = slim.conv2d(net, 256, 1, scope='Conv2d_0a_1x1') tower_conv1_1 = slim.conv2d(tower_conv1, 288, 3, stride=2, padding='VALID', scope='Conv2d_1a_3x3') with tf.variable_scope('Branch_2'): tower_conv2 = slim.conv2d(net, 256, 1, scope='Conv2d_0a_1x1') tower_conv2_1 = slim.conv2d(tower_conv2, 288, 3, scope='Conv2d_0b_3x3') tower_conv2_2 = slim.conv2d(tower_conv2_1, 320, 3, stride=2, padding='VALID', scope='Conv2d_1a_3x3') with tf.variable_scope('Branch_3'): tower_pool = slim.max_pool2d(net, 3, stride=2, padding='VALID', scope='MaxPool_1a_3x3') net = tf.concat([tower_conv_1, tower_conv1_1, tower_conv2_2, tower_pool], 3) end_points['Mixed_7a'] = net net = slim.repeat(net, 9, block8, scale=0.20) net = block8(net, activation_fn=None) net = slim.conv2d(net, 1536, 1, scope='Conv2d_7b_1x1') end_points['Conv2d_7b_1x1'] = net with tf.variable_scope('Logits'): end_points['PrePool'] = net #pylint: disable=no-member net = slim.avg_pool2d(net, net.get_shape()[1:3], padding='VALID', scope='AvgPool_1a_8x8') net = slim.flatten(net) net = slim.dropout(net, dropout_keep_prob, is_training=is_training, scope='Dropout') end_points['PreLogitsFlatten'] = net net = slim.fully_connected(net, bottleneck_layer_size, activation_fn=None, scope='Bottleneck', reuse=False) return net, end_points
[ "def", "inception_resnet_v2", "(", "inputs", ",", "is_training", "=", "True", ",", "dropout_keep_prob", "=", "0.8", ",", "bottleneck_layer_size", "=", "128", ",", "reuse", "=", "None", ",", "scope", "=", "'InceptionResnetV2'", ")", ":", "end_points", "=", "{",...
https://github.com/hzy46/Deep-Learning-21-Examples/blob/15c2d9edccad090cd67b033f24a43c544e5cba3e/chapter_6/src/models/inception_resnet_v2.py#L112-L255
Chaffelson/nipyapi
d3b186fd701ce308c2812746d98af9120955e810
nipyapi/registry/api_client.py
python
ApiClient.__deserialize_model
(self, data, klass)
return instance
Deserializes list or dict to model. :param data: dict, list. :param klass: class literal. :return: model object.
Deserializes list or dict to model.
[ "Deserializes", "list", "or", "dict", "to", "model", "." ]
def __deserialize_model(self, data, klass): """ Deserializes list or dict to model. :param data: dict, list. :param klass: class literal. :return: model object. """ if not klass.swagger_types: return data kwargs = {} for attr, attr_type in iteritems(klass.swagger_types): if data is not None \ and klass.attribute_map[attr] in data \ and isinstance(data, (list, dict)): value = data[klass.attribute_map[attr]] if attr_type.startswith('list['): # if this is a list, we may get back a single item # or a list # create the list object if it doesn't exist # append the return if not kwargs.get(attr): kwargs[attr] = [] deserialized_value = self.__deserialize(value, attr_type) if deserialized_value: if isinstance(deserialized_value, list): kwargs[attr].extend(deserialized_value) else: kwargs[attr].append(deserialized_value) else: kwargs[attr] = self.__deserialize(value, attr_type) instance = klass(**kwargs) return instance
[ "def", "__deserialize_model", "(", "self", ",", "data", ",", "klass", ")", ":", "if", "not", "klass", ".", "swagger_types", ":", "return", "data", "kwargs", "=", "{", "}", "for", "attr", ",", "attr_type", "in", "iteritems", "(", "klass", ".", "swagger_ty...
https://github.com/Chaffelson/nipyapi/blob/d3b186fd701ce308c2812746d98af9120955e810/nipyapi/registry/api_client.py#L632-L667
NVIDIA/NeMo
5b0c0b4dec12d87d3cd960846de4105309ce938e
nemo/collections/tts/modules/squeezewave.py
python
SqueezeWaveModule.input_example
(self)
return tuple([mel])
Generates input examples for tracing etc. Returns: A tuple of input examples.
Generates input examples for tracing etc. Returns: A tuple of input examples.
[ "Generates", "input", "examples", "for", "tracing", "etc", ".", "Returns", ":", "A", "tuple", "of", "input", "examples", "." ]
def input_example(self): """ Generates input examples for tracing etc. Returns: A tuple of input examples. """ par = next(self.parameters()) mel = torch.randn((1, self.n_mel_channels, 96), device=par.device, dtype=par.dtype) return tuple([mel])
[ "def", "input_example", "(", "self", ")", ":", "par", "=", "next", "(", "self", ".", "parameters", "(", ")", ")", "mel", "=", "torch", ".", "randn", "(", "(", "1", ",", "self", ".", "n_mel_channels", ",", "96", ")", ",", "device", "=", "par", "."...
https://github.com/NVIDIA/NeMo/blob/5b0c0b4dec12d87d3cd960846de4105309ce938e/nemo/collections/tts/modules/squeezewave.py#L153-L161
tenable/pyTenable
1ccab9fc6f6e4c9f1cfe5128f694388ea112719d
tenable/sc/current.py
python
CurrentSessionAPI.org
(self, fields=None)
return self._api.get('currentOrganization', params=params).json()['response']
Returns the organization of the current session. :sc-api:`current-organization <Current-Organization.html>` Args: fields (list, optional): The list of fields that are desired to be returned. For details on what fields are available, please refer to the details on the request within the organization list API doc. Returns: :obj:`dict`: The organization record. Examples: >>> org = sc.current.org()
Returns the organization of the current session.
[ "Returns", "the", "organization", "of", "the", "current", "session", "." ]
def org(self, fields=None): ''' Returns the organization of the current session. :sc-api:`current-organization <Current-Organization.html>` Args: fields (list, optional): The list of fields that are desired to be returned. For details on what fields are available, please refer to the details on the request within the organization list API doc. Returns: :obj:`dict`: The organization record. Examples: >>> org = sc.current.org() ''' params = dict() if fields: params['fields'] = ','.join([self._check('field', f, str) for f in fields]) return self._api.get('currentOrganization', params=params).json()['response']
[ "def", "org", "(", "self", ",", "fields", "=", "None", ")", ":", "params", "=", "dict", "(", ")", "if", "fields", ":", "params", "[", "'fields'", "]", "=", "','", ".", "join", "(", "[", "self", ".", "_check", "(", "'field'", ",", "f", ",", "str...
https://github.com/tenable/pyTenable/blob/1ccab9fc6f6e4c9f1cfe5128f694388ea112719d/tenable/sc/current.py#L33-L55
python/cpython
e13cdca0f5224ec4e23bdd04bb3120506964bc8b
Lib/datetime.py
python
_days_before_month
(year, month)
return _DAYS_BEFORE_MONTH[month] + (month > 2 and _is_leap(year))
year, month -> number of days in year preceding first day of month.
year, month -> number of days in year preceding first day of month.
[ "year", "month", "-", ">", "number", "of", "days", "in", "year", "preceding", "first", "day", "of", "month", "." ]
def _days_before_month(year, month): "year, month -> number of days in year preceding first day of month." assert 1 <= month <= 12, 'month must be in 1..12' return _DAYS_BEFORE_MONTH[month] + (month > 2 and _is_leap(year))
[ "def", "_days_before_month", "(", "year", ",", "month", ")", ":", "assert", "1", "<=", "month", "<=", "12", ",", "'month must be in 1..12'", "return", "_DAYS_BEFORE_MONTH", "[", "month", "]", "+", "(", "month", ">", "2", "and", "_is_leap", "(", "year", ")"...
https://github.com/python/cpython/blob/e13cdca0f5224ec4e23bdd04bb3120506964bc8b/Lib/datetime.py#L58-L61
git-cola/git-cola
b48b8028e0c3baf47faf7b074b9773737358163d
cola/widgets/status.py
python
show_help
(context)
return text.text_dialog(context, help_text, title)
[]
def show_help(context): help_text = N_( r""" Format String Variables ----------------------- %(path)s = relative file path %(abspath)s = absolute file path %(dirname)s = relative directory path %(absdirname)s = absolute directory path %(filename)s = file basename %(basename)s = file basename without extension %(ext)s = file extension """ ) title = N_('Help - Custom Copy Actions') return text.text_dialog(context, help_text, title)
[ "def", "show_help", "(", "context", ")", ":", "help_text", "=", "N_", "(", "r\"\"\"\n Format String Variables\n -----------------------\n %(path)s = relative file path\n %(abspath)s = absolute file path\n %(dirname)s = relative directory path\n %(absdi...
https://github.com/git-cola/git-cola/blob/b48b8028e0c3baf47faf7b074b9773737358163d/cola/widgets/status.py#L1249-L1264
shiweibsw/Translation-Tools
2fbbf902364e557fa7017f9a74a8797b7440c077
venv/Lib/site-packages/pip-9.0.3-py3.6.egg/pip/_vendor/pyparsing.py
python
Or.parseImpl
( self, instring, loc, doActions=True )
[]
def parseImpl( self, instring, loc, doActions=True ): maxExcLoc = -1 maxException = None matches = [] for e in self.exprs: try: loc2 = e.tryParse( instring, loc ) except ParseException as err: err.__traceback__ = None if err.loc > maxExcLoc: maxException = err maxExcLoc = err.loc except IndexError: if len(instring) > maxExcLoc: maxException = ParseException(instring,len(instring),e.errmsg,self) maxExcLoc = len(instring) else: # save match among all matches, to retry longest to shortest matches.append((loc2, e)) if matches: matches.sort(key=lambda x: -x[0]) for _,e in matches: try: return e._parse( instring, loc, doActions ) except ParseException as err: err.__traceback__ = None if err.loc > maxExcLoc: maxException = err maxExcLoc = err.loc if maxException is not None: maxException.msg = self.errmsg raise maxException else: raise ParseException(instring, loc, "no defined alternatives to match", self)
[ "def", "parseImpl", "(", "self", ",", "instring", ",", "loc", ",", "doActions", "=", "True", ")", ":", "maxExcLoc", "=", "-", "1", "maxException", "=", "None", "matches", "=", "[", "]", "for", "e", "in", "self", ".", "exprs", ":", "try", ":", "loc2...
https://github.com/shiweibsw/Translation-Tools/blob/2fbbf902364e557fa7017f9a74a8797b7440c077/venv/Lib/site-packages/pip-9.0.3-py3.6.egg/pip/_vendor/pyparsing.py#L3424-L3459
marcoeilers/nagini
a2a19df7d833e67841e03c9885869c3dddef3327
src/nagini_contracts/contracts.py
python
LowExit
()
Predicate that states that whether the current loop has been left via a break or return statement does not depend on high data.
Predicate that states that whether the current loop has been left via a break or return statement does not depend on high data.
[ "Predicate", "that", "states", "that", "whether", "the", "current", "loop", "has", "been", "left", "via", "a", "break", "or", "return", "statement", "does", "not", "depend", "on", "high", "data", "." ]
def LowExit() -> bool: """ Predicate that states that whether the current loop has been left via a break or return statement does not depend on high data. """ pass
[ "def", "LowExit", "(", ")", "->", "bool", ":", "pass" ]
https://github.com/marcoeilers/nagini/blob/a2a19df7d833e67841e03c9885869c3dddef3327/src/nagini_contracts/contracts.py#L125-L130
neubig/nn4nlp-code
970d91a51664b3d91a9822b61cd76abea20218cb
14-semparsing/ucca/scripts/distances/align.py
python
align
(sen1, sen2, string=True)
return mapping, refactored_indexes
finds the best mapping of words from one sentence to the other string = a boolean represents if sentences are given as strings or as list of ucca terminal nodes returns list of word tuples and the corresponding list of indexes tuples
finds the best mapping of words from one sentence to the other string = a boolean represents if sentences are given as strings or as list of ucca terminal nodes returns list of word tuples and the corresponding list of indexes tuples
[ "finds", "the", "best", "mapping", "of", "words", "from", "one", "sentence", "to", "the", "other", "string", "=", "a", "boolean", "represents", "if", "sentences", "are", "given", "as", "strings", "or", "as", "list", "of", "ucca", "terminal", "nodes", "retu...
def align(sen1, sen2, string=True): """finds the best mapping of words from one sentence to the other string = a boolean represents if sentences are given as strings or as list of ucca terminal nodes returns list of word tuples and the corresponding list of indexes tuples""" if string: sen1 = list(map(preprocess_word, sen1.split())) sen2 = list(map(preprocess_word, sen2.split())) else: sen1 = [preprocess_word(terminal.text) for terminal in sen1] sen2 = [preprocess_word(terminal.text) for terminal in sen2] # find lengths length_dif = len(sen1) - len(sen2) if length_dif > 0: shorter = sen2 longer = sen1 switched = False else: shorter = sen1 longer = sen2 switched = True length_dif = abs(length_dif) shorter += ["emptyWord"] * length_dif # create matrix matrix = np.zeros((len(longer), len(longer))) for i in range(len(longer)): for j in range(len(longer) - length_dif): matrix[i, j] = distance.levenshtein(longer[i], shorter[j]) + float(abs(i - j)) / len(longer) # compare with munkres m = Munkres() indexes = m.compute(matrix) # remove indexing for emptywords and create string mapping refactored_indexes = [] mapping = [] start = 0 if string else 1 for i, j in indexes: if j >= len(longer) - length_dif: j = -1 - start if switched: refactored_indexes.append((j + start, i + start)) mapping.append((shorter[j], longer[i])) else: refactored_indexes.append((i + start, j + start)) mapping.append((longer[i], shorter[j])) return mapping, refactored_indexes
[ "def", "align", "(", "sen1", ",", "sen2", ",", "string", "=", "True", ")", ":", "if", "string", ":", "sen1", "=", "list", "(", "map", "(", "preprocess_word", ",", "sen1", ".", "split", "(", ")", ")", ")", "sen2", "=", "list", "(", "map", "(", "...
https://github.com/neubig/nn4nlp-code/blob/970d91a51664b3d91a9822b61cd76abea20218cb/14-semparsing/ucca/scripts/distances/align.py#L56-L103
chdsbd/kodiak
4c705cea8edaa2792f2a59700a2f7c3d75b6e918
web_api/web_api/views.py
python
plan_id_from_period
(period: Literal["month", "year"])
return None
[]
def plan_id_from_period(period: Literal["month", "year"]) -> str: if period == "month": return cast(str, settings.STRIPE_PLAN_ID) if period == "year": return cast(str, settings.STRIPE_ANNUAL_PLAN_ID) return None
[ "def", "plan_id_from_period", "(", "period", ":", "Literal", "[", "\"month\"", ",", "\"year\"", "]", ")", "->", "str", ":", "if", "period", "==", "\"month\"", ":", "return", "cast", "(", "str", ",", "settings", ".", "STRIPE_PLAN_ID", ")", "if", "period", ...
https://github.com/chdsbd/kodiak/blob/4c705cea8edaa2792f2a59700a2f7c3d75b6e918/web_api/web_api/views.py#L498-L503
tensorflow/tfx
b4a6b83269815ed12ba9df9e9154c7376fef2ea0
tfx/orchestration/portable/mlmd/execution_lib.py
python
get_executions_associated_with_all_contexts
( metadata_handler: metadata.Metadata, contexts: Iterable[metadata_store_pb2.Context] )
return list(executions_dict.values()) if executions_dict else []
Returns executions that are associated with all given contexts. Args: metadata_handler: A handler to access MLMD. contexts: MLMD contexts for which to fetch associated executions. Returns: A list of executions associated with all given contexts.
Returns executions that are associated with all given contexts.
[ "Returns", "executions", "that", "are", "associated", "with", "all", "given", "contexts", "." ]
def get_executions_associated_with_all_contexts( metadata_handler: metadata.Metadata, contexts: Iterable[metadata_store_pb2.Context] ) -> List[metadata_store_pb2.Execution]: """Returns executions that are associated with all given contexts. Args: metadata_handler: A handler to access MLMD. contexts: MLMD contexts for which to fetch associated executions. Returns: A list of executions associated with all given contexts. """ executions_dict = None for context in contexts: executions = metadata_handler.store.get_executions_by_context(context.id) if executions_dict is None: executions_dict = {e.id: e for e in executions} else: executions_dict = {e.id: e for e in executions if e.id in executions_dict} return list(executions_dict.values()) if executions_dict else []
[ "def", "get_executions_associated_with_all_contexts", "(", "metadata_handler", ":", "metadata", ".", "Metadata", ",", "contexts", ":", "Iterable", "[", "metadata_store_pb2", ".", "Context", "]", ")", "->", "List", "[", "metadata_store_pb2", ".", "Execution", "]", ":...
https://github.com/tensorflow/tfx/blob/b4a6b83269815ed12ba9df9e9154c7376fef2ea0/tfx/orchestration/portable/mlmd/execution_lib.py#L245-L265
triaquae/triaquae
bbabf736b3ba56a0c6498e7f04e16c13b8b8f2b9
TriAquae/views.py
python
getSuccessLists
(request)
return HttpResponse(json.dumps(ip_list))
[]
def getSuccessLists(request): track_id = request.GET['TrackMark'] ret_list = OpsLogTemp.objects.filter(track_mark = track_id,result = "Success") ip_list = [] for ip in ret_list: ip_list.append(ip.ip) return HttpResponse(json.dumps(ip_list))
[ "def", "getSuccessLists", "(", "request", ")", ":", "track_id", "=", "request", ".", "GET", "[", "'TrackMark'", "]", "ret_list", "=", "OpsLogTemp", ".", "objects", ".", "filter", "(", "track_mark", "=", "track_id", ",", "result", "=", "\"Success\"", ")", "...
https://github.com/triaquae/triaquae/blob/bbabf736b3ba56a0c6498e7f04e16c13b8b8f2b9/TriAquae/views.py#L273-L279
pytorch/fairseq
1575f30dd0a9f7b3c499db0b4767aa4e9f79056c
fairseq/modules/quantization/pq/utils.py
python
SizeTracker.update
(self, W, block_size, n_centroids)
Updates the running statistics when quantizing a new layer.
Updates the running statistics when quantizing a new layer.
[ "Updates", "the", "running", "statistics", "when", "quantizing", "a", "new", "layer", "." ]
def update(self, W, block_size, n_centroids): """ Updates the running statistics when quantizing a new layer. """ # bits per weights bits_per_weight = np.log2(n_centroids) / block_size self.n_quantized_layers += 1 # size of indexing the subvectors of size block_size (in MB) size_index_layer = bits_per_weight * W.numel() / 8 / 1024 / 1024 self.size_index += size_index_layer # size of the centroids stored in float16 (in MB) size_centroids_layer = n_centroids * block_size * 2 / 1024 / 1024 self.size_centroids += size_centroids_layer # size of non-compressed layers, e.g. LayerNorms or biases (in MB) size_uncompressed_layer = W.numel() * 4 / 1024 / 1024 self.size_non_quantized -= size_uncompressed_layer
[ "def", "update", "(", "self", ",", "W", ",", "block_size", ",", "n_centroids", ")", ":", "# bits per weights", "bits_per_weight", "=", "np", ".", "log2", "(", "n_centroids", ")", "/", "block_size", "self", ".", "n_quantized_layers", "+=", "1", "# size of index...
https://github.com/pytorch/fairseq/blob/1575f30dd0a9f7b3c499db0b4767aa4e9f79056c/fairseq/modules/quantization/pq/utils.py#L326-L345
mozman/ezdxf
59d0fc2ea63f5cf82293428f5931da7e9f9718e9
src/ezdxf/math/_matrix44.py
python
Matrix44.__imul__
(self, other: "Matrix44")
return self
Inplace multiplication with another matrix.
Inplace multiplication with another matrix.
[ "Inplace", "multiplication", "with", "another", "matrix", "." ]
def __imul__(self, other: "Matrix44") -> "Matrix44": """Inplace multiplication with another matrix.""" m1 = self._matrix m2 = other._matrix # fmt: off self._matrix = [ m1[0] * m2[0] + m1[1] * m2[4] + m1[2] * m2[8] + m1[3] * m2[12], m1[0] * m2[1] + m1[1] * m2[5] + m1[2] * m2[9] + m1[3] * m2[13], m1[0] * m2[2] + m1[1] * m2[6] + m1[2] * m2[10] + m1[3] * m2[14], m1[0] * m2[3] + m1[1] * m2[7] + m1[2] * m2[11] + m1[3] * m2[15], m1[4] * m2[0] + m1[5] * m2[4] + m1[6] * m2[8] + m1[7] * m2[12], m1[4] * m2[1] + m1[5] * m2[5] + m1[6] * m2[9] + m1[7] * m2[13], m1[4] * m2[2] + m1[5] * m2[6] + m1[6] * m2[10] + m1[7] * m2[14], m1[4] * m2[3] + m1[5] * m2[7] + m1[6] * m2[11] + m1[7] * m2[15], m1[8] * m2[0] + m1[9] * m2[4] + m1[10] * m2[8] + m1[11] * m2[12], m1[8] * m2[1] + m1[9] * m2[5] + m1[10] * m2[9] + m1[11] * m2[13], m1[8] * m2[2] + m1[9] * m2[6] + m1[10] * m2[10] + m1[11] * m2[14], m1[8] * m2[3] + m1[9] * m2[7] + m1[10] * m2[11] + m1[11] * m2[15], m1[12] * m2[0] + m1[13] * m2[4] + m1[14] * m2[8] + m1[15] * m2[12], m1[12] * m2[1] + m1[13] * m2[5] + m1[14] * m2[9] + m1[15] * m2[13], m1[12] * m2[2] + m1[13] * m2[6] + m1[14] * m2[10] + m1[15] * m2[14], m1[12] * m2[3] + m1[13] * m2[7] + m1[14] * m2[11] + m1[15] * m2[15] ] # fmt: on return self
[ "def", "__imul__", "(", "self", ",", "other", ":", "\"Matrix44\"", ")", "->", "\"Matrix44\"", ":", "m1", "=", "self", ".", "_matrix", "m2", "=", "other", ".", "_matrix", "# fmt: off", "self", ".", "_matrix", "=", "[", "m1", "[", "0", "]", "*", "m2", ...
https://github.com/mozman/ezdxf/blob/59d0fc2ea63f5cf82293428f5931da7e9f9718e9/src/ezdxf/math/_matrix44.py#L509-L536
cloudera/impyla
0c736af4cad2bade9b8e313badc08ec50e81c948
impala/_thrift_gen/hive_metastore/ThriftHiveMetastore.py
python
add_partitions_args.read
(self, iprot)
[]
def read(self, iprot): if iprot._fast_decode is not None and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None: iprot._fast_decode(self, iprot, [self.__class__, self.thrift_spec]) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 1: if ftype == TType.LIST: self.new_parts = [] (_etype711, _size708) = iprot.readListBegin() for _i712 in range(_size708): _elem713 = Partition() _elem713.read(iprot) self.new_parts.append(_elem713) iprot.readListEnd() else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd()
[ "def", "read", "(", "self", ",", "iprot", ")", ":", "if", "iprot", ".", "_fast_decode", "is", "not", "None", "and", "isinstance", "(", "iprot", ".", "trans", ",", "TTransport", ".", "CReadableTransport", ")", "and", "self", ".", "thrift_spec", "is", "not...
https://github.com/cloudera/impyla/blob/0c736af4cad2bade9b8e313badc08ec50e81c948/impala/_thrift_gen/hive_metastore/ThriftHiveMetastore.py#L16804-L16827
paulproteus/python-scraping-code-samples
4e5396d4e311ca66c784a2b5f859308285e511da
new/seleniumrc/selenium.py
python
selenium.type
(self,locator,value)
Sets the value of an input field, as though you typed it in. Can also be used to set the value of combo boxes, check boxes, etc. In these cases, value should be the value of the option selected, not the visible text. 'locator' is an element locator 'value' is the value to type
Sets the value of an input field, as though you typed it in. Can also be used to set the value of combo boxes, check boxes, etc. In these cases, value should be the value of the option selected, not the visible text. 'locator' is an element locator 'value' is the value to type
[ "Sets", "the", "value", "of", "an", "input", "field", "as", "though", "you", "typed", "it", "in", ".", "Can", "also", "be", "used", "to", "set", "the", "value", "of", "combo", "boxes", "check", "boxes", "etc", ".", "In", "these", "cases", "value", "s...
def type(self,locator,value): """ Sets the value of an input field, as though you typed it in. Can also be used to set the value of combo boxes, check boxes, etc. In these cases, value should be the value of the option selected, not the visible text. 'locator' is an element locator 'value' is the value to type """ self.do_command("type", [locator,value,])
[ "def", "type", "(", "self", ",", "locator", ",", "value", ")", ":", "self", ".", "do_command", "(", "\"type\"", ",", "[", "locator", ",", "value", ",", "]", ")" ]
https://github.com/paulproteus/python-scraping-code-samples/blob/4e5396d4e311ca66c784a2b5f859308285e511da/new/seleniumrc/selenium.py#L578-L590
tensorflow/graphics
86997957324bfbdd85848daae989b4c02588faa0
tensorflow_graphics/geometry/transformation/dual_quaternion.py
python
to_rotation_translation
( dual_quaternion: type_alias.TensorLike, name: str = "dual_quaternion_to_rot_trans")
Converts a dual quaternion into a quaternion for rotation and translation. Args: dual_quaternion: A `[A1, ..., An, 8]`-tensor, where the last dimension represents a qual quaternion. name: A name for this op that defaults to "dual_quaternion_to_rot_trans". Returns: A tuple with a `[A1, ..., An, 4]`-tensor for rotation in quaternion form, and a `[A1, ..., An, 3]`-tensor for translation, in that order.
Converts a dual quaternion into a quaternion for rotation and translation.
[ "Converts", "a", "dual", "quaternion", "into", "a", "quaternion", "for", "rotation", "and", "translation", "." ]
def to_rotation_translation( dual_quaternion: type_alias.TensorLike, name: str = "dual_quaternion_to_rot_trans") -> Tuple[tf.Tensor, tf.Tensor]: """Converts a dual quaternion into a quaternion for rotation and translation. Args: dual_quaternion: A `[A1, ..., An, 8]`-tensor, where the last dimension represents a qual quaternion. name: A name for this op that defaults to "dual_quaternion_to_rot_trans". Returns: A tuple with a `[A1, ..., An, 4]`-tensor for rotation in quaternion form, and a `[A1, ..., An, 3]`-tensor for translation, in that order. """ with tf.name_scope(name): dual_quaternion = tf.convert_to_tensor(value=dual_quaternion) shape.check_static( tensor=dual_quaternion, tensor_name="dual_quaternion", has_dim_equals=(-1, 8)) rotation = dual_quaternion[..., 0:4] translation = 2 * quaternion.multiply( dual_quaternion[..., 4:8], quaternion.inverse(rotation)) translation = translation[..., 0:3] return rotation, translation
[ "def", "to_rotation_translation", "(", "dual_quaternion", ":", "type_alias", ".", "TensorLike", ",", "name", ":", "str", "=", "\"dual_quaternion_to_rot_trans\"", ")", "->", "Tuple", "[", "tf", ".", "Tensor", ",", "tf", ".", "Tensor", "]", ":", "with", "tf", ...
https://github.com/tensorflow/graphics/blob/86997957324bfbdd85848daae989b4c02588faa0/tensorflow_graphics/geometry/transformation/dual_quaternion.py#L308-L335
vmware/pyvmomi
5a738bef64efe8daea037ba9e8e0d566a0cc584c
pyVim/sso.py
python
SsoAuthenticator.get_bearer_saml_assertion
(self, username, password, public_key=None, private_key=None, request_duration=60, token_duration=600, delegatable=False, renewable=False, ssl_context=None)
return etree.tostring( _extract_element(etree.fromstring(bearer_token), 'Assertion', {'saml2': "urn:oasis:names:tc:SAML:2.0:assertion"}), pretty_print=False).decode(UTF_8)
Extracts the assertion from the Bearer Token received from the Security Token Service. @type username: C{str} @param username: Username for the user for which bearer token needs to be requested. @type password: C{str} @param password: Password for the user for which bearer token needs to be requested. @type public_key: C{str} @param public_key: File containing the public key for the service user registered with SSO, in PEM format. @type private_key: C{str} @param private_key: File containing the private key for the service user registered with SSO, in PEM format. @type request_duration: C{long} @param request_duration: The duration for which the request is valid. If the STS receives this request after this duration, it is assumed to have expired. The duration is in seconds and the default is 60s. @type token_duration: C{long} @param token_duration: The duration for which the SAML token is issued for. The duration is specified in seconds and the default is 600s. @type delegatable: C{boolean} @param delegatable: Whether the generated token is delegatable or not The default value is False @type ssl_context: C{ssl.SSLContext} @param ssl_context: SSL context describing the various SSL options. It is only supported in Python 2.7.9 or higher. @rtype: C{str} @return: The SAML assertion in Unicode.
Extracts the assertion from the Bearer Token received from the Security Token Service.
[ "Extracts", "the", "assertion", "from", "the", "Bearer", "Token", "received", "from", "the", "Security", "Token", "Service", "." ]
def get_bearer_saml_assertion(self, username, password, public_key=None, private_key=None, request_duration=60, token_duration=600, delegatable=False, renewable=False, ssl_context=None): ''' Extracts the assertion from the Bearer Token received from the Security Token Service. @type username: C{str} @param username: Username for the user for which bearer token needs to be requested. @type password: C{str} @param password: Password for the user for which bearer token needs to be requested. @type public_key: C{str} @param public_key: File containing the public key for the service user registered with SSO, in PEM format. @type private_key: C{str} @param private_key: File containing the private key for the service user registered with SSO, in PEM format. @type request_duration: C{long} @param request_duration: The duration for which the request is valid. If the STS receives this request after this duration, it is assumed to have expired. The duration is in seconds and the default is 60s. @type token_duration: C{long} @param token_duration: The duration for which the SAML token is issued for. The duration is specified in seconds and the default is 600s. @type delegatable: C{boolean} @param delegatable: Whether the generated token is delegatable or not The default value is False @type ssl_context: C{ssl.SSLContext} @param ssl_context: SSL context describing the various SSL options. It is only supported in Python 2.7.9 or higher. @rtype: C{str} @return: The SAML assertion in Unicode. ''' request = SecurityTokenRequest(username=username, password=password, public_key=public_key, private_key=private_key, request_duration=request_duration, token_duration=token_duration) soap_message = request.construct_bearer_token_request( delegatable=delegatable, renewable=renewable) bearer_token = self.perform_request(soap_message, public_key, private_key, ssl_context) return etree.tostring( _extract_element(etree.fromstring(bearer_token), 'Assertion', {'saml2': "urn:oasis:names:tc:SAML:2.0:assertion"}), pretty_print=False).decode(UTF_8)
[ "def", "get_bearer_saml_assertion", "(", "self", ",", "username", ",", "password", ",", "public_key", "=", "None", ",", "private_key", "=", "None", ",", "request_duration", "=", "60", ",", "token_duration", "=", "600", ",", "delegatable", "=", "False", ",", ...
https://github.com/vmware/pyvmomi/blob/5a738bef64efe8daea037ba9e8e0d566a0cc584c/pyVim/sso.py#L267-L328
natashamjaques/neural_chat
ddb977bb4602a67c460d02231e7bbf7b2cb49a97
ParlAI/projects/controllable_dialogue/controllable_seq2seq/modules.py
python
AttentionLayer.forward
(self, xes, hidden, attn_params)
return output, attn_weights
Compute attention over attn_params given input and hidden states. :param xes: input state. will be combined with applied attention. :param hidden: hidden state from model. will be used to select states to attend to in from the attn_params. :param attn_params: tuple of encoder output states and a mask showing which input indices are nonzero. :returns: output, attn_weights output is a new state of same size as input state `xes`. attn_weights are the weights given to each state in the encoder outputs.
Compute attention over attn_params given input and hidden states.
[ "Compute", "attention", "over", "attn_params", "given", "input", "and", "hidden", "states", "." ]
def forward(self, xes, hidden, attn_params): """Compute attention over attn_params given input and hidden states. :param xes: input state. will be combined with applied attention. :param hidden: hidden state from model. will be used to select states to attend to in from the attn_params. :param attn_params: tuple of encoder output states and a mask showing which input indices are nonzero. :returns: output, attn_weights output is a new state of same size as input state `xes`. attn_weights are the weights given to each state in the encoder outputs. """ if self.attention == 'none': # do nothing, no attention return xes, None if type(hidden) == tuple: # for lstms use the "hidden" state not the cell state hidden = hidden[0] last_hidden = hidden[-1] # select hidden state from last RNN layer enc_out, attn_mask = attn_params bsz, seqlen, hszXnumdir = enc_out.size() numlayersXnumdir = last_hidden.size(1) if self.attention == 'local': # local attention weights aren't based on encoder states h_merged = torch.cat((xes.squeeze(1), last_hidden), 1) attn_weights = F.softmax(self.attn(h_merged), dim=1) # adjust state sizes to the fixed window size if seqlen > self.max_length: offset = seqlen - self.max_length enc_out = enc_out.narrow(1, offset, self.max_length) seqlen = self.max_length if attn_weights.size(1) > seqlen: attn_weights = attn_weights.narrow(1, 0, seqlen) else: hid = last_hidden.unsqueeze(1) if self.attention == 'concat': # concat hidden state and encoder outputs hid = hid.expand(bsz, seqlen, numlayersXnumdir) h_merged = torch.cat((enc_out, hid), 2) # then do linear combination of them with activation active = F.tanh(self.attn(h_merged)) attn_w_premask = self.attn_v(active).squeeze(2) elif self.attention == 'dot': # dot product between hidden and encoder outputs if numlayersXnumdir != hszXnumdir: # enc_out has two directions, so double hid hid = torch.cat([hid, hid], 2) enc_t = enc_out.transpose(1, 2) attn_w_premask = torch.bmm(hid, enc_t).squeeze(1) elif self.attention == 'general': # before doing dot product, transform hidden state with linear # same as dot if linear is identity hid = self.attn(hid) enc_t = enc_out.transpose(1, 2) attn_w_premask = torch.bmm(hid, enc_t).squeeze(1) # calculate activation scores, apply mask if needed if attn_mask is not None: # remove activation from NULL symbols attn_w_premask.masked_fill_(~attn_mask, -NEAR_INF) attn_weights = F.softmax(attn_w_premask, dim=1) # apply the attention weights to the encoder states attn_applied = torch.bmm(attn_weights.unsqueeze(1), enc_out) # concatenate the input and encoder states merged = torch.cat((xes.squeeze(1), attn_applied.squeeze(1)), 1) # combine them with a linear layer and tanh activation output = torch.tanh(self.attn_combine(merged).unsqueeze(1)) return output, attn_weights
[ "def", "forward", "(", "self", ",", "xes", ",", "hidden", ",", "attn_params", ")", ":", "if", "self", ".", "attention", "==", "'none'", ":", "# do nothing, no attention", "return", "xes", ",", "None", "if", "type", "(", "hidden", ")", "==", "tuple", ":",...
https://github.com/natashamjaques/neural_chat/blob/ddb977bb4602a67c460d02231e7bbf7b2cb49a97/ParlAI/projects/controllable_dialogue/controllable_seq2seq/modules.py#L822-L898
Source-Python-Dev-Team/Source.Python
d0ffd8ccbd1e9923c9bc44936f20613c1c76b7fb
addons/source-python/packages/site-packages/docutils/utils/math/math2html.py
python
Container.locateprocess
(self, locate, process)
Search for all embedded containers and process them
Search for all embedded containers and process them
[ "Search", "for", "all", "embedded", "containers", "and", "process", "them" ]
def locateprocess(self, locate, process): "Search for all embedded containers and process them" for container in self.contents: container.locateprocess(locate, process) if locate(container): process(container)
[ "def", "locateprocess", "(", "self", ",", "locate", ",", "process", ")", ":", "for", "container", "in", "self", ".", "contents", ":", "container", ".", "locateprocess", "(", "locate", ",", "process", ")", "if", "locate", "(", "container", ")", ":", "proc...
https://github.com/Source-Python-Dev-Team/Source.Python/blob/d0ffd8ccbd1e9923c9bc44936f20613c1c76b7fb/addons/source-python/packages/site-packages/docutils/utils/math/math2html.py#L2148-L2153
Ha0Tang/SelectionGAN
80aa7ad9f79f643c28633c40c621f208f3fb0121
semantic_synthesis/data/pix2pix_dataset.py
python
Pix2pixDataset.modify_commandline_options
(parser, is_train)
return parser
[]
def modify_commandline_options(parser, is_train): parser.add_argument('--no_pairing_check', action='store_true', help='If specified, skip sanity check of correct label-image file pairing') return parser
[ "def", "modify_commandline_options", "(", "parser", ",", "is_train", ")", ":", "parser", ".", "add_argument", "(", "'--no_pairing_check'", ",", "action", "=", "'store_true'", ",", "help", "=", "'If specified, skip sanity check of correct label-image file pairing'", ")", "...
https://github.com/Ha0Tang/SelectionGAN/blob/80aa7ad9f79f643c28633c40c621f208f3fb0121/semantic_synthesis/data/pix2pix_dataset.py#L14-L17
tjweir/liftbook
e977a7face13ade1a4558e1909a6951d2f8928dd
elyxer.py
python
ImageFile.__init__
(self, path)
Create the file based on its path
Create the file based on its path
[ "Create", "the", "file", "based", "on", "its", "path" ]
def __init__(self, path): "Create the file based on its path" self.path = path
[ "def", "__init__", "(", "self", ",", "path", ")", ":", "self", ".", "path", "=", "path" ]
https://github.com/tjweir/liftbook/blob/e977a7face13ade1a4558e1909a6951d2f8928dd/elyxer.py#L6456-L6458
chainer/chainer
e9da1423255c58c37be9733f51b158aa9b39dc93
chainer/link.py
python
Link.children
(self)
Returns a generator of all child links. Returns: A generator object that generates all child links.
Returns a generator of all child links.
[ "Returns", "a", "generator", "of", "all", "child", "links", "." ]
def children(self) -> tp.Iterator['Link']: """Returns a generator of all child links. Returns: A generator object that generates all child links. """ if 0: yield
[ "def", "children", "(", "self", ")", "->", "tp", ".", "Iterator", "[", "'Link'", "]", ":", "if", "0", ":", "yield" ]
https://github.com/chainer/chainer/blob/e9da1423255c58c37be9733f51b158aa9b39dc93/chainer/link.py#L531-L539
dr-costas/mad-twinnet
446e49a423a4375e5ceedab5eb51bead1057d06b
helpers/data_feeder.py
python
data_feeder_testing
(window_size, fft_size, hop_size, seq_length, context_length, batch_size, debug, sources_list=None)
return testing_it
Provides an iterator over the testing examples. :param window_size: The window size to be used for the time-frequency transformation. :type window_size: int :param fft_size: The size of the FFT in samples. :type fft_size: int :param hop_size: The hop size in samples. :type hop_size: int :param seq_length: The sequence length in frames. :type seq_length: int :param context_length: The context length in frames. :type context_length: int :param batch_size: The batch size. :type batch_size: int :param debug: A flag to indicate debug :type debug: bool :param sources_list: The file list provided for using the MaD-TwinNet. :type sources_list: list[str|pathlib.Path] :return: An iterator that will provide the input and target values.\ The iterator yields (mix, mix magnitude, mix phase, voice true, bg true) values. :rtype: callable
Provides an iterator over the testing examples.
[ "Provides", "an", "iterator", "over", "the", "testing", "examples", "." ]
def data_feeder_testing(window_size, fft_size, hop_size, seq_length, context_length, batch_size, debug, sources_list=None): """Provides an iterator over the testing examples. :param window_size: The window size to be used for the time-frequency transformation. :type window_size: int :param fft_size: The size of the FFT in samples. :type fft_size: int :param hop_size: The hop size in samples. :type hop_size: int :param seq_length: The sequence length in frames. :type seq_length: int :param context_length: The context length in frames. :type context_length: int :param batch_size: The batch size. :type batch_size: int :param debug: A flag to indicate debug :type debug: bool :param sources_list: The file list provided for using the MaD-TwinNet. :type sources_list: list[str|pathlib.Path] :return: An iterator that will provide the input and target values.\ The iterator yields (mix, mix magnitude, mix phase, voice true, bg true) values. :rtype: callable """ if sources_list is None: usage_case = False sources_list = _get_files_lists('testing')[-1] else: usage_case = True hamming_window = signal.hamming(window_size, True) def testing_it(): for index in range(len(sources_list)): yield _get_data_testing( sources_parent_path=sources_list[index], window_values=hamming_window, fft_size=fft_size, hop=hop_size, seq_length=seq_length, context_length=context_length, batch_size=batch_size, usage_case=usage_case ) if debug: break return testing_it
[ "def", "data_feeder_testing", "(", "window_size", ",", "fft_size", ",", "hop_size", ",", "seq_length", ",", "context_length", ",", "batch_size", ",", "debug", ",", "sources_list", "=", "None", ")", ":", "if", "sources_list", "is", "None", ":", "usage_case", "=...
https://github.com/dr-costas/mad-twinnet/blob/446e49a423a4375e5ceedab5eb51bead1057d06b/helpers/data_feeder.py#L91-L135
materialsproject/pymatgen
8128f3062a334a2edd240e4062b5b9bdd1ae6f58
pymatgen/io/lammps/data.py
python
LammpsData.write_file
(self, filename, distance=6, velocity=8, charge=4)
Writes LammpsData to file. Args: filename (str): Filename. distance (int): No. of significant figures to output for box settings (bounds and tilt) and atomic coordinates. Default to 6. velocity (int): No. of significant figures to output for velocities. Default to 8. charge (int): No. of significant figures to output for charges. Default to 4.
Writes LammpsData to file.
[ "Writes", "LammpsData", "to", "file", "." ]
def write_file(self, filename, distance=6, velocity=8, charge=4): """ Writes LammpsData to file. Args: filename (str): Filename. distance (int): No. of significant figures to output for box settings (bounds and tilt) and atomic coordinates. Default to 6. velocity (int): No. of significant figures to output for velocities. Default to 8. charge (int): No. of significant figures to output for charges. Default to 4. """ with open(filename, "w") as f: f.write(self.get_string(distance=distance, velocity=velocity, charge=charge))
[ "def", "write_file", "(", "self", ",", "filename", ",", "distance", "=", "6", ",", "velocity", "=", "8", ",", "charge", "=", "4", ")", ":", "with", "open", "(", "filename", ",", "\"w\"", ")", "as", "f", ":", "f", ".", "write", "(", "self", ".", ...
https://github.com/materialsproject/pymatgen/blob/8128f3062a334a2edd240e4062b5b9bdd1ae6f58/pymatgen/io/lammps/data.py#L492-L508
shubhomoydas/ad_examples
0a7b86c4f2f7306ff543a15b387fe938f9c06130
ad_examples/aad/forest_description.py
python
InstancesDescriber.__init__
(self, x, y, model, opts, sample_negative=False)
:param x: np.ndarray The instance matrix with ALL instances :param y: np.array :param model: Aad :param opts: AadOpts :param sample_negative: bool
[]
def __init__(self, x, y, model, opts, sample_negative=False): """ :param x: np.ndarray The instance matrix with ALL instances :param y: np.array :param model: Aad :param opts: AadOpts :param sample_negative: bool """ self.x = x self.y = y self.model = model self.opts = opts self.sample_negative = sample_negative self.meta = None
[ "def", "__init__", "(", "self", ",", "x", ",", "y", ",", "model", ",", "opts", ",", "sample_negative", "=", "False", ")", ":", "self", ".", "x", "=", "x", "self", ".", "y", "=", "y", "self", ".", "model", "=", "model", "self", ".", "opts", "=",...
https://github.com/shubhomoydas/ad_examples/blob/0a7b86c4f2f7306ff543a15b387fe938f9c06130/ad_examples/aad/forest_description.py#L218-L234
doraemonext/wechat-python-sdk
bf6f6f3d4a5440feb73a51937059d7feddc335a0
wechat_sdk/ext.py
python
WechatExt.get_message_image
(self, msgid, mode='large')
return r.raw.data
根据消息 ID 获取图片消息内容 :param msgid: 消息 ID :param mode: 图片尺寸 ('large'或'small') :return: 二进制 JPG 图片字符串, 可直接作为 File Object 中 write 的参数 :raises NeedLoginError: 操作未执行成功, 需要再次尝试登录, 异常内容为服务器返回的错误数据 :raises ValueError: 参数出错, 错误原因直接打印异常即可, 错误内容: ``image message not exist``: msg参数无效, ``mode error``: mode参数无效
根据消息 ID 获取图片消息内容 :param msgid: 消息 ID :param mode: 图片尺寸 ('large'或'small') :return: 二进制 JPG 图片字符串, 可直接作为 File Object 中 write 的参数 :raises NeedLoginError: 操作未执行成功, 需要再次尝试登录, 异常内容为服务器返回的错误数据 :raises ValueError: 参数出错, 错误原因直接打印异常即可, 错误内容: ``image message not exist``: msg参数无效, ``mode error``: mode参数无效
[ "根据消息", "ID", "获取图片消息内容", ":", "param", "msgid", ":", "消息", "ID", ":", "param", "mode", ":", "图片尺寸", "(", "large", "或", "small", ")", ":", "return", ":", "二进制", "JPG", "图片字符串", "可直接作为", "File", "Object", "中", "write", "的参数", ":", "raises", "NeedLogin...
def get_message_image(self, msgid, mode='large'): """ 根据消息 ID 获取图片消息内容 :param msgid: 消息 ID :param mode: 图片尺寸 ('large'或'small') :return: 二进制 JPG 图片字符串, 可直接作为 File Object 中 write 的参数 :raises NeedLoginError: 操作未执行成功, 需要再次尝试登录, 异常内容为服务器返回的错误数据 :raises ValueError: 参数出错, 错误原因直接打印异常即可, 错误内容: ``image message not exist``: msg参数无效, ``mode error``: mode参数无效 """ if mode != 'large' and mode != 'small': raise ValueError('mode error') url = 'https://mp.weixin.qq.com/cgi-bin/getimgdata?token={token}&msgid={msgid}&mode={mode}&source=&fileId=0'.format( msgid=msgid, token=self.__token, mode=mode, ) headers = { 'x-requested-with': 'XMLHttpRequest', 'referer': 'https://mp.weixin.qq.com/cgi-bin/message?t=message/list&token={token}&count=20&day=7'.format( token=self.__token, ), 'cookie': self.__cookies, } r = requests.get(url, headers=headers, stream=True) # 检测会话是否超时 if r.headers.get('content-type', None) == 'text/html; charset=UTF-8': raise NeedLoginError(r.text) # 检测图片是否存在 if not r.raw.data: raise ValueError('image message not exist') return r.raw.data
[ "def", "get_message_image", "(", "self", ",", "msgid", ",", "mode", "=", "'large'", ")", ":", "if", "mode", "!=", "'large'", "and", "mode", "!=", "'small'", ":", "raise", "ValueError", "(", "'mode error'", ")", "url", "=", "'https://mp.weixin.qq.com/cgi-bin/ge...
https://github.com/doraemonext/wechat-python-sdk/blob/bf6f6f3d4a5440feb73a51937059d7feddc335a0/wechat_sdk/ext.py#L1186-L1219
bbfamily/abu
2de85ae57923a720dac99a545b4f856f6b87304b
abupy/PickStockBu/ABuPickStockPriceMinMax.py
python
AbuPickStockPriceMinMax.fit_pick
(self, kl_pd, target_symbol)
return False
开始根据自定义价格边际参数进行选股
开始根据自定义价格边际参数进行选股
[ "开始根据自定义价格边际参数进行选股" ]
def fit_pick(self, kl_pd, target_symbol): """开始根据自定义价格边际参数进行选股""" if kl_pd.close.max() < self.threshold_price_max and kl_pd.close.min() > self.threshold_price_min: # kl_pd.close的最大价格 < 最大价格阀值 且 kl_pd.close的最小价格 > 最小价格阀值 return True return False
[ "def", "fit_pick", "(", "self", ",", "kl_pd", ",", "target_symbol", ")", ":", "if", "kl_pd", ".", "close", ".", "max", "(", ")", "<", "self", ".", "threshold_price_max", "and", "kl_pd", ".", "close", ".", "min", "(", ")", ">", "self", ".", "threshold...
https://github.com/bbfamily/abu/blob/2de85ae57923a720dac99a545b4f856f6b87304b/abupy/PickStockBu/ABuPickStockPriceMinMax.py#L35-L40
barseghyanartur/django-fobi
a998feae007d7fe3637429a80e42952ec7cda79f
src/fobi/decorators.py
python
permissions_required
(perms, satisfy=DEFAULT_SATISFY, login_url=None, raise_exception=False)
return user_passes_test(check_perms, login_url=login_url)
Check for the permissions given based on the strategy chosen. :param iterable perms: :param string satisfy: Allowed values are "all" and "any". :param string login_url: :param bool raise_exception: If set to True, the ``PermissionDenied`` exception is raised on failures. :return bool: :example: >>> @login_required >>> @permissions_required(satisfy='any', perms=[ >>> 'fobi.add_formentry', >>> 'fobi.change_formentry', >>> 'fobi.delete_formentry', >>> 'fobi.add_formelemententry', >>> 'fobi.change_formelemententry', >>> 'fobi.delete_formelemententry', >>> ]) >>> def edit_dashboard(request): >>> # your code
Check for the permissions given based on the strategy chosen.
[ "Check", "for", "the", "permissions", "given", "based", "on", "the", "strategy", "chosen", "." ]
def permissions_required(perms, satisfy=DEFAULT_SATISFY, login_url=None, raise_exception=False): """Check for the permissions given based on the strategy chosen. :param iterable perms: :param string satisfy: Allowed values are "all" and "any". :param string login_url: :param bool raise_exception: If set to True, the ``PermissionDenied`` exception is raised on failures. :return bool: :example: >>> @login_required >>> @permissions_required(satisfy='any', perms=[ >>> 'fobi.add_formentry', >>> 'fobi.change_formentry', >>> 'fobi.delete_formentry', >>> 'fobi.add_formelemententry', >>> 'fobi.change_formelemententry', >>> 'fobi.delete_formelemententry', >>> ]) >>> def edit_dashboard(request): >>> # your code """ assert satisfy in (SATISFY_ANY, SATISFY_ALL) if SATISFY_ALL == satisfy: # ``SATISFY_ALL`` case def check_perms(user): # First check if the user has the permission (even anon users) if user.has_perms(perms): return True # In case the 403 handler should be called raise the exception if raise_exception: raise PermissionDenied # As the last resort, show the login form return False else: # ``SATISFY_ANY`` case def check_perms(user): # First check if the user has the permission (even anon users) for perm in perms: if user.has_perm(perm): return True # In case the 403 handler should be called raise the exception if raise_exception: raise PermissionDenied # As the last resort, show the login form return False return user_passes_test(check_perms, login_url=login_url)
[ "def", "permissions_required", "(", "perms", ",", "satisfy", "=", "DEFAULT_SATISFY", ",", "login_url", "=", "None", ",", "raise_exception", "=", "False", ")", ":", "assert", "satisfy", "in", "(", "SATISFY_ANY", ",", "SATISFY_ALL", ")", "if", "SATISFY_ALL", "==...
https://github.com/barseghyanartur/django-fobi/blob/a998feae007d7fe3637429a80e42952ec7cda79f/src/fobi/decorators.py#L23-L74
P1sec/pycrate
d12bbccf1df8c9c7891a26967a9d2635610ec5b8
pycrate_mobile/ISUP.py
python
ISUPNum.get_num
(self)
return the BCD-encoded number, properly decoded according to OE
return the BCD-encoded number, properly decoded according to OE
[ "return", "the", "BCD", "-", "encoded", "number", "properly", "decoded", "according", "to", "OE" ]
def get_num(self): """return the BCD-encoded number, properly decoded according to OE """ if self['OE'].get_val(): return self['Num'].decode()[:-1] else: return self['Num'].decode()
[ "def", "get_num", "(", "self", ")", ":", "if", "self", "[", "'OE'", "]", ".", "get_val", "(", ")", ":", "return", "self", "[", "'Num'", "]", ".", "decode", "(", ")", "[", ":", "-", "1", "]", "else", ":", "return", "self", "[", "'Num'", "]", "...
https://github.com/P1sec/pycrate/blob/d12bbccf1df8c9c7891a26967a9d2635610ec5b8/pycrate_mobile/ISUP.py#L57-L63
naftaliharris/tauthon
5587ceec329b75f7caf6d65a036db61ac1bae214
Lib/lib-tk/turtle.py
python
ScrolledCanvas.adjustScrolls
(self)
Adjust scrollbars according to window- and canvas-size.
Adjust scrollbars according to window- and canvas-size.
[ "Adjust", "scrollbars", "according", "to", "window", "-", "and", "canvas", "-", "size", "." ]
def adjustScrolls(self): """ Adjust scrollbars according to window- and canvas-size. """ cwidth = self._canvas.winfo_width() cheight = self._canvas.winfo_height() self._canvas.xview_moveto(0.5*(self.canvwidth-cwidth)/self.canvwidth) self._canvas.yview_moveto(0.5*(self.canvheight-cheight)/self.canvheight) if cwidth < self.canvwidth or cheight < self.canvheight: self.hscroll.grid(padx=1, in_ = self, pady=1, row=1, column=0, rowspan=1, columnspan=1, sticky='news') self.vscroll.grid(padx=1, in_ = self, pady=1, row=0, column=1, rowspan=1, columnspan=1, sticky='news') else: self.hscroll.grid_forget() self.vscroll.grid_forget()
[ "def", "adjustScrolls", "(", "self", ")", ":", "cwidth", "=", "self", ".", "_canvas", ".", "winfo_width", "(", ")", "cheight", "=", "self", ".", "_canvas", ".", "winfo_height", "(", ")", "self", ".", "_canvas", ".", "xview_moveto", "(", "0.5", "*", "("...
https://github.com/naftaliharris/tauthon/blob/5587ceec329b75f7caf6d65a036db61ac1bae214/Lib/lib-tk/turtle.py#L402-L416
scrtlabs/catalyst
2e8029780f2381da7a0729f7b52505e5db5f535b
catalyst/pipeline/term.py
python
Term.__init__
(self, *args, **kwargs)
Noop constructor to play nicely with our caching __new__. Subclasses should implement _init instead of this method. When a class' __new__ returns an instance of that class, Python will automatically call __init__ on the object, even if a new object wasn't actually constructed. Because we memoize instances, we often return an object that was already initialized from __new__, in which case we don't want to call __init__ again. Subclasses that need to initialize new instances should override _init, which is guaranteed to be called only once.
Noop constructor to play nicely with our caching __new__. Subclasses should implement _init instead of this method.
[ "Noop", "constructor", "to", "play", "nicely", "with", "our", "caching", "__new__", ".", "Subclasses", "should", "implement", "_init", "instead", "of", "this", "method", "." ]
def __init__(self, *args, **kwargs): """ Noop constructor to play nicely with our caching __new__. Subclasses should implement _init instead of this method. When a class' __new__ returns an instance of that class, Python will automatically call __init__ on the object, even if a new object wasn't actually constructed. Because we memoize instances, we often return an object that was already initialized from __new__, in which case we don't want to call __init__ again. Subclasses that need to initialize new instances should override _init, which is guaranteed to be called only once. """ pass
[ "def", "__init__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "pass" ]
https://github.com/scrtlabs/catalyst/blob/2e8029780f2381da7a0729f7b52505e5db5f535b/catalyst/pipeline/term.py#L189-L203
sfepy/sfepy
02ec7bb2ab39ee1dfe1eb4cd509f0ffb7dcc8b25
sfepy/discrete/fem/fields_positive.py
python
H1BernsteinVolumeField.create_basis_context
(self)
return ctx
Create the context required for evaluating the field basis.
Create the context required for evaluating the field basis.
[ "Create", "the", "context", "required", "for", "evaluating", "the", "field", "basis", "." ]
def create_basis_context(self): """ Create the context required for evaluating the field basis. """ # Hack for tests to pass - the reference coordinates are determined # from vertices only - we can use the Lagrange basis context for the # moment. The true context for Field.evaluate_at() is not implemented. gps = self.gel.poly_space mesh = self.create_mesh(extra_nodes=False) ctx = geo_ctx = gps.create_context(mesh.cmesh, 0, 1e-15, 100, 1e-8) ctx.geo_ctx = geo_ctx return ctx
[ "def", "create_basis_context", "(", "self", ")", ":", "# Hack for tests to pass - the reference coordinates are determined", "# from vertices only - we can use the Lagrange basis context for the", "# moment. The true context for Field.evaluate_at() is not implemented.", "gps", "=", "self", "...
https://github.com/sfepy/sfepy/blob/02ec7bb2ab39ee1dfe1eb4cd509f0ffb7dcc8b25/sfepy/discrete/fem/fields_positive.py#L8-L21
holzschu/Carnets
44effb10ddfc6aa5c8b0687582a724ba82c6b547
Library/lib/python3.7/site-packages/astropy-4.0-py3.7-macosx-10.9-x86_64.egg/astropy/_erfa/core.py
python
ppp
(a, b)
return apb
Wrapper for ERFA function ``eraPpp``. Parameters ---------- a : double array b : double array Returns ------- apb : double array Notes ----- The ERFA documentation is below. - - - - - - - e r a P p p - - - - - - - P-vector addition. Given: a double[3] first p-vector b double[3] second p-vector Returned: apb double[3] a + b Note: It is permissible to re-use the same array for any of the arguments. Copyright (C) 2013-2019, NumFOCUS Foundation. Derived, with permission, from the SOFA library. See notes at end of file.
Wrapper for ERFA function ``eraPpp``.
[ "Wrapper", "for", "ERFA", "function", "eraPpp", "." ]
def ppp(a, b): """ Wrapper for ERFA function ``eraPpp``. Parameters ---------- a : double array b : double array Returns ------- apb : double array Notes ----- The ERFA documentation is below. - - - - - - - e r a P p p - - - - - - - P-vector addition. Given: a double[3] first p-vector b double[3] second p-vector Returned: apb double[3] a + b Note: It is permissible to re-use the same array for any of the arguments. Copyright (C) 2013-2019, NumFOCUS Foundation. Derived, with permission, from the SOFA library. See notes at end of file. """ apb = ufunc.ppp(a, b) return apb
[ "def", "ppp", "(", "a", ",", "b", ")", ":", "apb", "=", "ufunc", ".", "ppp", "(", "a", ",", "b", ")", "return", "apb" ]
https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/site-packages/astropy-4.0-py3.7-macosx-10.9-x86_64.egg/astropy/_erfa/core.py#L19621-L19660
tendenci/tendenci
0f2c348cc0e7d41bc56f50b00ce05544b083bf1d
tendenci/apps/events/forms.py
python
RegistrationPreForm.clean_pricing
(self)
return pricing
[]
def clean_pricing(self): if not self.table_only: is_table = self.cleaned_data['is_table'] == '1' else: is_table = True pricing = self.cleaned_data['pricing'] if is_table and not pricing: raise forms.ValidationError(_('Please choose a price for table registration.')) return pricing
[ "def", "clean_pricing", "(", "self", ")", ":", "if", "not", "self", ".", "table_only", ":", "is_table", "=", "self", ".", "cleaned_data", "[", "'is_table'", "]", "==", "'1'", "else", ":", "is_table", "=", "True", "pricing", "=", "self", ".", "cleaned_dat...
https://github.com/tendenci/tendenci/blob/0f2c348cc0e7d41bc56f50b00ce05544b083bf1d/tendenci/apps/events/forms.py#L1640-L1649
mozillazg/pypy
2ff5cd960c075c991389f842c6d59e71cf0cb7d0
lib_pypy/_cffi_ssl/cryptography/x509/name.py
python
Name.rfc4514_string
(self)
return ','.join(attr.rfc4514_string() for attr in self._attributes)
Format as RFC4514 Distinguished Name string. For example 'CN=foobar.com,O=Foo Corp,C=US' An X.509 name is a two-level structure: a list of sets of attributes. Each list element is separated by ',' and within each list element, set elements are separated by '+'. The latter is almost never used in real world certificates.
Format as RFC4514 Distinguished Name string. For example 'CN=foobar.com,O=Foo Corp,C=US'
[ "Format", "as", "RFC4514", "Distinguished", "Name", "string", ".", "For", "example", "CN", "=", "foobar", ".", "com", "O", "=", "Foo", "Corp", "C", "=", "US" ]
def rfc4514_string(self): """ Format as RFC4514 Distinguished Name string. For example 'CN=foobar.com,O=Foo Corp,C=US' An X.509 name is a two-level structure: a list of sets of attributes. Each list element is separated by ',' and within each list element, set elements are separated by '+'. The latter is almost never used in real world certificates. """ return ','.join(attr.rfc4514_string() for attr in self._attributes)
[ "def", "rfc4514_string", "(", "self", ")", ":", "return", "','", ".", "join", "(", "attr", ".", "rfc4514_string", "(", ")", "for", "attr", "in", "self", ".", "_attributes", ")" ]
https://github.com/mozillazg/pypy/blob/2ff5cd960c075c991389f842c6d59e71cf0cb7d0/lib_pypy/_cffi_ssl/cryptography/x509/name.py#L211-L221
awslabs/aws-config-rules
8dfeacf9d9e5e5f0fbb1b8545ff702dea700ea7a
python/EC2_SECURITY_GROUP_BADINGRESS/EC2_SECURITY_GROUP_BADINGRESS.py
python
get_client
(service, event, region=None)
return boto3.client(service, aws_access_key_id=credentials['AccessKeyId'], aws_secret_access_key=credentials['SecretAccessKey'], aws_session_token=credentials['SessionToken'], region_name=region )
Return the service boto client. It should be used instead of directly calling the client. Keyword arguments: service -- the service name used for calling the boto.client() event -- the event variable given in the lambda handler region -- the region where the client is called (default: None)
Return the service boto client. It should be used instead of directly calling the client.
[ "Return", "the", "service", "boto", "client", ".", "It", "should", "be", "used", "instead", "of", "directly", "calling", "the", "client", "." ]
def get_client(service, event, region=None): """Return the service boto client. It should be used instead of directly calling the client. Keyword arguments: service -- the service name used for calling the boto.client() event -- the event variable given in the lambda handler region -- the region where the client is called (default: None) """ if not ASSUME_ROLE_MODE: return boto3.client(service, region) credentials = get_assume_role_credentials(get_execution_role_arn(event), region) return boto3.client(service, aws_access_key_id=credentials['AccessKeyId'], aws_secret_access_key=credentials['SecretAccessKey'], aws_session_token=credentials['SessionToken'], region_name=region )
[ "def", "get_client", "(", "service", ",", "event", ",", "region", "=", "None", ")", ":", "if", "not", "ASSUME_ROLE_MODE", ":", "return", "boto3", ".", "client", "(", "service", ",", "region", ")", "credentials", "=", "get_assume_role_credentials", "(", "get_...
https://github.com/awslabs/aws-config-rules/blob/8dfeacf9d9e5e5f0fbb1b8545ff702dea700ea7a/python/EC2_SECURITY_GROUP_BADINGRESS/EC2_SECURITY_GROUP_BADINGRESS.py#L120-L135
nathanborror/django-basic-apps
3a90090857549ea4198a72c44f45f6edb238e2a8
basic/tools/templatetags/listutils.py
python
pop_from_GET
(obj, attr)
return '&%s' % obj.urlencode()
Returns GET parameters sans specified attribute.
Returns GET parameters sans specified attribute.
[ "Returns", "GET", "parameters", "sans", "specified", "attribute", "." ]
def pop_from_GET(obj, attr): """ Returns GET parameters sans specified attribute. """ if obj.get(attr, None): obj_copy = obj.copy() del obj_copy[attr] return '&%s' % obj_copy.urlencode() if not obj: return '' return '&%s' % obj.urlencode()
[ "def", "pop_from_GET", "(", "obj", ",", "attr", ")", ":", "if", "obj", ".", "get", "(", "attr", ",", "None", ")", ":", "obj_copy", "=", "obj", ".", "copy", "(", ")", "del", "obj_copy", "[", "attr", "]", "return", "'&%s'", "%", "obj_copy", ".", "u...
https://github.com/nathanborror/django-basic-apps/blob/3a90090857549ea4198a72c44f45f6edb238e2a8/basic/tools/templatetags/listutils.py#L21-L31
lebedov/scikit-cuda
5d3c74f926fe7ce67ecfc85e9623aab7bc0b344f
skcuda/magma.py
python
magma_cheevd_m
(ngpu, jobz, uplo, n, A, lda, w, work, lwork, rwork, lrwork, iwork, liwork)
Compute eigenvalues of complex hermitian matrix. Multi-GPU, data on host
Compute eigenvalues of complex hermitian matrix. Multi-GPU, data on host
[ "Compute", "eigenvalues", "of", "complex", "hermitian", "matrix", ".", "Multi", "-", "GPU", "data", "on", "host" ]
def magma_cheevd_m(ngpu, jobz, uplo, n, A, lda, w, work, lwork, rwork, lrwork, iwork, liwork): """ Compute eigenvalues of complex hermitian matrix. Multi-GPU, data on host """ jobz = _vec_conversion[jobz] uplo = _uplo_conversion[uplo] info = c_int_type() status = _libmagma.magma_cheevd_m(ngpu, jobz, uplo, n, int(A), lda, int(w), int(work), lwork, int(rwork), lrwork, int(iwork), liwork, ctypes.byref(info)) magmaCheckStatus(status)
[ "def", "magma_cheevd_m", "(", "ngpu", ",", "jobz", ",", "uplo", ",", "n", ",", "A", ",", "lda", ",", "w", ",", "work", ",", "lwork", ",", "rwork", ",", "lrwork", ",", "iwork", ",", "liwork", ")", ":", "jobz", "=", "_vec_conversion", "[", "jobz", ...
https://github.com/lebedov/scikit-cuda/blob/5d3c74f926fe7ce67ecfc85e9623aab7bc0b344f/skcuda/magma.py#L3716-L3728
interpretml/DiCE
e6a1dc3893799a364da993d4a368b7ccfabe4447
dice_ml/explainer_interfaces/dice_tensorflow2.py
python
DiceTensorFlow2.compute_diversity_loss
(self)
Computes the third part (diversity) of the loss function.
Computes the third part (diversity) of the loss function.
[ "Computes", "the", "third", "part", "(", "diversity", ")", "of", "the", "loss", "function", "." ]
def compute_diversity_loss(self): """Computes the third part (diversity) of the loss function.""" if self.total_CFs == 1: return tf.constant(0.0) if "dpp" in self.diversity_loss_type: submethod = self.diversity_loss_type.split(':')[1] return tf.reduce_sum(self.dpp_style(submethod)) elif self.diversity_loss_type == "avg_dist": diversity_loss = 0.0 count = 0.0 # computing pairwise distance and transforming it to normalized similarity for i in range(self.total_CFs): for j in range(i+1, self.total_CFs): count += 1.0 diversity_loss += 1.0/(1.0 + self.compute_dist(self.cfs[i], self.cfs[j])) return 1.0 - (diversity_loss/count)
[ "def", "compute_diversity_loss", "(", "self", ")", ":", "if", "self", ".", "total_CFs", "==", "1", ":", "return", "tf", ".", "constant", "(", "0.0", ")", "if", "\"dpp\"", "in", "self", ".", "diversity_loss_type", ":", "submethod", "=", "self", ".", "dive...
https://github.com/interpretml/DiCE/blob/e6a1dc3893799a364da993d4a368b7ccfabe4447/dice_ml/explainer_interfaces/dice_tensorflow2.py#L290-L307
Source-Python-Dev-Team/Source.Python
d0ffd8ccbd1e9923c9bc44936f20613c1c76b7fb
addons/source-python/packages/site-packages/sqlalchemy/orm/base.py
python
InspectionAttrInfo.info
(self)
return {}
Info dictionary associated with the object, allowing user-defined data to be associated with this :class:`.InspectionAttr`. The dictionary is generated when first accessed. Alternatively, it can be specified as a constructor argument to the :func:`.column_property`, :func:`.relationship`, or :func:`.composite` functions. .. versionadded:: 0.8 Added support for .info to all :class:`.MapperProperty` subclasses. .. versionchanged:: 1.0.0 :attr:`.MapperProperty.info` is also available on extension types via the :attr:`.InspectionAttrInfo.info` attribute, so that it can apply to a wider variety of ORM and extension constructs. .. seealso:: :attr:`.QueryableAttribute.info` :attr:`.SchemaItem.info`
Info dictionary associated with the object, allowing user-defined data to be associated with this :class:`.InspectionAttr`.
[ "Info", "dictionary", "associated", "with", "the", "object", "allowing", "user", "-", "defined", "data", "to", "be", "associated", "with", "this", ":", "class", ":", ".", "InspectionAttr", "." ]
def info(self): """Info dictionary associated with the object, allowing user-defined data to be associated with this :class:`.InspectionAttr`. The dictionary is generated when first accessed. Alternatively, it can be specified as a constructor argument to the :func:`.column_property`, :func:`.relationship`, or :func:`.composite` functions. .. versionadded:: 0.8 Added support for .info to all :class:`.MapperProperty` subclasses. .. versionchanged:: 1.0.0 :attr:`.MapperProperty.info` is also available on extension types via the :attr:`.InspectionAttrInfo.info` attribute, so that it can apply to a wider variety of ORM and extension constructs. .. seealso:: :attr:`.QueryableAttribute.info` :attr:`.SchemaItem.info` """ return {}
[ "def", "info", "(", "self", ")", ":", "return", "{", "}" ]
https://github.com/Source-Python-Dev-Team/Source.Python/blob/d0ffd8ccbd1e9923c9bc44936f20613c1c76b7fb/addons/source-python/packages/site-packages/sqlalchemy/orm/base.py#L508-L532
abr/abr_control
a248ec56166f01791857a766ac58ee0920c0861c
abr_control/interfaces/coppeliasim_files/sim.py
python
simxGetDialogInput
(clientID, dialogHandle, operationMode)
return ret, a
Please have a look at the function description/documentation in the CoppeliaSim user manual
Please have a look at the function description/documentation in the CoppeliaSim user manual
[ "Please", "have", "a", "look", "at", "the", "function", "description", "/", "documentation", "in", "the", "CoppeliaSim", "user", "manual" ]
def simxGetDialogInput(clientID, dialogHandle, operationMode): """ Please have a look at the function description/documentation in the CoppeliaSim user manual """ inputText = ct.POINTER(ct.c_char)() ret = c_GetDialogInput(clientID, dialogHandle, ct.byref(inputText), operationMode) a = bytearray() if ret == 0: i = 0 while inputText[i] != b"\0": if sys.version_info[0] == 3: a.append(int.from_bytes(inputText[i], "big")) else: a.append(inputText[i]) i = i + 1 if sys.version_info[0] == 3: a = str(a, "utf-8") else: a = str(a) return ret, a
[ "def", "simxGetDialogInput", "(", "clientID", ",", "dialogHandle", ",", "operationMode", ")", ":", "inputText", "=", "ct", ".", "POINTER", "(", "ct", ".", "c_char", ")", "(", ")", "ret", "=", "c_GetDialogInput", "(", "clientID", ",", "dialogHandle", ",", "...
https://github.com/abr/abr_control/blob/a248ec56166f01791857a766ac58ee0920c0861c/abr_control/interfaces/coppeliasim_files/sim.py#L1504-L1525
home-assistant/core
265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1
homeassistant/components/channels/media_player.py
python
ChannelsPlayer.media_previous_track
(self)
Seek back.
Seek back.
[ "Seek", "back", "." ]
def media_previous_track(self): """Seek back.""" response = self.client.skip_backward() self.update_state(response)
[ "def", "media_previous_track", "(", "self", ")", ":", "response", "=", "self", ".", "client", ".", "skip_backward", "(", ")", "self", ".", "update_state", "(", "response", ")" ]
https://github.com/home-assistant/core/blob/265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1/homeassistant/components/channels/media_player.py#L250-L253
conjure-up/conjure-up
d2bf8ab8e71ff01321d0e691a8d3e3833a047678
conjureup/ui/views/base.py
python
HelpView.build_widget
(self)
return lines
[]
def build_widget(self): key_col_width = max(len(k) for k, _ in self.help_defs) + 2 lines = [] for key_def, help_text in self.help_defs: lines.append(Columns([(key_col_width, Text(key_def)), Text(help_text)])) lines.append(Text("")) return lines
[ "def", "build_widget", "(", "self", ")", ":", "key_col_width", "=", "max", "(", "len", "(", "k", ")", "for", "k", ",", "_", "in", "self", ".", "help_defs", ")", "+", "2", "lines", "=", "[", "]", "for", "key_def", ",", "help_text", "in", "self", "...
https://github.com/conjure-up/conjure-up/blob/d2bf8ab8e71ff01321d0e691a8d3e3833a047678/conjureup/ui/views/base.py#L444-L451
JimmXinu/FanFicFare
bc149a2deb2636320fe50a3e374af6eef8f61889
included_dependencies/soupsieve/css_match.py
python
Document.get_children
(self, el, start=None, reverse=False, tags=True, no_iframe=False)
Get children.
Get children.
[ "Get", "children", "." ]
def get_children(self, el, start=None, reverse=False, tags=True, no_iframe=False): """Get children.""" if not no_iframe or not self.is_iframe(el): last = len(el.contents) - 1 if start is None: index = last if reverse else 0 else: index = start end = -1 if reverse else last + 1 incr = -1 if reverse else 1 if 0 <= index <= last: while index != end: node = el.contents[index] index += incr if not tags or self.is_tag(node): yield node
[ "def", "get_children", "(", "self", ",", "el", ",", "start", "=", "None", ",", "reverse", "=", "False", ",", "tags", "=", "True", ",", "no_iframe", "=", "False", ")", ":", "if", "not", "no_iframe", "or", "not", "self", ".", "is_iframe", "(", "el", ...
https://github.com/JimmXinu/FanFicFare/blob/bc149a2deb2636320fe50a3e374af6eef8f61889/included_dependencies/soupsieve/css_match.py#L186-L203
home-assistant/core
265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1
homeassistant/components/nissan_leaf/switch.py
python
LeafClimateSwitch.async_turn_off
(self, **kwargs: Any)
Turn off climate control.
Turn off climate control.
[ "Turn", "off", "climate", "control", "." ]
async def async_turn_off(self, **kwargs: Any) -> None: """Turn off climate control.""" if await self.car.async_set_climate(False): self.car.data[DATA_CLIMATE] = False
[ "async", "def", "async_turn_off", "(", "self", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "None", ":", "if", "await", "self", ".", "car", ".", "async_set_climate", "(", "False", ")", ":", "self", ".", "car", ".", "data", "[", "DATA_CLIMATE", "]"...
https://github.com/home-assistant/core/blob/265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1/homeassistant/components/nissan_leaf/switch.py#L75-L78
MaurizioFD/RecSys2019_DeepLearning_Evaluation
0fb6b7f5c396f8525316ed66cf9c9fdb03a5fa9b
CNN_on_embeddings/IJCAI/CFM_our_interface/LoadData.py
python
LoadData.bind_user
(self)
return len(self.binded_users)
Map the item fields in all files, kept in self.item_fields dictionary :return:
Map the item fields in all files, kept in self.item_fields dictionary :return:
[ "Map", "the", "item", "fields", "in", "all", "files", "kept", "in", "self", ".", "item_fields", "dictionary", ":", "return", ":" ]
def bind_user(self): ''' Map the item fields in all files, kept in self.item_fields dictionary :return: ''' self.binded_users = {} self.bind_u(self.trainfile) self.bind_u(self.testfile) return len(self.binded_users)
[ "def", "bind_user", "(", "self", ")", ":", "self", ".", "binded_users", "=", "{", "}", "self", ".", "bind_u", "(", "self", ".", "trainfile", ")", "self", ".", "bind_u", "(", "self", ".", "testfile", ")", "return", "len", "(", "self", ".", "binded_use...
https://github.com/MaurizioFD/RecSys2019_DeepLearning_Evaluation/blob/0fb6b7f5c396f8525316ed66cf9c9fdb03a5fa9b/CNN_on_embeddings/IJCAI/CFM_our_interface/LoadData.py#L92-L100
implus/PytorchInsight
2864528f8b83f52c3df76f7c3804aa468b91e5cf
detection/mmdet/models/utils/conv_module.py
python
ConvModule.forward
(self, x, activate=True, norm=True)
return x
[]
def forward(self, x, activate=True, norm=True): if self.activate_last: x = self.conv(x) if norm and self.with_norm: x = self.norm(x) if activate and self.with_activatation: x = self.activate(x) else: if norm and self.with_norm: x = self.norm(x) if activate and self.with_activatation: x = self.activate(x) x = self.conv(x) return x
[ "def", "forward", "(", "self", ",", "x", ",", "activate", "=", "True", ",", "norm", "=", "True", ")", ":", "if", "self", ".", "activate_last", ":", "x", "=", "self", ".", "conv", "(", "x", ")", "if", "norm", "and", "self", ".", "with_norm", ":", ...
https://github.com/implus/PytorchInsight/blob/2864528f8b83f52c3df76f7c3804aa468b91e5cf/detection/mmdet/models/utils/conv_module.py#L77-L90
trakt/Plex-Trakt-Scrobbler
aeb0bfbe62fad4b06c164f1b95581da7f35dce0b
Trakttv.bundle/Contents/Libraries/MacOSX/i386/ucs2/cryptography/x509/base.py
python
CertificateBuilder.not_valid_before
(self, time)
return CertificateBuilder( self._issuer_name, self._subject_name, self._public_key, self._serial_number, time, self._not_valid_after, self._extensions )
Sets the certificate activation time.
Sets the certificate activation time.
[ "Sets", "the", "certificate", "activation", "time", "." ]
def not_valid_before(self, time): """ Sets the certificate activation time. """ if not isinstance(time, datetime.datetime): raise TypeError('Expecting datetime object.') if self._not_valid_before is not None: raise ValueError('The not valid before may only be set once.') time = _convert_to_naive_utc_time(time) if time <= _UNIX_EPOCH: raise ValueError('The not valid before date must be after the unix' ' epoch (1970 January 1).') if self._not_valid_after is not None and time > self._not_valid_after: raise ValueError( 'The not valid before date must be before the not valid after ' 'date.' ) return CertificateBuilder( self._issuer_name, self._subject_name, self._public_key, self._serial_number, time, self._not_valid_after, self._extensions )
[ "def", "not_valid_before", "(", "self", ",", "time", ")", ":", "if", "not", "isinstance", "(", "time", ",", "datetime", ".", "datetime", ")", ":", "raise", "TypeError", "(", "'Expecting datetime object.'", ")", "if", "self", ".", "_not_valid_before", "is", "...
https://github.com/trakt/Plex-Trakt-Scrobbler/blob/aeb0bfbe62fad4b06c164f1b95581da7f35dce0b/Trakttv.bundle/Contents/Libraries/MacOSX/i386/ucs2/cryptography/x509/base.py#L456-L477
phimpme/phimpme-generator
ba6d11190b9016238f27672e1ad55e6a875b74a0
Phimpme/site-packages/coverage/data.py
python
CoverageData.write
(self, suffix=None)
Write the collected coverage data to a file. `suffix` is a suffix to append to the base file name. This can be used for multiple or parallel execution, so that many coverage data files can exist simultaneously. A dot will be used to join the base name and the suffix.
Write the collected coverage data to a file.
[ "Write", "the", "collected", "coverage", "data", "to", "a", "file", "." ]
def write(self, suffix=None): """Write the collected coverage data to a file. `suffix` is a suffix to append to the base file name. This can be used for multiple or parallel execution, so that many coverage data files can exist simultaneously. A dot will be used to join the base name and the suffix. """ if self.use_file: filename = self.filename if suffix: filename += "." + suffix self.write_file(filename)
[ "def", "write", "(", "self", ",", "suffix", "=", "None", ")", ":", "if", "self", ".", "use_file", ":", "filename", "=", "self", ".", "filename", "if", "suffix", ":", "filename", "+=", "\".\"", "+", "suffix", "self", ".", "write_file", "(", "filename", ...
https://github.com/phimpme/phimpme-generator/blob/ba6d11190b9016238f27672e1ad55e6a875b74a0/Phimpme/site-packages/coverage/data.py#L78-L91
Tautulli/Tautulli
2410eb33805aaac4bd1c5dad0f71e4f15afaf742
lib/dns/rdata.py
python
GenericRdata.from_text
(cls, rdclass, rdtype, tok, origin=None, relativize=True, relativize_to=None)
return cls(rdclass, rdtype, data)
[]
def from_text(cls, rdclass, rdtype, tok, origin=None, relativize=True, relativize_to=None): token = tok.get() if not token.is_identifier() or token.value != r'\#': raise dns.exception.SyntaxError( r'generic rdata does not start with \#') length = tok.get_int() chunks = [] while 1: token = tok.get() if token.is_eol_or_eof(): break chunks.append(token.value.encode()) hex = b''.join(chunks) data = binascii.unhexlify(hex) if len(data) != length: raise dns.exception.SyntaxError( 'generic rdata hex data has wrong length') return cls(rdclass, rdtype, data)
[ "def", "from_text", "(", "cls", ",", "rdclass", ",", "rdtype", ",", "tok", ",", "origin", "=", "None", ",", "relativize", "=", "True", ",", "relativize_to", "=", "None", ")", ":", "token", "=", "tok", ".", "get", "(", ")", "if", "not", "token", "."...
https://github.com/Tautulli/Tautulli/blob/2410eb33805aaac4bd1c5dad0f71e4f15afaf742/lib/dns/rdata.py#L360-L378
ym2011/POC-EXP
206b22d3a6b2a172359678df33bbc5b2ad04b6c3
windows/SYNfulKnock/scapy-2.3.1/scapy/utils6.py
python
in6_addrtovendor
(addr)
return res
Extract the MAC address from a modified EUI-64 constructed IPv6 address provided and use the IANA oui.txt file to get the vendor. The database used for the conversion is the one loaded by Scapy, based on Wireshark (/usr/share/wireshark/wireshark/manuf) None is returned on error, "UNKNOWN" if the vendor is unknown.
Extract the MAC address from a modified EUI-64 constructed IPv6 address provided and use the IANA oui.txt file to get the vendor. The database used for the conversion is the one loaded by Scapy, based on Wireshark (/usr/share/wireshark/wireshark/manuf) None is returned on error, "UNKNOWN" if the vendor is unknown.
[ "Extract", "the", "MAC", "address", "from", "a", "modified", "EUI", "-", "64", "constructed", "IPv6", "address", "provided", "and", "use", "the", "IANA", "oui", ".", "txt", "file", "to", "get", "the", "vendor", ".", "The", "database", "used", "for", "the...
def in6_addrtovendor(addr): """ Extract the MAC address from a modified EUI-64 constructed IPv6 address provided and use the IANA oui.txt file to get the vendor. The database used for the conversion is the one loaded by Scapy, based on Wireshark (/usr/share/wireshark/wireshark/manuf) None is returned on error, "UNKNOWN" if the vendor is unknown. """ mac = in6_addrtomac(addr) if mac is None: return None res = conf.manufdb._get_manuf(mac) if len(res) == 17 and res.count(':') != 5: # Mac address, i.e. unknown res = "UNKNOWN" return res
[ "def", "in6_addrtovendor", "(", "addr", ")", ":", "mac", "=", "in6_addrtomac", "(", "addr", ")", "if", "mac", "is", "None", ":", "return", "None", "res", "=", "conf", ".", "manufdb", ".", "_get_manuf", "(", "mac", ")", "if", "len", "(", "res", ")", ...
https://github.com/ym2011/POC-EXP/blob/206b22d3a6b2a172359678df33bbc5b2ad04b6c3/windows/SYNfulKnock/scapy-2.3.1/scapy/utils6.py#L268-L284
taowen/es-monitor
c4deceb4964857f495d13bfaf2d92f36734c9e1c
es_sql/sqlparse/sql.py
python
TokenList.get_token_at_offset
(self, offset)
Returns the token that is on position offset.
Returns the token that is on position offset.
[ "Returns", "the", "token", "that", "is", "on", "position", "offset", "." ]
def get_token_at_offset(self, offset): """Returns the token that is on position offset.""" idx = 0 for token in self.flatten(): end = idx + len(token.value) if idx <= offset <= end: return token idx = end
[ "def", "get_token_at_offset", "(", "self", ",", "offset", ")", ":", "idx", "=", "0", "for", "token", "in", "self", ".", "flatten", "(", ")", ":", "end", "=", "idx", "+", "len", "(", "token", ".", "value", ")", "if", "idx", "<=", "offset", "<=", "...
https://github.com/taowen/es-monitor/blob/c4deceb4964857f495d13bfaf2d92f36734c9e1c/es_sql/sqlparse/sql.py#L206-L213
SBCV/Blender-Addon-Photogrammetry-Importer
d964ef04cefde73320749cc346113e16be5bd73b
photogrammetry_importer/operators/open3d_import_op.py
python
ImportOpen3DOperator.invoke
(self, context, event)
return {"RUNNING_MODAL"}
Set the default import options before running the operator.
Set the default import options before running the operator.
[ "Set", "the", "default", "import", "options", "before", "running", "the", "operator", "." ]
def invoke(self, context, event): """Set the default import options before running the operator.""" self.initialize_options_from_addon_preferences() context.window_manager.fileselect_add(self) return {"RUNNING_MODAL"}
[ "def", "invoke", "(", "self", ",", "context", ",", "event", ")", ":", "self", ".", "initialize_options_from_addon_preferences", "(", ")", "context", ".", "window_manager", ".", "fileselect_add", "(", "self", ")", "return", "{", "\"RUNNING_MODAL\"", "}" ]
https://github.com/SBCV/Blender-Addon-Photogrammetry-Importer/blob/d964ef04cefde73320749cc346113e16be5bd73b/photogrammetry_importer/operators/open3d_import_op.py#L150-L154
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/Python-2.7.9/Lib/pydoc.py
python
ispath
(x)
return isinstance(x, str) and find(x, os.sep) >= 0
[]
def ispath(x): return isinstance(x, str) and find(x, os.sep) >= 0
[ "def", "ispath", "(", "x", ")", ":", "return", "isinstance", "(", "x", ",", "str", ")", "and", "find", "(", "x", ",", "os", ".", "sep", ")", ">=", "0" ]
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/Python-2.7.9/Lib/pydoc.py#L2312-L2313
F8LEFT/DecLLVM
d38e45e3d0dd35634adae1d0cf7f96f3bd96e74c
python/idaapi.py
python
cswitch_t.__eq__
(self, *args)
return _idaapi.cswitch_t___eq__(self, *args)
__eq__(self, r) -> bool
__eq__(self, r) -> bool
[ "__eq__", "(", "self", "r", ")", "-", ">", "bool" ]
def __eq__(self, *args): """ __eq__(self, r) -> bool """ return _idaapi.cswitch_t___eq__(self, *args)
[ "def", "__eq__", "(", "self", ",", "*", "args", ")", ":", "return", "_idaapi", ".", "cswitch_t___eq__", "(", "self", ",", "*", "args", ")" ]
https://github.com/F8LEFT/DecLLVM/blob/d38e45e3d0dd35634adae1d0cf7f96f3bd96e74c/python/idaapi.py#L38734-L38738
sagemath/sage
f9b2db94f675ff16963ccdefba4f1a3393b3fe0d
src/sage_docbuild/ext/inventory_builder.py
python
InventoryBuilder.finish
(self)
Only write the inventory files.
Only write the inventory files.
[ "Only", "write", "the", "inventory", "files", "." ]
def finish(self): """ Only write the inventory files. """ self.write_buildinfo() self.dump_inventory()
[ "def", "finish", "(", "self", ")", ":", "self", ".", "write_buildinfo", "(", ")", "self", ".", "dump_inventory", "(", ")" ]
https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage_docbuild/ext/inventory_builder.py#L66-L71
nixgates/plugin.video.seren
b6091842844337a0de51646be3f5a411d5185997
resources/lib/database/premiumizeTransfers/__init__.py
python
PremiumizeTransfers.get_premiumize_transfers
(self)
return self.fetchall("SELECT * FROM transfers")
Fetch all transfer created by Seren not removed :return: List of all transfers :rtype: list
Fetch all transfer created by Seren not removed :return: List of all transfers :rtype: list
[ "Fetch", "all", "transfer", "created", "by", "Seren", "not", "removed", ":", "return", ":", "List", "of", "all", "transfers", ":", "rtype", ":", "list" ]
def get_premiumize_transfers(self): """ Fetch all transfer created by Seren not removed :return: List of all transfers :rtype: list """ return self.fetchall("SELECT * FROM transfers")
[ "def", "get_premiumize_transfers", "(", "self", ")", ":", "return", "self", ".", "fetchall", "(", "\"SELECT * FROM transfers\"", ")" ]
https://github.com/nixgates/plugin.video.seren/blob/b6091842844337a0de51646be3f5a411d5185997/resources/lib/database/premiumizeTransfers/__init__.py#L29-L35
google/closure-linter
c09c885b4e4fec386ff81cebeb8c66c2b0643d49
closure_linter/tokenutil.py
python
InsertSpaceTokenAfter
(token)
Inserts a space token after the given token. Args: token: The token to insert a space token after Returns: A single space token
Inserts a space token after the given token.
[ "Inserts", "a", "space", "token", "after", "the", "given", "token", "." ]
def InsertSpaceTokenAfter(token): """Inserts a space token after the given token. Args: token: The token to insert a space token after Returns: A single space token """ space_token = JavaScriptToken(' ', Type.WHITESPACE, token.line, token.line_number) InsertTokenAfter(space_token, token)
[ "def", "InsertSpaceTokenAfter", "(", "token", ")", ":", "space_token", "=", "JavaScriptToken", "(", "' '", ",", "Type", ".", "WHITESPACE", ",", "token", ".", "line", ",", "token", ".", "line_number", ")", "InsertTokenAfter", "(", "space_token", ",", "token", ...
https://github.com/google/closure-linter/blob/c09c885b4e4fec386ff81cebeb8c66c2b0643d49/closure_linter/tokenutil.py#L342-L353
cloudtools/troposphere
62a90a5e88c6e2df8c3f0a5d56284df212438dc1
troposphere/__init__.py
python
GenericHelperFn.__init__
(self, data)
[]
def __init__(self, data): self.data = self.getdata(data)
[ "def", "__init__", "(", "self", ",", "data", ")", ":", "self", ".", "data", "=", "self", ".", "getdata", "(", "data", ")" ]
https://github.com/cloudtools/troposphere/blob/62a90a5e88c6e2df8c3f0a5d56284df212438dc1/troposphere/__init__.py#L415-L416
cupy/cupy
a47ad3105f0fe817a4957de87d98ddccb8c7491f
cupyx/scipy/ndimage/measurements.py
python
sum
(input, labels=None, index=None)
return sum_labels(input, labels, index)
Calculates the sum of the values of an n-D image array, optionally at specified sub-regions. Args: input (cupy.ndarray): Nd-image data to process. labels (cupy.ndarray or None): Labels defining sub-regions in `input`. If not None, must be same shape as `input`. index (cupy.ndarray or None): `labels` to include in output. If None (default), all values where `labels` is non-zero are used. Returns: sum (cupy.ndarray): sum of values, for each sub-region if `labels` and `index` are specified. Notes: This is an alias for `cupyx.scipy.ndimage.sum_labels` kept for backwards compatibility reasons. For new code please prefer `sum_labels`. .. seealso:: :func:`scipy.ndimage.sum`
Calculates the sum of the values of an n-D image array, optionally at specified sub-regions.
[ "Calculates", "the", "sum", "of", "the", "values", "of", "an", "n", "-", "D", "image", "array", "optionally", "at", "specified", "sub", "-", "regions", "." ]
def sum(input, labels=None, index=None): """Calculates the sum of the values of an n-D image array, optionally at specified sub-regions. Args: input (cupy.ndarray): Nd-image data to process. labels (cupy.ndarray or None): Labels defining sub-regions in `input`. If not None, must be same shape as `input`. index (cupy.ndarray or None): `labels` to include in output. If None (default), all values where `labels` is non-zero are used. Returns: sum (cupy.ndarray): sum of values, for each sub-region if `labels` and `index` are specified. Notes: This is an alias for `cupyx.scipy.ndimage.sum_labels` kept for backwards compatibility reasons. For new code please prefer `sum_labels`. .. seealso:: :func:`scipy.ndimage.sum` """ return sum_labels(input, labels, index)
[ "def", "sum", "(", "input", ",", "labels", "=", "None", ",", "index", "=", "None", ")", ":", "return", "sum_labels", "(", "input", ",", "labels", ",", "index", ")" ]
https://github.com/cupy/cupy/blob/a47ad3105f0fe817a4957de87d98ddccb8c7491f/cupyx/scipy/ndimage/measurements.py#L432-L454
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_hxb2/lib/python3.5/site-packages/wagtail_bak/wagtailadmin/templatetags/wagtailadmin_tags.py
python
main_nav_js
()
return admin_menu.media['js']
[]
def main_nav_js(): return admin_menu.media['js']
[ "def", "main_nav_js", "(", ")", ":", "return", "admin_menu", ".", "media", "[", "'js'", "]" ]
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_hxb2/lib/python3.5/site-packages/wagtail_bak/wagtailadmin/templatetags/wagtailadmin_tags.py#L88-L89
pandas-dev/pandas
5ba7d714014ae8feaccc0dd4a98890828cf2832d
pandas/core/apply.py
python
Apply.apply_str
(self)
return self._try_aggregate_string_function(obj, f, *self.args, **self.kwargs)
Compute apply in case of a string. Returns ------- result: Series or DataFrame
Compute apply in case of a string.
[ "Compute", "apply", "in", "case", "of", "a", "string", "." ]
def apply_str(self) -> DataFrame | Series: """ Compute apply in case of a string. Returns ------- result: Series or DataFrame """ # Caller is responsible for checking isinstance(self.f, str) f = cast(str, self.f) obj = self.obj # Support for `frame.transform('method')` # Some methods (shift, etc.) require the axis argument, others # don't, so inspect and insert if necessary. func = getattr(obj, f, None) if callable(func): sig = inspect.getfullargspec(func) if "axis" in sig.args: self.kwargs["axis"] = self.axis elif self.axis != 0: raise ValueError(f"Operation {f} does not support axis=1") return self._try_aggregate_string_function(obj, f, *self.args, **self.kwargs)
[ "def", "apply_str", "(", "self", ")", "->", "DataFrame", "|", "Series", ":", "# Caller is responsible for checking isinstance(self.f, str)", "f", "=", "cast", "(", "str", ",", "self", ".", "f", ")", "obj", "=", "self", ".", "obj", "# Support for `frame.transform('...
https://github.com/pandas-dev/pandas/blob/5ba7d714014ae8feaccc0dd4a98890828cf2832d/pandas/core/apply.py#L523-L546
googlearchive/simian
fb9c43946ff7ba29be417068d6447cfc0adfe9ef
src/simian/mac/admin/package.py
python
Package.UpdatePackageInfoFromPlist
(self, create_new=False)
Updates or creates a new PackageInfo entity from plist XML.
Updates or creates a new PackageInfo entity from plist XML.
[ "Updates", "or", "creates", "a", "new", "PackageInfo", "entity", "from", "plist", "XML", "." ]
def UpdatePackageInfoFromPlist(self, create_new=False): """Updates or creates a new PackageInfo entity from plist XML.""" plist_xml = self.request.get('new_pkginfo_plist').encode('utf-8').strip() try: pkginfo, log = models.PackageInfo.UpdateFromPlist( plist_xml, create_new=create_new) except models.PackageInfoUpdateError as e: self.error(httplib.BAD_REQUEST) self.Render( 'error.html', {'message': 'PackageInfoUpdateError: %s' % str(e)}) return else: if settings.EMAIL_ON_EVERY_CHANGE: self.NotifyAdminsOfPackageChangeFromPlist(log) self.redirect('/admin/package/%s?msg=PackageInfo saved#package-%s' % ( pkginfo.filename, pkginfo.filename))
[ "def", "UpdatePackageInfoFromPlist", "(", "self", ",", "create_new", "=", "False", ")", ":", "plist_xml", "=", "self", ".", "request", ".", "get", "(", "'new_pkginfo_plist'", ")", ".", "encode", "(", "'utf-8'", ")", ".", "strip", "(", ")", "try", ":", "p...
https://github.com/googlearchive/simian/blob/fb9c43946ff7ba29be417068d6447cfc0adfe9ef/src/simian/mac/admin/package.py#L360-L376
home-assistant/core
265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1
homeassistant/components/venstar/__init__.py
python
VenstarEntity.device_info
(self)
return { "identifiers": {(DOMAIN, self._config.entry_id)}, "name": self._client.name, "manufacturer": "Venstar", "model": f"{self._client.model}-{self._client.get_type()}", "sw_version": self._client.get_api_ver(), }
Return the device information for this entity.
Return the device information for this entity.
[ "Return", "the", "device", "information", "for", "this", "entity", "." ]
def device_info(self): """Return the device information for this entity.""" return { "identifiers": {(DOMAIN, self._config.entry_id)}, "name": self._client.name, "manufacturer": "Venstar", "model": f"{self._client.model}-{self._client.get_type()}", "sw_version": self._client.get_api_ver(), }
[ "def", "device_info", "(", "self", ")", ":", "return", "{", "\"identifiers\"", ":", "{", "(", "DOMAIN", ",", "self", ".", "_config", ".", "entry_id", ")", "}", ",", "\"name\"", ":", "self", ".", "_client", ".", "name", ",", "\"manufacturer\"", ":", "\"...
https://github.com/home-assistant/core/blob/265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1/homeassistant/components/venstar/__init__.py#L150-L158
tztztztztz/eql.detectron2
29224acf4ea549c53264e6229da69868bd5470f3
detectron2/structures/masks.py
python
polygons_to_bitmask
(polygons: List[np.ndarray], height: int, width: int)
return mask_utils.decode(rle).astype(np.bool)
Args: polygons (list[ndarray]): each array has shape (Nx2,) height, width (int) Returns: ndarray: a bool mask of shape (height, width)
Args: polygons (list[ndarray]): each array has shape (Nx2,) height, width (int)
[ "Args", ":", "polygons", "(", "list", "[", "ndarray", "]", ")", ":", "each", "array", "has", "shape", "(", "Nx2", ")", "height", "width", "(", "int", ")" ]
def polygons_to_bitmask(polygons: List[np.ndarray], height: int, width: int) -> np.ndarray: """ Args: polygons (list[ndarray]): each array has shape (Nx2,) height, width (int) Returns: ndarray: a bool mask of shape (height, width) """ assert len(polygons) > 0, "COCOAPI does not support empty polygons" rles = mask_utils.frPyObjects(polygons, height, width) rle = mask_utils.merge(rles) return mask_utils.decode(rle).astype(np.bool)
[ "def", "polygons_to_bitmask", "(", "polygons", ":", "List", "[", "np", ".", "ndarray", "]", ",", "height", ":", "int", ",", "width", ":", "int", ")", "->", "np", ".", "ndarray", ":", "assert", "len", "(", "polygons", ")", ">", "0", ",", "\"COCOAPI do...
https://github.com/tztztztztz/eql.detectron2/blob/29224acf4ea549c53264e6229da69868bd5470f3/detectron2/structures/masks.py#L21-L33
lovelylain/pyctp
fd304de4b50c4ddc31a4190b1caaeb5dec66bc5d
example/pyctp2/md/minute.py
python
Minutes_Previous.day_finalize
(self)
[]
def day_finalize(self): self.new_tick(DAY_FINALIZE_TICK) self._next_is_new_day = True
[ "def", "day_finalize", "(", "self", ")", ":", "self", ".", "new_tick", "(", "DAY_FINALIZE_TICK", ")", "self", ".", "_next_is_new_day", "=", "True" ]
https://github.com/lovelylain/pyctp/blob/fd304de4b50c4ddc31a4190b1caaeb5dec66bc5d/example/pyctp2/md/minute.py#L71-L73
RaRe-Technologies/bounter
21aeda1b88402bacb44ce92d05c08b632a1edb21
bounter/bounter.py
python
bounter
(size_mb=None, need_iteration=True, need_counts=True, log_counting=None)
Factory method for bounter implementation. Args: size_mb (int): Desired memory footprint of the counter. need_iteration (Bool): With `True`, create a `HashTable` implementation which can iterate over inserted key/value pairs. With `False`, create a `CountMinSketch` implementation which performs better in limited-memory scenarios, but does not support iteration over elements. need_counts (Bool): With `True`, construct the structure normally. With `False`, ignore all remaining parameters and create a minimalistic cardinality counter based on hyperloglog which only takes 64KB memory. log_counting (int): Counting to use with `CountMinSketch` implementation. Accepted values are `None` (default counting with 32-bit integers), 1024 (16-bit), 8 (8-bit). See `CountMinSketch` documentation for details. Raise ValueError if not `None `and `need_iteration` is `True`.
Factory method for bounter implementation.
[ "Factory", "method", "for", "bounter", "implementation", "." ]
def bounter(size_mb=None, need_iteration=True, need_counts=True, log_counting=None): """Factory method for bounter implementation. Args: size_mb (int): Desired memory footprint of the counter. need_iteration (Bool): With `True`, create a `HashTable` implementation which can iterate over inserted key/value pairs. With `False`, create a `CountMinSketch` implementation which performs better in limited-memory scenarios, but does not support iteration over elements. need_counts (Bool): With `True`, construct the structure normally. With `False`, ignore all remaining parameters and create a minimalistic cardinality counter based on hyperloglog which only takes 64KB memory. log_counting (int): Counting to use with `CountMinSketch` implementation. Accepted values are `None` (default counting with 32-bit integers), 1024 (16-bit), 8 (8-bit). See `CountMinSketch` documentation for details. Raise ValueError if not `None `and `need_iteration` is `True`. """ if not need_counts: return CardinalityEstimator() if size_mb is None: raise ValueError("Max size in MB must be provided.") if need_iteration: if log_counting: raise ValueError("Log counting is only supported with CMS implementation (need_iteration=False).") return HashTable(size_mb=size_mb) else: return CountMinSketch(size_mb=size_mb, log_counting=log_counting)
[ "def", "bounter", "(", "size_mb", "=", "None", ",", "need_iteration", "=", "True", ",", "need_counts", "=", "True", ",", "log_counting", "=", "None", ")", ":", "if", "not", "need_counts", ":", "return", "CardinalityEstimator", "(", ")", "if", "size_mb", "i...
https://github.com/RaRe-Technologies/bounter/blob/21aeda1b88402bacb44ce92d05c08b632a1edb21/bounter/bounter.py#L14-L39
007gzs/dingtalk-sdk
7979da2e259fdbc571728cae2425a04dbc65850a
dingtalk/client/api/taobao.py
python
TbDingDing.dingtalk_oapi_role_addrolesforemps
( self, role_ids, user_ids )
return self._top_request( "dingtalk.oapi.role.addrolesforemps", { "roleIds": role_ids, "userIds": user_ids } )
批量为员工增加角色信息 企业在做企业员工管理的时候,需要对部分员工进行角色分类,该接口可以批量为员工增加角色信息 文档地址:https://open-doc.dingtalk.com/docs/api.htm?apiId=36985 :param role_ids: 角色id list :param user_ids: 员工id list
批量为员工增加角色信息 企业在做企业员工管理的时候,需要对部分员工进行角色分类,该接口可以批量为员工增加角色信息 文档地址:https://open-doc.dingtalk.com/docs/api.htm?apiId=36985
[ "批量为员工增加角色信息", "企业在做企业员工管理的时候,需要对部分员工进行角色分类,该接口可以批量为员工增加角色信息", "文档地址:https", ":", "//", "open", "-", "doc", ".", "dingtalk", ".", "com", "/", "docs", "/", "api", ".", "htm?apiId", "=", "36985" ]
def dingtalk_oapi_role_addrolesforemps( self, role_ids, user_ids ): """ 批量为员工增加角色信息 企业在做企业员工管理的时候,需要对部分员工进行角色分类,该接口可以批量为员工增加角色信息 文档地址:https://open-doc.dingtalk.com/docs/api.htm?apiId=36985 :param role_ids: 角色id list :param user_ids: 员工id list """ return self._top_request( "dingtalk.oapi.role.addrolesforemps", { "roleIds": role_ids, "userIds": user_ids } )
[ "def", "dingtalk_oapi_role_addrolesforemps", "(", "self", ",", "role_ids", ",", "user_ids", ")", ":", "return", "self", ".", "_top_request", "(", "\"dingtalk.oapi.role.addrolesforemps\"", ",", "{", "\"roleIds\"", ":", "role_ids", ",", "\"userIds\"", ":", "user_ids", ...
https://github.com/007gzs/dingtalk-sdk/blob/7979da2e259fdbc571728cae2425a04dbc65850a/dingtalk/client/api/taobao.py#L2071-L2090
bbangert/beaker
d4ab7d37387feddd0d544792d9e32533e39ff868
beaker/middleware.py
python
session_filter_factory
(global_conf, **kwargs)
return filter
[]
def session_filter_factory(global_conf, **kwargs): def filter(app): return SessionMiddleware(app, global_conf, **kwargs) return filter
[ "def", "session_filter_factory", "(", "global_conf", ",", "*", "*", "kwargs", ")", ":", "def", "filter", "(", "app", ")", ":", "return", "SessionMiddleware", "(", "app", ",", "global_conf", ",", "*", "*", "kwargs", ")", "return", "filter" ]
https://github.com/bbangert/beaker/blob/d4ab7d37387feddd0d544792d9e32533e39ff868/beaker/middleware.py#L162-L165
gwpy/gwpy
82becd78d166a32985cb657a54d0d39f6a207739
gwpy/frequencyseries/hist.py
python
SpectralVariance.__getitem__
(self, item)
[]
def __getitem__(self, item): # disable slicing bins if not isinstance(item, tuple) or null_slice(item[1]): return super().__getitem__(item) raise NotImplementedError("cannot slice SpectralVariance across bins")
[ "def", "__getitem__", "(", "self", ",", "item", ")", ":", "# disable slicing bins", "if", "not", "isinstance", "(", "item", ",", "tuple", ")", "or", "null_slice", "(", "item", "[", "1", "]", ")", ":", "return", "super", "(", ")", ".", "__getitem__", "(...
https://github.com/gwpy/gwpy/blob/82becd78d166a32985cb657a54d0d39f6a207739/gwpy/frequencyseries/hist.py#L213-L217
kbandla/ImmunityDebugger
2abc03fb15c8f3ed0914e1175c4d8933977c73e3
1.74/Libs/immlib.py
python
Debugger.searchLong
(self, long, flag=None)
return self.search( immutils.int2str32_swapped(long),flag)
Search a short integer on the remote process memory @type long: DWORD @param long: integer to search for @type flag: STRING @param flag: Memory Protection String Flag @rtype: List @return: List of address of the integer founded
Search a short integer on the remote process memory
[ "Search", "a", "short", "integer", "on", "the", "remote", "process", "memory" ]
def searchLong(self, long, flag=None): """ Search a short integer on the remote process memory @type long: DWORD @param long: integer to search for @type flag: STRING @param flag: Memory Protection String Flag @rtype: List @return: List of address of the integer founded """ return self.search( immutils.int2str32_swapped(long),flag)
[ "def", "searchLong", "(", "self", ",", "long", ",", "flag", "=", "None", ")", ":", "return", "self", ".", "search", "(", "immutils", ".", "int2str32_swapped", "(", "long", ")", ",", "flag", ")" ]
https://github.com/kbandla/ImmunityDebugger/blob/2abc03fb15c8f3ed0914e1175c4d8933977c73e3/1.74/Libs/immlib.py#L2165-L2177
trailofbits/manticore
b050fdf0939f6c63f503cdf87ec0ab159dd41159
manticore/native/cpu/abstractcpu.py
python
Abi.get_argument_values
(self, model: Callable, prefix_args: Tuple)
Extract arguments for model from the environment and return as a tuple that is ready to be passed to the model. :param model: Python model of the function :param prefix_args: Parameters to pass to model before actual ones :return: Arguments to be passed to the model
Extract arguments for model from the environment and return as a tuple that is ready to be passed to the model.
[ "Extract", "arguments", "for", "model", "from", "the", "environment", "and", "return", "as", "a", "tuple", "that", "is", "ready", "to", "be", "passed", "to", "the", "model", "." ]
def get_argument_values(self, model: Callable, prefix_args: Tuple) -> Tuple: """ Extract arguments for model from the environment and return as a tuple that is ready to be passed to the model. :param model: Python model of the function :param prefix_args: Parameters to pass to model before actual ones :return: Arguments to be passed to the model """ if type(model) is partial: # mypy issue with partial types https://github.com/python/mypy/issues/1484 model = model.args[0] # type: ignore sig = inspect.signature(model) if _sig_is_varargs(sig): model_name = getattr(model, "__qualname__", "<no name>") logger.warning("ABI: %s: a vararg model must be a unary function.", model_name) nargs = len(sig.parameters) - len(prefix_args) def resolve_argument(arg): if isinstance(arg, str): return self._cpu.read_register(arg) else: return self._cpu.read_int(arg) # Create a stream of resolved arguments from argument descriptors descriptors = self.get_arguments() argument_iter = map(resolve_argument, descriptors) from ..models import isvariadic # prevent circular imports if isvariadic(model): return prefix_args + (argument_iter,) else: return prefix_args + tuple(islice(argument_iter, nargs))
[ "def", "get_argument_values", "(", "self", ",", "model", ":", "Callable", ",", "prefix_args", ":", "Tuple", ")", "->", "Tuple", ":", "if", "type", "(", "model", ")", "is", "partial", ":", "# mypy issue with partial types https://github.com/python/mypy/issues/1484", ...
https://github.com/trailofbits/manticore/blob/b050fdf0939f6c63f503cdf87ec0ab159dd41159/manticore/native/cpu/abstractcpu.py#L339-L373
mayank93/Twitter-Sentiment-Analysis
f095c6ca6bf69787582b5dabb140fefaf278eb37
front-end/web2py/gluon/contrib/markdown/markdown2.py
python
_memoized.__repr__
(self)
return self.func.__doc__
Return the function's docstring.
Return the function's docstring.
[ "Return", "the", "function", "s", "docstring", "." ]
def __repr__(self): """Return the function's docstring.""" return self.func.__doc__
[ "def", "__repr__", "(", "self", ")", ":", "return", "self", ".", "func", ".", "__doc__" ]
https://github.com/mayank93/Twitter-Sentiment-Analysis/blob/f095c6ca6bf69787582b5dabb140fefaf278eb37/front-end/web2py/gluon/contrib/markdown/markdown2.py#L1698-L1700
sth2018/FastWordQuery
901ebe8fd5989d8861d20ee3fec3acd15b7f46a5
addons21/fastwq/libs/mdict/pureSalsa20.py
python
rot32
( w, nLeft )
return RRR | ( sLLLLLL << nLeft )
Rotate 32-bit word left by nLeft or right by -nLeft without creating a Python long. Timing depends on nLeft but not on w.
Rotate 32-bit word left by nLeft or right by -nLeft without creating a Python long. Timing depends on nLeft but not on w.
[ "Rotate", "32", "-", "bit", "word", "left", "by", "nLeft", "or", "right", "by", "-", "nLeft", "without", "creating", "a", "Python", "long", ".", "Timing", "depends", "on", "nLeft", "but", "not", "on", "w", "." ]
def rot32( w, nLeft ): """ Rotate 32-bit word left by nLeft or right by -nLeft without creating a Python long. Timing depends on nLeft but not on w. """ nLeft &= 31 # which makes nLeft >= 0 if nLeft == 0: return w # Note: now 1 <= nLeft <= 31. # RRRsLLLLLL There are nLeft RRR's, (31-nLeft) LLLLLL's, # => sLLLLLLRRR and one s which becomes the sign bit. RRR = ( ( ( w >> 1 ) & 0x7fffFFFF ) >> ( 31 - nLeft ) ) sLLLLLL = -( (1<<(31-nLeft)) & w ) | (0x7fffFFFF>>nLeft) & w return RRR | ( sLLLLLL << nLeft )
[ "def", "rot32", "(", "w", ",", "nLeft", ")", ":", "nLeft", "&=", "31", "# which makes nLeft >= 0", "if", "nLeft", "==", "0", ":", "return", "w", "# Note: now 1 <= nLeft <= 31.", "# RRRsLLLLLL There are nLeft RRR's, (31-nLeft) LLLLLL's,", "# => sLLLLLLRRR and one s ...
https://github.com/sth2018/FastWordQuery/blob/901ebe8fd5989d8861d20ee3fec3acd15b7f46a5/addons21/fastwq/libs/mdict/pureSalsa20.py#L348-L362
facebookresearch/ReAgent
52f666670a7fa03206812ef48949f6b934d400f7
reagent/models/cem_planner.py
python
CEMPlannerNetwork.acc_rewards_of_all_solutions
( self, state: rlt.FeatureData, solutions: torch.Tensor )
return acc_reward_vec
Calculate accumulated rewards of solutions. :param state: the input which contains the starting state :param solutions: its shape is (cem_pop_size, plan_horizon_length, action_dim) :returns: a vector of size cem_pop_size, which is the reward of each solution
Calculate accumulated rewards of solutions.
[ "Calculate", "accumulated", "rewards", "of", "solutions", "." ]
def acc_rewards_of_all_solutions( self, state: rlt.FeatureData, solutions: torch.Tensor ) -> float: """ Calculate accumulated rewards of solutions. :param state: the input which contains the starting state :param solutions: its shape is (cem_pop_size, plan_horizon_length, action_dim) :returns: a vector of size cem_pop_size, which is the reward of each solution """ acc_reward_vec = np.zeros(self.cem_pop_size) init_state = state.float_features for i in range(self.cem_pop_size): if i % (self.cem_pop_size // 10) == 0: logger.debug(f"Simulating the {i}-th solution...") acc_reward_vec[i] = self.acc_rewards_of_one_solution( init_state, solutions[i], i ) return acc_reward_vec
[ "def", "acc_rewards_of_all_solutions", "(", "self", ",", "state", ":", "rlt", ".", "FeatureData", ",", "solutions", ":", "torch", ".", "Tensor", ")", "->", "float", ":", "acc_reward_vec", "=", "np", ".", "zeros", "(", "self", ".", "cem_pop_size", ")", "ini...
https://github.com/facebookresearch/ReAgent/blob/52f666670a7fa03206812ef48949f6b934d400f7/reagent/models/cem_planner.py#L169-L187
Epistimio/orion
732e739d99561020dbe620760acf062ade746006
src/orion/algo/gridsearch.py
python
GridSearch.build_grid
(space, n_values, max_trials=10000)
return list(itertools.product(*coordinates))
Build a grid of trials Parameters ---------- n_values: int or dict Number of trials for each dimensions, or dictionary specifying number of trials for each dimension independently (name, n_values). For categorical dimensions, n_values will not be used, and all categories will be used to build the grid. max_trials: int Maximum number of trials for the grid. If n_values lead to more trials than max_trials, the n_values will be adjusted down. Will raise ValueError if it is impossible to build a grid smaller than max_trials (for instance if choices are too large).
Build a grid of trials
[ "Build", "a", "grid", "of", "trials" ]
def build_grid(space, n_values, max_trials=10000): """Build a grid of trials Parameters ---------- n_values: int or dict Number of trials for each dimensions, or dictionary specifying number of trials for each dimension independently (name, n_values). For categorical dimensions, n_values will not be used, and all categories will be used to build the grid. max_trials: int Maximum number of trials for the grid. If n_values lead to more trials than max_trials, the n_values will be adjusted down. Will raise ValueError if it is impossible to build a grid smaller than max_trials (for instance if choices are too large). """ adjust = 0 n_trials = float("inf") while n_trials > max_trials: coordinates = [] capped_values = [] for name, dim in space.items(): capped_value = max(n_values[name] - adjust, 1) capped_values.append(capped_value) coordinates.append(list(grid(dim, capped_value))) if all(value <= 1 for value in capped_values): raise ValueError( f"Cannot build a grid smaller than {max_trials}. " "Try reducing the number of choices in categorical dimensions." ) n_trials = numpy.prod([len(dim_values) for dim_values in coordinates]) # TODO: Use binary search instead of incrementing by one. adjust += 1 if adjust > 1: log.warning( f"`n_values` reduced by {adjust-1} to limit number of trials below {max_trials}." ) return list(itertools.product(*coordinates))
[ "def", "build_grid", "(", "space", ",", "n_values", ",", "max_trials", "=", "10000", ")", ":", "adjust", "=", "0", "n_trials", "=", "float", "(", "\"inf\"", ")", "while", "n_trials", ">", "max_trials", ":", "coordinates", "=", "[", "]", "capped_values", ...
https://github.com/Epistimio/orion/blob/732e739d99561020dbe620760acf062ade746006/src/orion/algo/gridsearch.py#L133-L174
CouchPotato/CouchPotatoV1
135b3331d1b88ef645e29b76f2d4cc4a732c9232
library/hachoir_core/field/generic_field_set.py
python
GenericFieldSet.__iter__
(self)
Create a generator to iterate on each field, may create new fields when needed
Create a generator to iterate on each field, may create new fields when needed
[ "Create", "a", "generator", "to", "iterate", "on", "each", "field", "may", "create", "new", "fields", "when", "needed" ]
def __iter__(self): """ Create a generator to iterate on each field, may create new fields when needed """ try: done = 0 while True: if done == len(self._fields): if self._field_generator is None: break self._addField( self._field_generator.next() ) for field in self._fields.values[done:]: yield field done += 1 except HACHOIR_ERRORS, err: field = self._fixFeedError(err) if isinstance(field, Field): yield field elif hasattr(field, '__iter__'): for f in field: yield f elif field is False: raise except StopIteration: field = self._stopFeeding() if isinstance(field, Field): yield field elif hasattr(field, '__iter__'): for f in field: yield f
[ "def", "__iter__", "(", "self", ")", ":", "try", ":", "done", "=", "0", "while", "True", ":", "if", "done", "==", "len", "(", "self", ".", "_fields", ")", ":", "if", "self", ".", "_field_generator", "is", "None", ":", "break", "self", ".", "_addFie...
https://github.com/CouchPotato/CouchPotatoV1/blob/135b3331d1b88ef645e29b76f2d4cc4a732c9232/library/hachoir_core/field/generic_field_set.py#L370-L400
tableau/rest-api-samples
0be12fa52c6e66104633ab26e67fdf73ae411b33
python/publish_workbook.py
python
_encode_for_display
(text)
return text.encode('ascii', errors="backslashreplace").decode('utf-8')
Encodes strings so they can display as ASCII in a Windows terminal window. This function also encodes strings for processing by xml.etree.ElementTree functions. Returns an ASCII-encoded version of the text. Unicode characters are converted to ASCII placeholders (for example, "?").
Encodes strings so they can display as ASCII in a Windows terminal window. This function also encodes strings for processing by xml.etree.ElementTree functions. Returns an ASCII-encoded version of the text. Unicode characters are converted to ASCII placeholders (for example, "?").
[ "Encodes", "strings", "so", "they", "can", "display", "as", "ASCII", "in", "a", "Windows", "terminal", "window", ".", "This", "function", "also", "encodes", "strings", "for", "processing", "by", "xml", ".", "etree", ".", "ElementTree", "functions", ".", "Ret...
def _encode_for_display(text): """ Encodes strings so they can display as ASCII in a Windows terminal window. This function also encodes strings for processing by xml.etree.ElementTree functions. Returns an ASCII-encoded version of the text. Unicode characters are converted to ASCII placeholders (for example, "?"). """ return text.encode('ascii', errors="backslashreplace").decode('utf-8')
[ "def", "_encode_for_display", "(", "text", ")", ":", "return", "text", ".", "encode", "(", "'ascii'", ",", "errors", "=", "\"backslashreplace\"", ")", ".", "decode", "(", "'utf-8'", ")" ]
https://github.com/tableau/rest-api-samples/blob/0be12fa52c6e66104633ab26e67fdf73ae411b33/python/publish_workbook.py#L64-L72
replit-archive/empythoned
977ec10ced29a3541a4973dc2b59910805695752
cpython/Lib/urlparse.py
python
parse_qsl
(qs, keep_blank_values=0, strict_parsing=0)
return r
Parse a query given as a string argument. Arguments: qs: percent-encoded query string to be parsed keep_blank_values: flag indicating whether blank values in percent-encoded queries should be treated as blank strings. A true value indicates that blanks should be retained as blank strings. The default false value indicates that blank values are to be ignored and treated as if they were not included. strict_parsing: flag indicating what to do with parsing errors. If false (the default), errors are silently ignored. If true, errors raise a ValueError exception. Returns a list, as G-d intended.
Parse a query given as a string argument.
[ "Parse", "a", "query", "given", "as", "a", "string", "argument", "." ]
def parse_qsl(qs, keep_blank_values=0, strict_parsing=0): """Parse a query given as a string argument. Arguments: qs: percent-encoded query string to be parsed keep_blank_values: flag indicating whether blank values in percent-encoded queries should be treated as blank strings. A true value indicates that blanks should be retained as blank strings. The default false value indicates that blank values are to be ignored and treated as if they were not included. strict_parsing: flag indicating what to do with parsing errors. If false (the default), errors are silently ignored. If true, errors raise a ValueError exception. Returns a list, as G-d intended. """ pairs = [s2 for s1 in qs.split('&') for s2 in s1.split(';')] r = [] for name_value in pairs: if not name_value and not strict_parsing: continue nv = name_value.split('=', 1) if len(nv) != 2: if strict_parsing: raise ValueError, "bad query field: %r" % (name_value,) # Handle case of a control-name with no equal sign if keep_blank_values: nv.append('') else: continue if len(nv[1]) or keep_blank_values: name = unquote(nv[0].replace('+', ' ')) value = unquote(nv[1].replace('+', ' ')) r.append((name, value)) return r
[ "def", "parse_qsl", "(", "qs", ",", "keep_blank_values", "=", "0", ",", "strict_parsing", "=", "0", ")", ":", "pairs", "=", "[", "s2", "for", "s1", "in", "qs", ".", "split", "(", "'&'", ")", "for", "s2", "in", "s1", ".", "split", "(", "';'", ")",...
https://github.com/replit-archive/empythoned/blob/977ec10ced29a3541a4973dc2b59910805695752/cpython/Lib/urlparse.py#L359-L397
certbot/certbot
30b066f08260b73fc26256b5484a180468b9d0a6
certbot/certbot/reverter.py
python
Reverter.register_undo_command
(self, temporary: bool, command: Iterable[str])
Register a command to be run to undo actions taken. .. warning:: This function does not enforce order of operations in terms of file modification vs. command registration. All undo commands are run first before all normal files are reverted to their previous state. If you need to maintain strict order, you may create checkpoints before and after the the command registration. This function may be improved in the future based on demand. :param bool temporary: Whether the command should be saved in the IN_PROGRESS or TEMPORARY checkpoints. :param command: Command to be run. :type command: list of str
Register a command to be run to undo actions taken.
[ "Register", "a", "command", "to", "be", "run", "to", "undo", "actions", "taken", "." ]
def register_undo_command(self, temporary: bool, command: Iterable[str]) -> None: """Register a command to be run to undo actions taken. .. warning:: This function does not enforce order of operations in terms of file modification vs. command registration. All undo commands are run first before all normal files are reverted to their previous state. If you need to maintain strict order, you may create checkpoints before and after the the command registration. This function may be improved in the future based on demand. :param bool temporary: Whether the command should be saved in the IN_PROGRESS or TEMPORARY checkpoints. :param command: Command to be run. :type command: list of str """ commands_fp = os.path.join(self._get_cp_dir(temporary), "COMMANDS") # It is strongly advised to set newline = '' on Python 3 with CSV, # and it fixes problems on Windows. kwargs = {'newline': ''} try: mode = "a" if os.path.isfile(commands_fp) else "w" with open(commands_fp, mode, **kwargs) as f: # type: ignore csvwriter = csv.writer(f) csvwriter.writerow(command) except (IOError, OSError): logger.error("Unable to register undo command") raise errors.ReverterError( "Unable to register undo command.")
[ "def", "register_undo_command", "(", "self", ",", "temporary", ":", "bool", ",", "command", ":", "Iterable", "[", "str", "]", ")", "->", "None", ":", "commands_fp", "=", "os", ".", "path", ".", "join", "(", "self", ".", "_get_cp_dir", "(", "temporary", ...
https://github.com/certbot/certbot/blob/30b066f08260b73fc26256b5484a180468b9d0a6/certbot/certbot/reverter.py#L341-L369
tendenci/tendenci
0f2c348cc0e7d41bc56f50b00ce05544b083bf1d
tendenci/apps/invoices/models.py
python
Invoice.save
(self, user=None)
Set guid, creator and owner if any of these fields are missing.
Set guid, creator and owner if any of these fields are missing.
[ "Set", "guid", "creator", "and", "owner", "if", "any", "of", "these", "fields", "are", "missing", "." ]
def save(self, user=None): """ Set guid, creator and owner if any of these fields are missing. """ self.guid = self.guid or uuid.uuid4().hex if hasattr(user, 'pk') and not user.is_anonymous: self.set_creator(user) self.set_owner(user) # assign entity if not self.entity_id and self.object_type: self.entity = self.get_entity() self.verifydata() super(Invoice, self).save()
[ "def", "save", "(", "self", ",", "user", "=", "None", ")", ":", "self", ".", "guid", "=", "self", ".", "guid", "or", "uuid", ".", "uuid4", "(", ")", ".", "hex", "if", "hasattr", "(", "user", ",", "'pk'", ")", "and", "not", "user", ".", "is_anon...
https://github.com/tendenci/tendenci/blob/0f2c348cc0e7d41bc56f50b00ce05544b083bf1d/tendenci/apps/invoices/models.py#L212-L228
atlassian-api/atlassian-python-api
6d8545a790c3aae10b75bdc225fb5c3a0aee44db
atlassian/bitbucket/cloud/repositories/issues.py
python
Issue.state
(self, state)
return self.update(state=state)
Setter for the issue state
Setter for the issue state
[ "Setter", "for", "the", "issue", "state" ]
def state(self, state): """Setter for the issue state""" return self.update(state=state)
[ "def", "state", "(", "self", ",", "state", ")", ":", "return", "self", ".", "update", "(", "state", "=", "state", ")" ]
https://github.com/atlassian-api/atlassian-python-api/blob/6d8545a790c3aae10b75bdc225fb5c3a0aee44db/atlassian/bitbucket/cloud/repositories/issues.py#L117-L119
sagemath/sage
f9b2db94f675ff16963ccdefba4f1a3393b3fe0d
src/sage/dynamics/arithmetic_dynamics/projective_ds.py
python
DynamicalSystem_projective.is_PGL_minimal
(self, prime_list=None)
return affine_minimal(self, return_transformation=False, D=prime_list, quick=True)
r""" Check if this dynamical system is a minimal model in its conjugacy class. See [BM2012]_ and [Mol2015]_ for a description of the algorithm. For polynomial maps it uses [HS2018]_. INPUT: - ``prime_list`` -- (optional) list of primes to check minimality OUTPUT: boolean EXAMPLES:: sage: PS.<X,Y> = ProjectiveSpace(QQ,1) sage: f = DynamicalSystem_projective([X^2+3*Y^2, X*Y]) sage: f.is_PGL_minimal() True :: sage: PS.<x,y> = ProjectiveSpace(QQ,1) sage: f = DynamicalSystem_projective([6*x^2+12*x*y+7*y^2, 12*x*y]) sage: f.is_PGL_minimal() False :: sage: PS.<x,y> = ProjectiveSpace(QQ,1) sage: f = DynamicalSystem_projective([6*x^2+12*x*y+7*y^2, y^2]) sage: f.is_PGL_minimal() False
r""" Check if this dynamical system is a minimal model in its conjugacy class.
[ "r", "Check", "if", "this", "dynamical", "system", "is", "a", "minimal", "model", "in", "its", "conjugacy", "class", "." ]
def is_PGL_minimal(self, prime_list=None): r""" Check if this dynamical system is a minimal model in its conjugacy class. See [BM2012]_ and [Mol2015]_ for a description of the algorithm. For polynomial maps it uses [HS2018]_. INPUT: - ``prime_list`` -- (optional) list of primes to check minimality OUTPUT: boolean EXAMPLES:: sage: PS.<X,Y> = ProjectiveSpace(QQ,1) sage: f = DynamicalSystem_projective([X^2+3*Y^2, X*Y]) sage: f.is_PGL_minimal() True :: sage: PS.<x,y> = ProjectiveSpace(QQ,1) sage: f = DynamicalSystem_projective([6*x^2+12*x*y+7*y^2, 12*x*y]) sage: f.is_PGL_minimal() False :: sage: PS.<x,y> = ProjectiveSpace(QQ,1) sage: f = DynamicalSystem_projective([6*x^2+12*x*y+7*y^2, y^2]) sage: f.is_PGL_minimal() False """ if self.base_ring() != QQ and self.base_ring() != ZZ: raise NotImplementedError("minimal models only implemented over ZZ or QQ") if not self.is_morphism(): raise TypeError("the function is not a morphism") if self.degree() == 1: raise NotImplementedError("minimality is only for degree 2 or higher") f = copy(self) f.normalize_coordinates() R = f.domain().coordinate_ring() F = R(f[0].numerator()) G = R(f[0].denominator()) if G.degree() == 0 or F.degree() == 0: #can't use BM for polynomial from .endPN_minimal_model import HS_minimal g, m = HS_minimal(self, return_transformation=True, D=prime_list) return m == m.parent().one() from .endPN_minimal_model import affine_minimal return affine_minimal(self, return_transformation=False, D=prime_list, quick=True)
[ "def", "is_PGL_minimal", "(", "self", ",", "prime_list", "=", "None", ")", ":", "if", "self", ".", "base_ring", "(", ")", "!=", "QQ", "and", "self", ".", "base_ring", "(", ")", "!=", "ZZ", ":", "raise", "NotImplementedError", "(", "\"minimal models only im...
https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/dynamics/arithmetic_dynamics/projective_ds.py#L2688-L2742
chribsen/simple-machine-learning-examples
dc94e52a4cebdc8bb959ff88b81ff8cfeca25022
venv/lib/python2.7/site-packages/scipy/io/arff/arffread.py
python
get_nominal
(attribute)
return attribute.split(',')
If attribute is nominal, returns a list of the values
If attribute is nominal, returns a list of the values
[ "If", "attribute", "is", "nominal", "returns", "a", "list", "of", "the", "values" ]
def get_nominal(attribute): """If attribute is nominal, returns a list of the values""" return attribute.split(',')
[ "def", "get_nominal", "(", "attribute", ")", ":", "return", "attribute", ".", "split", "(", "','", ")" ]
https://github.com/chribsen/simple-machine-learning-examples/blob/dc94e52a4cebdc8bb959ff88b81ff8cfeca25022/venv/lib/python2.7/site-packages/scipy/io/arff/arffread.py#L92-L94
mpenning/ciscoconfparse
a6a176e6ceac7c5f3e974272fa70273476ba84a3
ciscoconfparse/models_junos.py
python
JunosIntfGlobal.is_object_for
(cls, line="", re=re)
return False
[]
def is_object_for(cls, line="", re=re): if re.search( r"^(no\s+cdp\s+run)|(logging\s+event\s+link-status\s+global)|(spanning-tree\sportfast\sdefault)|(spanning-tree\sportfast\sbpduguard\sdefault)", line, ): return True return False
[ "def", "is_object_for", "(", "cls", ",", "line", "=", "\"\"", ",", "re", "=", "re", ")", ":", "if", "re", ".", "search", "(", "r\"^(no\\s+cdp\\s+run)|(logging\\s+event\\s+link-status\\s+global)|(spanning-tree\\sportfast\\sdefault)|(spanning-tree\\sportfast\\sbpduguard\\sdefault...
https://github.com/mpenning/ciscoconfparse/blob/a6a176e6ceac7c5f3e974272fa70273476ba84a3/ciscoconfparse/models_junos.py#L565-L571
shiweibsw/Translation-Tools
2fbbf902364e557fa7017f9a74a8797b7440c077
venv/Lib/site-packages/pip-9.0.3-py3.6.egg/pip/_vendor/requests/cookies.py
python
MockRequest.__init__
(self, request)
[]
def __init__(self, request): self._r = request self._new_headers = {} self.type = urlparse(self._r.url).scheme
[ "def", "__init__", "(", "self", ",", "request", ")", ":", "self", ".", "_r", "=", "request", "self", ".", "_new_headers", "=", "{", "}", "self", ".", "type", "=", "urlparse", "(", "self", ".", "_r", ".", "url", ")", ".", "scheme" ]
https://github.com/shiweibsw/Translation-Tools/blob/2fbbf902364e557fa7017f9a74a8797b7440c077/venv/Lib/site-packages/pip-9.0.3-py3.6.egg/pip/_vendor/requests/cookies.py#L38-L41
nucleic/enaml
65c2a2a2d765e88f2e1103046680571894bb41ed
enaml/qt/qt_color_dialog.py
python
QtColorDialog.on_color_selected
(self, qcolor)
Handle the 'colorSelected' signal from the widget.
Handle the 'colorSelected' signal from the widget.
[ "Handle", "the", "colorSelected", "signal", "from", "the", "widget", "." ]
def on_color_selected(self, qcolor): """ Handle the 'colorSelected' signal from the widget. """ d = self.declaration if d is not None: d.selected_color = color_from_qcolor(qcolor)
[ "def", "on_color_selected", "(", "self", ",", "qcolor", ")", ":", "d", "=", "self", ".", "declaration", "if", "d", "is", "not", "None", ":", "d", ".", "selected_color", "=", "color_from_qcolor", "(", "qcolor", ")" ]
https://github.com/nucleic/enaml/blob/65c2a2a2d765e88f2e1103046680571894bb41ed/enaml/qt/qt_color_dialog.py#L118-L124
trezor/trezor-firmware
5c4703c9bbfb962fbbe409c2e40030f30161e4f0
python/tools/firmware-fingerprint.py
python
firmware_fingerprint
(filename: BinaryIO, output: TextIO)
Display fingerprint of a firmware file.
Display fingerprint of a firmware file.
[ "Display", "fingerprint", "of", "a", "firmware", "file", "." ]
def firmware_fingerprint(filename: BinaryIO, output: TextIO) -> None: """Display fingerprint of a firmware file.""" data = filename.read() try: version, fw = firmware.parse(data) # Unsigned production builds for Trezor T do not have valid code hashes. # Use the internal module which recomputes them first. if version == firmware.FirmwareFormat.TREZOR_T: fingerprint = firmware_headers.FirmwareImage(fw).digest() else: fingerprint = firmware.digest(version, fw) except Exception as e: click.echo(e, err=True) sys.exit(2) click.echo(fingerprint.hex(), file=output)
[ "def", "firmware_fingerprint", "(", "filename", ":", "BinaryIO", ",", "output", ":", "TextIO", ")", "->", "None", ":", "data", "=", "filename", ".", "read", "(", ")", "try", ":", "version", ",", "fw", "=", "firmware", ".", "parse", "(", "data", ")", ...
https://github.com/trezor/trezor-firmware/blob/5c4703c9bbfb962fbbe409c2e40030f30161e4f0/python/tools/firmware-fingerprint.py#L31-L48
tlsfuzzer/tlslite-ng
8720db53067ba4f7bb7b5a32d682033d8b5446f9
tlslite/extensions.py
python
TACKExtension.create
(self, tacks, activation_flags)
return self
Initialize the instance of TACKExtension :rtype: TACKExtension
Initialize the instance of TACKExtension
[ "Initialize", "the", "instance", "of", "TACKExtension" ]
def create(self, tacks, activation_flags): """ Initialize the instance of TACKExtension :rtype: TACKExtension """ self.tacks = tacks self.activation_flags = activation_flags return self
[ "def", "create", "(", "self", ",", "tacks", ",", "activation_flags", ")", ":", "self", ".", "tacks", "=", "tacks", "self", ".", "activation_flags", "=", "activation_flags", "return", "self" ]
https://github.com/tlsfuzzer/tlslite-ng/blob/8720db53067ba4f7bb7b5a32d682033d8b5446f9/tlslite/extensions.py#L1322-L1331
fofix/fofix
7730d1503c66562b901f62b33a5bd46c3d5e5c34
fofix/game/guitarscene/Rockmeter.py
python
Layer.render
(self, visibility, playerNum)
Handle the final step of rendering the image.
Handle the final step of rendering the image.
[ "Handle", "the", "final", "step", "of", "rendering", "the", "image", "." ]
def render(self, visibility, playerNum): """ Handle the final step of rendering the image. """ pass
[ "def", "render", "(", "self", ",", "visibility", ",", "playerNum", ")", ":", "pass" ]
https://github.com/fofix/fofix/blob/7730d1503c66562b901f62b33a5bd46c3d5e5c34/fofix/game/guitarscene/Rockmeter.py#L217-L219
nicemayi/play-with-data-structures
fa82cfeb9a1ae3faec859f207b1eca6952cee525
chapter_06_BST/bst.py
python
BST.level_order
(self)
非常好的BFS例子
非常好的BFS例子
[ "非常好的BFS例子" ]
def level_order(self): """非常好的BFS例子""" queue = deque() queue.append(self._root) while queue: curr = queue.popleft() print(curr.e) if curr.left: queue.append(curr.left) if curr.right: queue.append(curr.right)
[ "def", "level_order", "(", "self", ")", ":", "queue", "=", "deque", "(", ")", "queue", ".", "append", "(", "self", ".", "_root", ")", "while", "queue", ":", "curr", "=", "queue", ".", "popleft", "(", ")", "print", "(", "curr", ".", "e", ")", "if"...
https://github.com/nicemayi/play-with-data-structures/blob/fa82cfeb9a1ae3faec859f207b1eca6952cee525/chapter_06_BST/bst.py#L114-L124
lululxvi/deepxde
730c97282636e86c845ce2ba3253482f2178469e
deepxde/model.py
python
LossHistory.append
(self, step, loss_train, loss_test, metrics_test)
[]
def append(self, step, loss_train, loss_test, metrics_test): self.steps.append(step) self.loss_train.append(loss_train) if loss_test is None: loss_test = self.loss_test[-1] if metrics_test is None: metrics_test = self.metrics_test[-1] self.loss_test.append(loss_test) self.metrics_test.append(metrics_test)
[ "def", "append", "(", "self", ",", "step", ",", "loss_train", ",", "loss_test", ",", "metrics_test", ")", ":", "self", ".", "steps", ".", "append", "(", "step", ")", "self", ".", "loss_train", ".", "append", "(", "loss_train", ")", "if", "loss_test", "...
https://github.com/lululxvi/deepxde/blob/730c97282636e86c845ce2ba3253482f2178469e/deepxde/model.py#L769-L777
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/lib/python2.7/site-packages/pip/_vendor/urllib3/exceptions.py
python
ProxySchemeUnknown.__init__
(self, scheme)
[]
def __init__(self, scheme): message = "Not supported proxy scheme %s" % scheme super(ProxySchemeUnknown, self).__init__(message)
[ "def", "__init__", "(", "self", ",", "scheme", ")", ":", "message", "=", "\"Not supported proxy scheme %s\"", "%", "scheme", "super", "(", "ProxySchemeUnknown", ",", "self", ")", ".", "__init__", "(", "message", ")" ]
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/lib/python2.7/site-packages/pip/_vendor/urllib3/exceptions.py#L232-L234
kanzure/nanoengineer
874e4c9f8a9190f093625b267f9767e19f82e6c4
cad/src/outtakes/Peptide.py
python
Peptide._update
(self)
Private method. Updates all chirality parameters whenever the following attrs are changed via their set methods: - n, m, - type - bond_length
Private method.
[ "Private", "method", "." ]
def _update(self): """ Private method. Updates all chirality parameters whenever the following attrs are changed via their set methods: - n, m, - type - bond_length """ n, m = self.getChirality() type = self.getType() bond_length = self.getBondLength() self.maxlen = maxlen = 1.2 * bond_length self.maxlensq = maxlen**2 x = (n + 0.5 * m) * sqrt3 y = 1.5 * m angle = atan2(y, x) twoPiRoverA = (x**2 + y**2) ** .5 AoverR = (2 * pi) / twoPiRoverA self.__cos = cos(angle) self.__sin = sin(angle) # time to get the constants s, t = self.x1y1(0,0) u, v = self.x1y1(1./3, 1./3) w, x = self.x1y1(0,1) F = (t - v)**2 G = 2 * (1 - cos(AoverR * (s - u))) H = (v - x)**2 J = 2 * (1 - cos(AoverR * (u - w))) denom = F * J - G * H self.R = (bond_length**2 * (F - H) / denom) ** .5 self.B = (bond_length**2 * (J - G) / denom) ** .5 self.A = self.R * AoverR if 0: print "--------------" print "angle =", angle print "A =", self.A print "B =", self.B print "R =", self.R
[ "def", "_update", "(", "self", ")", ":", "n", ",", "m", "=", "self", ".", "getChirality", "(", ")", "type", "=", "self", ".", "getType", "(", ")", "bond_length", "=", "self", ".", "getBondLength", "(", ")", "self", ".", "maxlen", "=", "maxlen", "="...
https://github.com/kanzure/nanoengineer/blob/874e4c9f8a9190f093625b267f9767e19f82e6c4/cad/src/outtakes/Peptide.py#L71-L113
Qiskit/qiskit-terra
b66030e3b9192efdd3eb95cf25c6545fe0a13da4
qiskit/algorithms/phase_estimators/phase_estimation.py
python
PhaseEstimation.estimate_from_pe_circuit
( self, pe_circuit: QuantumCircuit, num_unitary_qubits: int )
return PhaseEstimationResult( self._num_evaluation_qubits, circuit_result=circuit_result, phases=phases )
Run the the phase estimation algorithm on a phase estimation circuit Args: pe_circuit: The phase estimation circuit. num_unitary_qubits: Must agree with the number of qubits in the unitary in `pe_circuit`. Returns: An instance of qiskit.algorithms.phase_estimator_result.PhaseEstimationResult.
Run the the phase estimation algorithm on a phase estimation circuit
[ "Run", "the", "the", "phase", "estimation", "algorithm", "on", "a", "phase", "estimation", "circuit" ]
def estimate_from_pe_circuit( self, pe_circuit: QuantumCircuit, num_unitary_qubits: int ) -> PhaseEstimationResult: """Run the the phase estimation algorithm on a phase estimation circuit Args: pe_circuit: The phase estimation circuit. num_unitary_qubits: Must agree with the number of qubits in the unitary in `pe_circuit`. Returns: An instance of qiskit.algorithms.phase_estimator_result.PhaseEstimationResult. """ self._add_measurement_if_required(pe_circuit) circuit_result = self._quantum_instance.execute(pe_circuit) phases = self._compute_phases(num_unitary_qubits, circuit_result) return PhaseEstimationResult( self._num_evaluation_qubits, circuit_result=circuit_result, phases=phases )
[ "def", "estimate_from_pe_circuit", "(", "self", ",", "pe_circuit", ":", "QuantumCircuit", ",", "num_unitary_qubits", ":", "int", ")", "->", "PhaseEstimationResult", ":", "self", ".", "_add_measurement_if_required", "(", "pe_circuit", ")", "circuit_result", "=", "self"...
https://github.com/Qiskit/qiskit-terra/blob/b66030e3b9192efdd3eb95cf25c6545fe0a13da4/qiskit/algorithms/phase_estimators/phase_estimation.py#L188-L205
joblib/joblib
7742f5882273889f7aaf1d483a8a1c72a97d57e3
joblib/numpy_pickle.py
python
dump
(value, filename, compress=0, protocol=None, cache_size=None)
return [filename]
Persist an arbitrary Python object into one file. Read more in the :ref:`User Guide <persistence>`. Parameters ----------- value: any Python object The object to store to disk. filename: str, pathlib.Path, or file object. The file object or path of the file in which it is to be stored. The compression method corresponding to one of the supported filename extensions ('.z', '.gz', '.bz2', '.xz' or '.lzma') will be used automatically. compress: int from 0 to 9 or bool or 2-tuple, optional Optional compression level for the data. 0 or False is no compression. Higher value means more compression, but also slower read and write times. Using a value of 3 is often a good compromise. See the notes for more details. If compress is True, the compression level used is 3. If compress is a 2-tuple, the first element must correspond to a string between supported compressors (e.g 'zlib', 'gzip', 'bz2', 'lzma' 'xz'), the second element must be an integer from 0 to 9, corresponding to the compression level. protocol: int, optional Pickle protocol, see pickle.dump documentation for more details. cache_size: positive int, optional This option is deprecated in 0.10 and has no effect. Returns ------- filenames: list of strings The list of file names in which the data is stored. If compress is false, each array is stored in a different file. See Also -------- joblib.load : corresponding loader Notes ----- Memmapping on load cannot be used for compressed files. Thus using compression can significantly slow down loading. In addition, compressed files take extra extra memory during dump and load.
Persist an arbitrary Python object into one file.
[ "Persist", "an", "arbitrary", "Python", "object", "into", "one", "file", "." ]
def dump(value, filename, compress=0, protocol=None, cache_size=None): """Persist an arbitrary Python object into one file. Read more in the :ref:`User Guide <persistence>`. Parameters ----------- value: any Python object The object to store to disk. filename: str, pathlib.Path, or file object. The file object or path of the file in which it is to be stored. The compression method corresponding to one of the supported filename extensions ('.z', '.gz', '.bz2', '.xz' or '.lzma') will be used automatically. compress: int from 0 to 9 or bool or 2-tuple, optional Optional compression level for the data. 0 or False is no compression. Higher value means more compression, but also slower read and write times. Using a value of 3 is often a good compromise. See the notes for more details. If compress is True, the compression level used is 3. If compress is a 2-tuple, the first element must correspond to a string between supported compressors (e.g 'zlib', 'gzip', 'bz2', 'lzma' 'xz'), the second element must be an integer from 0 to 9, corresponding to the compression level. protocol: int, optional Pickle protocol, see pickle.dump documentation for more details. cache_size: positive int, optional This option is deprecated in 0.10 and has no effect. Returns ------- filenames: list of strings The list of file names in which the data is stored. If compress is false, each array is stored in a different file. See Also -------- joblib.load : corresponding loader Notes ----- Memmapping on load cannot be used for compressed files. Thus using compression can significantly slow down loading. In addition, compressed files take extra extra memory during dump and load. """ if Path is not None and isinstance(filename, Path): filename = str(filename) is_filename = isinstance(filename, str) is_fileobj = hasattr(filename, "write") compress_method = 'zlib' # zlib is the default compression method. if compress is True: # By default, if compress is enabled, we want the default compress # level of the compressor. compress_level = None elif isinstance(compress, tuple): # a 2-tuple was set in compress if len(compress) != 2: raise ValueError( 'Compress argument tuple should contain exactly 2 elements: ' '(compress method, compress level), you passed {}' .format(compress)) compress_method, compress_level = compress elif isinstance(compress, str): compress_method = compress compress_level = None # Use default compress level compress = (compress_method, compress_level) else: compress_level = compress if compress_method == 'lz4' and lz4 is None: raise ValueError(LZ4_NOT_INSTALLED_ERROR) if (compress_level is not None and compress_level is not False and compress_level not in range(10)): # Raising an error if a non valid compress level is given. raise ValueError( 'Non valid compress level given: "{}". Possible values are ' '{}.'.format(compress_level, list(range(10)))) if compress_method not in _COMPRESSORS: # Raising an error if an unsupported compression method is given. raise ValueError( 'Non valid compression method given: "{}". Possible values are ' '{}.'.format(compress_method, _COMPRESSORS)) if not is_filename and not is_fileobj: # People keep inverting arguments, and the resulting error is # incomprehensible raise ValueError( 'Second argument should be a filename or a file-like object, ' '%s (type %s) was given.' % (filename, type(filename)) ) if is_filename and not isinstance(compress, tuple): # In case no explicit compression was requested using both compression # method and level in a tuple and the filename has an explicit # extension, we select the corresponding compressor. # unset the variable to be sure no compression level is set afterwards. compress_method = None for name, compressor in _COMPRESSORS.items(): if filename.endswith(compressor.extension): compress_method = name if compress_method in _COMPRESSORS and compress_level == 0: # we choose the default compress_level in case it was not given # as an argument (using compress). compress_level = None if cache_size is not None: # Cache size is deprecated starting from version 0.10 warnings.warn("Please do not set 'cache_size' in joblib.dump, " "this parameter has no effect and will be removed. " "You used 'cache_size={}'".format(cache_size), DeprecationWarning, stacklevel=2) if compress_level != 0: with _write_fileobject(filename, compress=(compress_method, compress_level)) as f: NumpyPickler(f, protocol=protocol).dump(value) elif is_filename: with open(filename, 'wb') as f: NumpyPickler(f, protocol=protocol).dump(value) else: NumpyPickler(filename, protocol=protocol).dump(value) # If the target container is a file object, nothing is returned. if is_fileobj: return # For compatibility, the list of created filenames (e.g with one element # after 0.10.0) is returned by default. return [filename]
[ "def", "dump", "(", "value", ",", "filename", ",", "compress", "=", "0", ",", "protocol", "=", "None", ",", "cache_size", "=", "None", ")", ":", "if", "Path", "is", "not", "None", "and", "isinstance", "(", "filename", ",", "Path", ")", ":", "filename...
https://github.com/joblib/joblib/blob/7742f5882273889f7aaf1d483a8a1c72a97d57e3/joblib/numpy_pickle.py#L353-L492
google/prettytensor
75daa0b11252590f548da5647addc0ea610c4c45
prettytensor/layers.py
python
apply_activation
( books, x, activation, activation_args=(), activation_kwargs=None)
return y
Returns activation(x, *activation_args, **activation_kwargs). This applies the given activation and adds useful summaries specific to the activation. Args: books: The bookkeeper. x: The tensor to apply activation to. activation: An activation function. activation_args: Optional additional arguments for the activation. activation_kwargs: Optional keyword args for activation. Returns: A tensor with activation applied to x.
Returns activation(x, *activation_args, **activation_kwargs).
[ "Returns", "activation", "(", "x", "*", "activation_args", "**", "activation_kwargs", ")", "." ]
def apply_activation( books, x, activation, activation_args=(), activation_kwargs=None): """Returns activation(x, *activation_args, **activation_kwargs). This applies the given activation and adds useful summaries specific to the activation. Args: books: The bookkeeper. x: The tensor to apply activation to. activation: An activation function. activation_args: Optional additional arguments for the activation. activation_kwargs: Optional keyword args for activation. Returns: A tensor with activation applied to x. """ if activation is None: return x if activation_kwargs is None: activation_kwargs = {} y = activation(x, *activation_args, **activation_kwargs) if activation in (tf.nn.relu, functions.leaky_relu, functions.softplus): books.add_scalar_summary( tf.reduce_mean(tf.cast(tf.less(x, 0.0), tf.float32)), '%s/zeros' % y.op.name) elif activation is tf.nn.relu6: books.add_scalar_summary( tf.reduce_mean(tf.cast(tf.less(x, 0.0), tf.float32)), '%s/zeros' % y.op.name) books.add_scalar_summary( tf.reduce_mean(tf.cast(tf.greater(x, 6.0), tf.float32)), '%s/sixes' % y.op.name) elif activation in (functions.l2_normalize, tf.nn.l2_normalize, functions.l1_normalize): books.add_scalar_summary( tf.reduce_mean(tf.sqrt(tf.reduce_sum( tf.square(x), 1))), '%s/length' % y.op.name) return y
[ "def", "apply_activation", "(", "books", ",", "x", ",", "activation", ",", "activation_args", "=", "(", ")", ",", "activation_kwargs", "=", "None", ")", ":", "if", "activation", "is", "None", ":", "return", "x", "if", "activation_kwargs", "is", "None", ":"...
https://github.com/google/prettytensor/blob/75daa0b11252590f548da5647addc0ea610c4c45/prettytensor/layers.py#L31-L72