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
securesystemslab/zippy
ff0e84ac99442c2c55fe1d285332cfd4e185e089
zippy/lib-python/3/site.py
python
_Helper.__call__
(self, *args, **kwds)
return pydoc.help(*args, **kwds)
[]
def __call__(self, *args, **kwds): import pydoc return pydoc.help(*args, **kwds)
[ "def", "__call__", "(", "self", ",", "*", "args", ",", "*", "*", "kwds", ")", ":", "import", "pydoc", "return", "pydoc", ".", "help", "(", "*", "args", ",", "*", "*", "kwds", ")" ]
https://github.com/securesystemslab/zippy/blob/ff0e84ac99442c2c55fe1d285332cfd4e185e089/zippy/lib-python/3/site.py#L455-L457
WerWolv/EdiZon_CheatsConfigsAndScripts
d16d36c7509c01dca770f402babd83ff2e9ae6e7
Scripts/lib/python3.5/pydoc.py
python
cram
(text, maxlen)
return text
Omit part of a string if needed to make it fit in a maximum length.
Omit part of a string if needed to make it fit in a maximum length.
[ "Omit", "part", "of", "a", "string", "if", "needed", "to", "make", "it", "fit", "in", "a", "maximum", "length", "." ]
def cram(text, maxlen): """Omit part of a string if needed to make it fit in a maximum length.""" if len(text) > maxlen: pre = max(0, (maxlen-3)//2) post = max(0, maxlen-3-pre) return text[:pre] + '...' + text[len(text)-post:] return text
[ "def", "cram", "(", "text", ",", "maxlen", ")", ":", "if", "len", "(", "text", ")", ">", "maxlen", ":", "pre", "=", "max", "(", "0", ",", "(", "maxlen", "-", "3", ")", "//", "2", ")", "post", "=", "max", "(", "0", ",", "maxlen", "-", "3", ...
https://github.com/WerWolv/EdiZon_CheatsConfigsAndScripts/blob/d16d36c7509c01dca770f402babd83ff2e9ae6e7/Scripts/lib/python3.5/pydoc.py#L123-L129
ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework
cb692f527e4e819b6c228187c5702d990a180043
bin/x86/Debug/scripting_engine/Lib/pydoc.py
python
HTMLDoc.docdata
(self, object, name=None, mod=None, cl=None)
return self._docdescriptor(name, object, mod)
Produce html documentation for a data descriptor.
Produce html documentation for a data descriptor.
[ "Produce", "html", "documentation", "for", "a", "data", "descriptor", "." ]
def docdata(self, object, name=None, mod=None, cl=None): """Produce html documentation for a data descriptor.""" return self._docdescriptor(name, object, mod)
[ "def", "docdata", "(", "self", ",", "object", ",", "name", "=", "None", ",", "mod", "=", "None", ",", "cl", "=", "None", ")", ":", "return", "self", ".", "_docdescriptor", "(", "name", ",", "object", ",", "mod", ")" ]
https://github.com/ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework/blob/cb692f527e4e819b6c228187c5702d990a180043/bin/x86/Debug/scripting_engine/Lib/pydoc.py#L927-L929
tomplus/kubernetes_asyncio
f028cc793e3a2c519be6a52a49fb77ff0b014c9b
kubernetes_asyncio/client/api/custom_objects_api.py
python
CustomObjectsApi.patch_namespaced_custom_object_status
(self, group, version, namespace, plural, name, body, **kwargs)
return self.patch_namespaced_custom_object_status_with_http_info(group, version, namespace, plural, name, body, **kwargs)
patch_namespaced_custom_object_status # noqa: E501 partially update status of the specified namespace scoped custom object # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.patch_namespaced_custom_object_status(group, version, namespace, plural, name, body, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str group: the custom resource's group (required) :param str version: the custom resource's version (required) :param str namespace: The custom resource's namespace (required) :param str plural: the custom resource's plural name. For TPRs this would be lowercase plural kind. (required) :param str name: the custom object's name (required) :param object body: (required) :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch). :param bool force: Force is going to \"force\" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests. :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread.
patch_namespaced_custom_object_status # noqa: E501
[ "patch_namespaced_custom_object_status", "#", "noqa", ":", "E501" ]
def patch_namespaced_custom_object_status(self, group, version, namespace, plural, name, body, **kwargs): # noqa: E501 """patch_namespaced_custom_object_status # noqa: E501 partially update status of the specified namespace scoped custom object # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.patch_namespaced_custom_object_status(group, version, namespace, plural, name, body, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str group: the custom resource's group (required) :param str version: the custom resource's version (required) :param str namespace: The custom resource's namespace (required) :param str plural: the custom resource's plural name. For TPRs this would be lowercase plural kind. (required) :param str name: the custom object's name (required) :param object body: (required) :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch). :param bool force: Force is going to \"force\" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests. :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True return self.patch_namespaced_custom_object_status_with_http_info(group, version, namespace, plural, name, body, **kwargs)
[ "def", "patch_namespaced_custom_object_status", "(", "self", ",", "group", ",", "version", ",", "namespace", ",", "plural", ",", "name", ",", "body", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True"...
https://github.com/tomplus/kubernetes_asyncio/blob/f028cc793e3a2c519be6a52a49fb77ff0b014c9b/kubernetes_asyncio/client/api/custom_objects_api.py#L3143-L3174
linxid/Machine_Learning_Study_Path
558e82d13237114bbb8152483977806fc0c222af
Machine Learning In Action/Chapter5-LogisticRegression/venv/Lib/codecs.py
python
StreamWriter.seek
(self, offset, whence=0)
[]
def seek(self, offset, whence=0): self.stream.seek(offset, whence) if whence == 0 and offset == 0: self.reset()
[ "def", "seek", "(", "self", ",", "offset", ",", "whence", "=", "0", ")", ":", "self", ".", "stream", ".", "seek", "(", "offset", ",", "whence", ")", "if", "whence", "==", "0", "and", "offset", "==", "0", ":", "self", ".", "reset", "(", ")" ]
https://github.com/linxid/Machine_Learning_Study_Path/blob/558e82d13237114bbb8152483977806fc0c222af/Machine Learning In Action/Chapter5-LogisticRegression/venv/Lib/codecs.py#L398-L401
BoyuanJiang/matching-networks-pytorch
3f7bc55ce531143004cc4bc6138a3485d4886794
matching_networks.py
python
BidirectionalLSTM.__init__
(self, layer_size, batch_size, vector_dim,use_cuda)
Initial a muti-layer Bidirectional LSTM :param layer_size: a list of each layer'size :param batch_size: :param vector_dim:
Initial a muti-layer Bidirectional LSTM :param layer_size: a list of each layer'size :param batch_size: :param vector_dim:
[ "Initial", "a", "muti", "-", "layer", "Bidirectional", "LSTM", ":", "param", "layer_size", ":", "a", "list", "of", "each", "layer", "size", ":", "param", "batch_size", ":", ":", "param", "vector_dim", ":" ]
def __init__(self, layer_size, batch_size, vector_dim,use_cuda): super(BidirectionalLSTM, self).__init__() """ Initial a muti-layer Bidirectional LSTM :param layer_size: a list of each layer'size :param batch_size: :param vector_dim: """ self.batch_size = batch_size self.hidden_size = layer_size[0] self.vector_dim = vector_dim self.num_layer = len(layer_size) self.use_cuda = use_cuda self.lstm = nn.LSTM(input_size=self.vector_dim, num_layers=self.num_layer, hidden_size=self.hidden_size, bidirectional=True) self.hidden = self.init_hidden(self.use_cuda)
[ "def", "__init__", "(", "self", ",", "layer_size", ",", "batch_size", ",", "vector_dim", ",", "use_cuda", ")", ":", "super", "(", "BidirectionalLSTM", ",", "self", ")", ".", "__init__", "(", ")", "self", ".", "batch_size", "=", "batch_size", "self", ".", ...
https://github.com/BoyuanJiang/matching-networks-pytorch/blob/3f7bc55ce531143004cc4bc6138a3485d4886794/matching_networks.py#L108-L123
demisto/content
5c664a65b992ac8ca90ac3f11b1b2cdf11ee9b07
Packs/Axonius/Integrations/Axonius/Axonius.py
python
parse_asset
(asset: dict)
return { parse_key(key=k): parse_kv(key=k, value=v) for k, v in asset.items() if k not in SKIPS }
Initiate field format correction on assets.
Initiate field format correction on assets.
[ "Initiate", "field", "format", "correction", "on", "assets", "." ]
def parse_asset(asset: dict) -> dict: """Initiate field format correction on assets.""" return { parse_key(key=k): parse_kv(key=k, value=v) for k, v in asset.items() if k not in SKIPS }
[ "def", "parse_asset", "(", "asset", ":", "dict", ")", "->", "dict", ":", "return", "{", "parse_key", "(", "key", "=", "k", ")", ":", "parse_kv", "(", "key", "=", "k", ",", "value", "=", "v", ")", "for", "k", ",", "v", "in", "asset", ".", "items...
https://github.com/demisto/content/blob/5c664a65b992ac8ca90ac3f11b1b2cdf11ee9b07/Packs/Axonius/Integrations/Axonius/Axonius.py#L81-L87
1012598167/flask_mongodb_game
60c7e0351586656ec38f851592886338e50b4110
python_flask/venv/Lib/site-packages/pip-19.0.3-py3.6.egg/pip/_vendor/urllib3/util/ssl_.py
python
_const_compare_digest_backport
(a, b)
return result == 0
Compare two digests of equal length in constant time. The digests must be of type str/bytes. Returns True if the digests match, and False otherwise.
Compare two digests of equal length in constant time.
[ "Compare", "two", "digests", "of", "equal", "length", "in", "constant", "time", "." ]
def _const_compare_digest_backport(a, b): """ Compare two digests of equal length in constant time. The digests must be of type str/bytes. Returns True if the digests match, and False otherwise. """ result = abs(len(a) - len(b)) for l, r in zip(bytearray(a), bytearray(b)): result |= l ^ r return result == 0
[ "def", "_const_compare_digest_backport", "(", "a", ",", "b", ")", ":", "result", "=", "abs", "(", "len", "(", "a", ")", "-", "len", "(", "b", ")", ")", "for", "l", ",", "r", "in", "zip", "(", "bytearray", "(", "a", ")", ",", "bytearray", "(", "...
https://github.com/1012598167/flask_mongodb_game/blob/60c7e0351586656ec38f851592886338e50b4110/python_flask/venv/Lib/site-packages/pip-19.0.3-py3.6.egg/pip/_vendor/urllib3/util/ssl_.py#L27-L37
aws-samples/aws-kube-codesuite
ab4e5ce45416b83bffb947ab8d234df5437f4fca
src/kubernetes/client/models/v1alpha1_admission_hook_client_config.py
python
V1alpha1AdmissionHookClientConfig.__init__
(self, ca_bundle=None, service=None)
V1alpha1AdmissionHookClientConfig - a model defined in Swagger :param dict swaggerTypes: The key is attribute name and the value is attribute type. :param dict attributeMap: The key is attribute name and the value is json key in definition.
V1alpha1AdmissionHookClientConfig - a model defined in Swagger
[ "V1alpha1AdmissionHookClientConfig", "-", "a", "model", "defined", "in", "Swagger" ]
def __init__(self, ca_bundle=None, service=None): """ V1alpha1AdmissionHookClientConfig - a model defined in Swagger :param dict swaggerTypes: The key is attribute name and the value is attribute type. :param dict attributeMap: The key is attribute name and the value is json key in definition. """ self.swagger_types = { 'ca_bundle': 'str', 'service': 'V1alpha1ServiceReference' } self.attribute_map = { 'ca_bundle': 'caBundle', 'service': 'service' } self._ca_bundle = ca_bundle self._service = service
[ "def", "__init__", "(", "self", ",", "ca_bundle", "=", "None", ",", "service", "=", "None", ")", ":", "self", ".", "swagger_types", "=", "{", "'ca_bundle'", ":", "'str'", ",", "'service'", ":", "'V1alpha1ServiceReference'", "}", "self", ".", "attribute_map",...
https://github.com/aws-samples/aws-kube-codesuite/blob/ab4e5ce45416b83bffb947ab8d234df5437f4fca/src/kubernetes/client/models/v1alpha1_admission_hook_client_config.py#L24-L44
dimagi/commcare-hq
d67ff1d3b4c51fa050c19e60c3253a79d3452a39
corehq/apps/userreports/pillow.py
python
get_kafka_ucr_registry_pillow
( pillow_id='kafka-ucr-registry', num_processes=1, process_num=0, dedicated_migration_process=False, processor_chunk_size=DEFAULT_PROCESSOR_CHUNK_SIZE, ucr_configs=None, **kwargs)
return ConfigurableReportKafkaPillow( processor=ucr_processor, pillow_name=pillow_id, topics=CASE_TOPICS, num_processes=num_processes, process_num=process_num, is_dedicated_migration_process=dedicated_migration_process and (process_num == 0), processor_chunk_size=processor_chunk_size, )
UCR pillow that reads from all 'case' Kafka topics and writes data into the UCR database tables Only UCRs backed by Data Registries are processed in this pillow. Processors: - :py:class:`corehq.apps.userreports.pillow.ConfigurableReportPillowProcessor`
UCR pillow that reads from all 'case' Kafka topics and writes data into the UCR database tables
[ "UCR", "pillow", "that", "reads", "from", "all", "case", "Kafka", "topics", "and", "writes", "data", "into", "the", "UCR", "database", "tables" ]
def get_kafka_ucr_registry_pillow( pillow_id='kafka-ucr-registry', num_processes=1, process_num=0, dedicated_migration_process=False, processor_chunk_size=DEFAULT_PROCESSOR_CHUNK_SIZE, ucr_configs=None, **kwargs): """UCR pillow that reads from all 'case' Kafka topics and writes data into the UCR database tables Only UCRs backed by Data Registries are processed in this pillow. Processors: - :py:class:`corehq.apps.userreports.pillow.ConfigurableReportPillowProcessor` """ ucr_processor = get_data_registry_ucr_processor( run_migrations=(process_num == 0), # only first process runs migrations ucr_configs=ucr_configs ) return ConfigurableReportKafkaPillow( processor=ucr_processor, pillow_name=pillow_id, topics=CASE_TOPICS, num_processes=num_processes, process_num=process_num, is_dedicated_migration_process=dedicated_migration_process and (process_num == 0), processor_chunk_size=processor_chunk_size, )
[ "def", "get_kafka_ucr_registry_pillow", "(", "pillow_id", "=", "'kafka-ucr-registry'", ",", "num_processes", "=", "1", ",", "process_num", "=", "0", ",", "dedicated_migration_process", "=", "False", ",", "processor_chunk_size", "=", "DEFAULT_PROCESSOR_CHUNK_SIZE", ",", ...
https://github.com/dimagi/commcare-hq/blob/d67ff1d3b4c51fa050c19e60c3253a79d3452a39/corehq/apps/userreports/pillow.py#L746-L770
gem/oq-engine
1bdb88f3914e390abcbd285600bfd39477aae47c
openquake/hazardlib/gsim/atkinson_boore_2003.py
python
_compute_site_class_dummy_variables_2008
(kind, vs30)
return Sbc, Sc, Sd, Se
Extend :meth:`AtkinsonBoore2003SInter._compute_site_class_dummy_variables` and includes dummy variable for B/C site conditions (vs30 > 760.)
Extend :meth:`AtkinsonBoore2003SInter._compute_site_class_dummy_variables` and includes dummy variable for B/C site conditions (vs30 > 760.)
[ "Extend", ":", "meth", ":", "AtkinsonBoore2003SInter", ".", "_compute_site_class_dummy_variables", "and", "includes", "dummy", "variable", "for", "B", "/", "C", "site", "conditions", "(", "vs30", ">", "760", ".", ")" ]
def _compute_site_class_dummy_variables_2008(kind, vs30): """ Extend :meth:`AtkinsonBoore2003SInter._compute_site_class_dummy_variables` and includes dummy variable for B/C site conditions (vs30 > 760.) """ Sbc = np.zeros_like(vs30) Sc = np.zeros_like(vs30) Sd = np.zeros_like(vs30) Se = np.zeros_like(vs30) Sbc[vs30 > 760.] = 1 Sc[(vs30 > 360) & (vs30 <= 760)] = 1 Sd[(vs30 >= 180) & (vs30 <= 360)] = 1 Se[vs30 < 180] = 1 return Sbc, Sc, Sd, Se
[ "def", "_compute_site_class_dummy_variables_2008", "(", "kind", ",", "vs30", ")", ":", "Sbc", "=", "np", ".", "zeros_like", "(", "vs30", ")", "Sc", "=", "np", ".", "zeros_like", "(", "vs30", ")", "Sd", "=", "np", ".", "zeros_like", "(", "vs30", ")", "S...
https://github.com/gem/oq-engine/blob/1bdb88f3914e390abcbd285600bfd39477aae47c/openquake/hazardlib/gsim/atkinson_boore_2003.py#L86-L102
mcneel/rhinoscriptsyntax
c49bd0bf24c2513bdcb84d1bf307144489600fd9
Scripts/rhinoscript/surface.py
python
AddLoftSrf
(object_ids, start=None, end=None, loft_type=0, simplify_method=0, value=0, closed=False)
return idlist
Adds a surface created by lofting curves to the document. - no curve sorting performed. pass in curves in the order you want them sorted - directions of open curves not adjusted. Use CurveDirectionsMatch and ReverseCurve to adjust the directions of open curves - seams of closed curves are not adjusted. Use CurveSeam to adjust the seam of closed curves Parameters: object_ids ({guid, guid, ...]): ordered list of the curves to loft through start (point, optional): starting point of the loft end (point, optional): ending point of the loft loft_type (number, optional): type of loft. Possible options are: 0 = Normal. Uses chord-length parameterization in the loft direction 1 = Loose. The surface is allowed to move away from the original curves to make a smoother surface. The surface control points are created at the same locations as the control points of the loft input curves. 2 = Straight. The sections between the curves are straight. This is also known as a ruled surface. 3 = Tight. The surface sticks closely to the original curves. Uses square root of chord-length parameterization in the loft direction 4 = Developable. Creates a separate developable surface or polysurface from each pair of curves. simplify_method (number, optional): Possible options are: 0 = None. Does not simplify. 1 = Rebuild. Rebuilds the shape curves before lofting. modified by `value` below 2 = Refit. Refits the shape curves to a specified tolerance. modified by `value` below value (number, optional): Additional value based on the specified `simplify_method`: Simplify - Description Rebuild(1) - then value is the number of control point used to rebuild Rebuild(1) - is specified and this argument is omitted, then curves will be rebuilt using 10 control points. Refit(2) - then value is the tolerance used to rebuild. Refit(2) - is specified and this argument is omitted, then the document's absolute tolerance us used for refitting. closed (bool, optional): close the loft back to the first curve Returns: list(guid, ...):Array containing the identifiers of the new surface objects if successful None: on error Example: import rhinoscriptsyntax as rs objs = rs.GetObjects("Pick curves to loft", rs.filter.curve) if objs: rs.AddLoftSrf(objs) See Also: CurveDirectionsMatch CurveSeam ReverseCurve
Adds a surface created by lofting curves to the document. - no curve sorting performed. pass in curves in the order you want them sorted - directions of open curves not adjusted. Use CurveDirectionsMatch and ReverseCurve to adjust the directions of open curves - seams of closed curves are not adjusted. Use CurveSeam to adjust the seam of closed curves Parameters: object_ids ({guid, guid, ...]): ordered list of the curves to loft through start (point, optional): starting point of the loft end (point, optional): ending point of the loft loft_type (number, optional): type of loft. Possible options are: 0 = Normal. Uses chord-length parameterization in the loft direction 1 = Loose. The surface is allowed to move away from the original curves to make a smoother surface. The surface control points are created at the same locations as the control points of the loft input curves. 2 = Straight. The sections between the curves are straight. This is also known as a ruled surface. 3 = Tight. The surface sticks closely to the original curves. Uses square root of chord-length parameterization in the loft direction 4 = Developable. Creates a separate developable surface or polysurface from each pair of curves. simplify_method (number, optional): Possible options are: 0 = None. Does not simplify. 1 = Rebuild. Rebuilds the shape curves before lofting. modified by `value` below 2 = Refit. Refits the shape curves to a specified tolerance. modified by `value` below value (number, optional): Additional value based on the specified `simplify_method`: Simplify - Description Rebuild(1) - then value is the number of control point used to rebuild Rebuild(1) - is specified and this argument is omitted, then curves will be rebuilt using 10 control points. Refit(2) - then value is the tolerance used to rebuild. Refit(2) - is specified and this argument is omitted, then the document's absolute tolerance us used for refitting. closed (bool, optional): close the loft back to the first curve Returns: list(guid, ...):Array containing the identifiers of the new surface objects if successful None: on error Example: import rhinoscriptsyntax as rs objs = rs.GetObjects("Pick curves to loft", rs.filter.curve) if objs: rs.AddLoftSrf(objs) See Also: CurveDirectionsMatch CurveSeam ReverseCurve
[ "Adds", "a", "surface", "created", "by", "lofting", "curves", "to", "the", "document", ".", "-", "no", "curve", "sorting", "performed", ".", "pass", "in", "curves", "in", "the", "order", "you", "want", "them", "sorted", "-", "directions", "of", "open", "...
def AddLoftSrf(object_ids, start=None, end=None, loft_type=0, simplify_method=0, value=0, closed=False): """Adds a surface created by lofting curves to the document. - no curve sorting performed. pass in curves in the order you want them sorted - directions of open curves not adjusted. Use CurveDirectionsMatch and ReverseCurve to adjust the directions of open curves - seams of closed curves are not adjusted. Use CurveSeam to adjust the seam of closed curves Parameters: object_ids ({guid, guid, ...]): ordered list of the curves to loft through start (point, optional): starting point of the loft end (point, optional): ending point of the loft loft_type (number, optional): type of loft. Possible options are: 0 = Normal. Uses chord-length parameterization in the loft direction 1 = Loose. The surface is allowed to move away from the original curves to make a smoother surface. The surface control points are created at the same locations as the control points of the loft input curves. 2 = Straight. The sections between the curves are straight. This is also known as a ruled surface. 3 = Tight. The surface sticks closely to the original curves. Uses square root of chord-length parameterization in the loft direction 4 = Developable. Creates a separate developable surface or polysurface from each pair of curves. simplify_method (number, optional): Possible options are: 0 = None. Does not simplify. 1 = Rebuild. Rebuilds the shape curves before lofting. modified by `value` below 2 = Refit. Refits the shape curves to a specified tolerance. modified by `value` below value (number, optional): Additional value based on the specified `simplify_method`: Simplify - Description Rebuild(1) - then value is the number of control point used to rebuild Rebuild(1) - is specified and this argument is omitted, then curves will be rebuilt using 10 control points. Refit(2) - then value is the tolerance used to rebuild. Refit(2) - is specified and this argument is omitted, then the document's absolute tolerance us used for refitting. closed (bool, optional): close the loft back to the first curve Returns: list(guid, ...):Array containing the identifiers of the new surface objects if successful None: on error Example: import rhinoscriptsyntax as rs objs = rs.GetObjects("Pick curves to loft", rs.filter.curve) if objs: rs.AddLoftSrf(objs) See Also: CurveDirectionsMatch CurveSeam ReverseCurve """ if loft_type<0 or loft_type>5: raise ValueError("loft_type must be 0-4") if simplify_method<0 or simplify_method>2: raise ValueError("simplify_method must be 0-2") # get set of curves from object_ids curves = [rhutil.coercecurve(id,-1,True) for id in object_ids] if len(curves)<2: return scriptcontext.errorhandler() if start is None: start = Rhino.Geometry.Point3d.Unset if end is None: end = Rhino.Geometry.Point3d.Unset start = rhutil.coerce3dpoint(start, True) end = rhutil.coerce3dpoint(end, True) lt = Rhino.Geometry.LoftType.Normal if loft_type==1: lt = Rhino.Geometry.LoftType.Loose elif loft_type==2: lt = Rhino.Geometry.LoftType.Straight elif loft_type==3: lt = Rhino.Geometry.LoftType.Tight elif loft_type==4: lt = Rhino.Geometry.LoftType.Developable breps = None if simplify_method==0: breps = Rhino.Geometry.Brep.CreateFromLoft(curves, start, end, lt, closed) elif simplify_method==1: value = abs(value) rebuild_count = int(value) breps = Rhino.Geometry.Brep.CreateFromLoftRebuild(curves, start, end, lt, closed, rebuild_count) elif simplify_method==2: refit = abs(value) if refit==0: refit = scriptcontext.doc.ModelAbsoluteTolerance breps = Rhino.Geometry.Brep.CreateFromLoftRefit(curves, start, end, lt, closed, refit) if not breps: return scriptcontext.errorhandler() idlist = [] for brep in breps: id = scriptcontext.doc.Objects.AddBrep(brep) if id!=System.Guid.Empty: idlist.append(id) if idlist: scriptcontext.doc.Views.Redraw() return idlist
[ "def", "AddLoftSrf", "(", "object_ids", ",", "start", "=", "None", ",", "end", "=", "None", ",", "loft_type", "=", "0", ",", "simplify_method", "=", "0", ",", "value", "=", "0", ",", "closed", "=", "False", ")", ":", "if", "loft_type", "<", "0", "o...
https://github.com/mcneel/rhinoscriptsyntax/blob/c49bd0bf24c2513bdcb84d1bf307144489600fd9/Scripts/rhinoscript/surface.py#L439-L521
keras-team/keras
5caa668b6a415675064a730f5eb46ecc08e40f65
keras/engine/functional.py
python
ModuleWrapper.__init__
(self, module, method_name=None, **kwargs)
Initializes the wrapper Layer for this module. Args: module: The `tf.Module` instance to be wrapped. method_name: (Optional) str. The name of the method to use as the forward pass of the module. If not set, defaults to '__call__' if defined, or 'call'. **kwargs: Additional keywrod arguments. See `tf.keras.layers.Layer`. Raises: ValueError: If `method` is not defined on `module`.
Initializes the wrapper Layer for this module.
[ "Initializes", "the", "wrapper", "Layer", "for", "this", "module", "." ]
def __init__(self, module, method_name=None, **kwargs): """Initializes the wrapper Layer for this module. Args: module: The `tf.Module` instance to be wrapped. method_name: (Optional) str. The name of the method to use as the forward pass of the module. If not set, defaults to '__call__' if defined, or 'call'. **kwargs: Additional keywrod arguments. See `tf.keras.layers.Layer`. Raises: ValueError: If `method` is not defined on `module`. """ super(ModuleWrapper, self).__init__(**kwargs) if method_name is None: if hasattr(module, '__call__'): method_name = '__call__' elif hasattr(module, 'call'): method_name = 'call' if method_name is None or not hasattr(module, method_name): raise ValueError('{} is not defined on object {}'.format( method_name, module)) self._module = module self._method_name = method_name # Check if module.__call__ has a `training` arg or accepts `**kwargs`. method = getattr(module, method_name) method_arg_spec = tf_inspect.getfullargspec(method) self._expects_training_arg = ('training' in method_arg_spec.args or method_arg_spec.varkw is not None) self._expects_mask_arg = ('mask' in method_arg_spec.args or method_arg_spec.varkw is not None)
[ "def", "__init__", "(", "self", ",", "module", ",", "method_name", "=", "None", ",", "*", "*", "kwargs", ")", ":", "super", "(", "ModuleWrapper", ",", "self", ")", ".", "__init__", "(", "*", "*", "kwargs", ")", "if", "method_name", "is", "None", ":",...
https://github.com/keras-team/keras/blob/5caa668b6a415675064a730f5eb46ecc08e40f65/keras/engine/functional.py#L1461-L1493
boston-dynamics/spot-sdk
5ffa12e6943a47323c7279d86e30346868755f52
python/bosdyn-client/src/bosdyn/client/math_helpers.py
python
SE3Velocity.angular
(self)
return geometry_pb2.Vec3(x=self.angular_velocity_x, y=self.angular_velocity_y, z=self.angular_velocity_z)
Property to allow attribute access of the protobuf message field 'angular' similar to the geometry_pb2.SE3Velocity for the math_helper.SE3Velocity.
Property to allow attribute access of the protobuf message field 'angular' similar to the geometry_pb2.SE3Velocity for the math_helper.SE3Velocity.
[ "Property", "to", "allow", "attribute", "access", "of", "the", "protobuf", "message", "field", "angular", "similar", "to", "the", "geometry_pb2", ".", "SE3Velocity", "for", "the", "math_helper", ".", "SE3Velocity", "." ]
def angular(self): """Property to allow attribute access of the protobuf message field 'angular' similar to the geometry_pb2.SE3Velocity for the math_helper.SE3Velocity.""" return geometry_pb2.Vec3(x=self.angular_velocity_x, y=self.angular_velocity_y, z=self.angular_velocity_z)
[ "def", "angular", "(", "self", ")", ":", "return", "geometry_pb2", ".", "Vec3", "(", "x", "=", "self", ".", "angular_velocity_x", ",", "y", "=", "self", ".", "angular_velocity_y", ",", "z", "=", "self", ".", "angular_velocity_z", ")" ]
https://github.com/boston-dynamics/spot-sdk/blob/5ffa12e6943a47323c7279d86e30346868755f52/python/bosdyn-client/src/bosdyn/client/math_helpers.py#L285-L289
reviewboard/reviewboard
7395902e4c181bcd1d633f61105012ffb1d18e1b
reviewboard/reviews/models/review_request_draft.py
python
ReviewRequestDraft.create
(review_request, changedesc=None)
return draft
Create a draft based on a review request. This will copy over all the details of the review request that we care about. If a draft already exists for the review request, the draft will be returned. Args: review_request (reviewboard.reviews.models.review_request. ReviewRequest): The review request to fetch or create the draft from. changedesc (reviewboard.changedescs.models.ChangeDescription): A custom change description to set on the draft. This will always be set, overriding any previous one if already set. Returns: ReviewRequestDraft: The resulting draft.
Create a draft based on a review request.
[ "Create", "a", "draft", "based", "on", "a", "review", "request", "." ]
def create(review_request, changedesc=None): """Create a draft based on a review request. This will copy over all the details of the review request that we care about. If a draft already exists for the review request, the draft will be returned. Args: review_request (reviewboard.reviews.models.review_request. ReviewRequest): The review request to fetch or create the draft from. changedesc (reviewboard.changedescs.models.ChangeDescription): A custom change description to set on the draft. This will always be set, overriding any previous one if already set. Returns: ReviewRequestDraft: The resulting draft. """ draft, draft_is_new = \ ReviewRequestDraft.objects.get_or_create( review_request=review_request, defaults={ 'changedesc': changedesc, 'extra_data': review_request.extra_data or {}, 'summary': review_request.summary, 'description': review_request.description, 'testing_done': review_request.testing_done, 'bugs_closed': review_request.bugs_closed, 'branch': review_request.branch, 'description_rich_text': review_request.description_rich_text, 'testing_done_rich_text': review_request.testing_done_rich_text, 'rich_text': review_request.rich_text, 'commit_id': review_request.commit_id, }) if (changedesc is None and draft.changedesc_id is None and review_request.public): changedesc = ChangeDescription.objects.create() if changedesc is not None and draft.changedesc_id != changedesc.pk: old_changedesc_id = draft.changedesc_id draft.changedesc = changedesc draft.save(update_fields=('changedesc',)) if old_changedesc_id is not None: ChangeDescription.objects.filter(pk=old_changedesc_id).delete() if draft_is_new: rels_to_update = [ ('depends_on', 'to_reviewrequest_id', 'from_reviewrequest_id'), ('target_groups', 'group_id', 'reviewrequest_id'), ('target_people', 'user_id', 'reviewrequest_id'), ] if review_request.screenshots_count > 0: review_request.screenshots.update(draft_caption=F('caption')) rels_to_update.append(('screenshots', 'screenshot_id', 'reviewrequest_id')) if review_request.inactive_screenshots_count > 0: review_request.inactive_screenshots.update( draft_caption=F('caption')) rels_to_update.append(('inactive_screenshots', 'screenshot_id', 'reviewrequest_id')) if review_request.file_attachments_count > 0: review_request.file_attachments.update( draft_caption=F('caption')) rels_to_update.append(('file_attachments', 'fileattachment_id', 'reviewrequest_id')) if review_request.inactive_file_attachments_count > 0: review_request.inactive_file_attachments.update( draft_caption=F('caption')) rels_to_update.append(('inactive_file_attachments', 'fileattachment_id', 'reviewrequest_id')) for rel_field, id_field, lookup_field, in rels_to_update: # We don't need to query the entirety of each object, and # we'd like to avoid any JOINs. So, we'll be using the # M2M 'through' tables to perform lookups of the related # models' IDs. items = list( getattr(review_request, rel_field).through.objects .filter(**{lookup_field: review_request.pk}) .values_list(id_field, flat=True) ) if items: # Note that we're using add() instead of directly # assigning the value. This lets us avoid a query that # Django would perform to determine if it needed to clear # out any existing values. Since we know this draft is # new, there's no point in doing that. getattr(draft, rel_field).add(*items) return draft
[ "def", "create", "(", "review_request", ",", "changedesc", "=", "None", ")", ":", "draft", ",", "draft_is_new", "=", "ReviewRequestDraft", ".", "objects", ".", "get_or_create", "(", "review_request", "=", "review_request", ",", "defaults", "=", "{", "'changedesc...
https://github.com/reviewboard/reviewboard/blob/7395902e4c181bcd1d633f61105012ffb1d18e1b/reviewboard/reviews/models/review_request_draft.py#L139-L241
hydroshare/hydroshare
7ba563b55412f283047fb3ef6da367d41dec58c6
hs_access_control/models/user.py
python
UserAccess.can_undo_share_community_with_user
(self, this_community, this_user)
return self.__get_community_undo_users(this_community).filter(id=this_user.id).exists()
Check that a user share can be undone :param this_user: shared user to check. :param this_community: with user to check. :returns: Boolean "undo_share" differs from "unshare" in that no special privilege is required to "undo" a share; all that is required is that one granted the privilege initially. Thus -- under freakish circumstances -- one can undo a share that one no longer has the privilege to grant. Usage: ------ c = some_community u = some_user if request_user.can_undo_share_community_with_user(c,u) request_user.undo_share_community_with_user(c,u)
Check that a user share can be undone
[ "Check", "that", "a", "user", "share", "can", "be", "undone" ]
def can_undo_share_community_with_user(self, this_community, this_user): """ Check that a user share can be undone :param this_user: shared user to check. :param this_community: with user to check. :returns: Boolean "undo_share" differs from "unshare" in that no special privilege is required to "undo" a share; all that is required is that one granted the privilege initially. Thus -- under freakish circumstances -- one can undo a share that one no longer has the privilege to grant. Usage: ------ c = some_community u = some_user if request_user.can_undo_share_community_with_user(c,u) request_user.undo_share_community_with_user(c,u) """ if __debug__: assert isinstance(this_user, User) assert isinstance(this_community, Community) if not self.user.is_active: raise PermissionDenied("Requesting user is not active") if not this_user.is_active: # This causes problems with display of resources # raise PermissionDenied("Grantee user is not active") return False return self.__get_community_undo_users(this_community).filter(id=this_user.id).exists()
[ "def", "can_undo_share_community_with_user", "(", "self", ",", "this_community", ",", "this_user", ")", ":", "if", "__debug__", ":", "assert", "isinstance", "(", "this_user", ",", "User", ")", "assert", "isinstance", "(", "this_community", ",", "Community", ")", ...
https://github.com/hydroshare/hydroshare/blob/7ba563b55412f283047fb3ef6da367d41dec58c6/hs_access_control/models/user.py#L3254-L3286
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/lib/python2.7/site-packages/pkg_resources/__init__.py
python
Distribution.__eq__
(self, other)
return self.hashcmp == other.hashcmp
[]
def __eq__(self, other): if not isinstance(other, self.__class__): # It's not a Distribution, so they are not equal return False return self.hashcmp == other.hashcmp
[ "def", "__eq__", "(", "self", ",", "other", ")", ":", "if", "not", "isinstance", "(", "other", ",", "self", ".", "__class__", ")", ":", "# It's not a Distribution, so they are not equal", "return", "False", "return", "self", ".", "hashcmp", "==", "other", ".",...
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/lib/python2.7/site-packages/pkg_resources/__init__.py#L2502-L2506
openhatch/oh-mainline
ce29352a034e1223141dcc2f317030bbc3359a51
vendor/packages/twisted/twisted/python/runtime.py
python
Platform.getType
(self)
return self.type
Return 'posix', 'win32' or 'java
Return 'posix', 'win32' or 'java
[ "Return", "posix", "win32", "or", "java" ]
def getType(self): """Return 'posix', 'win32' or 'java'""" return self.type
[ "def", "getType", "(", "self", ")", ":", "return", "self", ".", "type" ]
https://github.com/openhatch/oh-mainline/blob/ce29352a034e1223141dcc2f317030bbc3359a51/vendor/packages/twisted/twisted/python/runtime.py#L48-L50
DLR-RM/BlenderProc
e04e03f34b66702bbca45d1ac701599b6d764609
blenderproc/python/utility/SetupUtility.py
python
SetupUtility.setup
(user_required_packages: Optional[List[str]] = None, blender_path: Optional[str] = None, major_version: Optional[str] = None, reinstall_packages: bool = False, debug_args: Optional[List[str]] = None)
return sys.argv
Sets up the python environment. - Makes sure all required pip packages are installed - Prepares the given sys.argv :param user_required_packages: A list of python packages that are additionally necessary to execute the python script. :param blender_path: The path to the blender installation. If None, it is determined automatically based on the current python env. :param major_version: The version number of the blender installation. If None, it is determined automatically based on the current python env. :param reinstall_packages: Set to true, if all python packages should be reinstalled. :param debug_args: Can be used to overwrite sys.argv in debug mode.
Sets up the python environment.
[ "Sets", "up", "the", "python", "environment", "." ]
def setup(user_required_packages: Optional[List[str]] = None, blender_path: Optional[str] = None, major_version: Optional[str] = None, reinstall_packages: bool = False, debug_args: Optional[List[str]] = None): """ Sets up the python environment. - Makes sure all required pip packages are installed - Prepares the given sys.argv :param user_required_packages: A list of python packages that are additionally necessary to execute the python script. :param blender_path: The path to the blender installation. If None, it is determined automatically based on the current python env. :param major_version: The version number of the blender installation. If None, it is determined automatically based on the current python env. :param reinstall_packages: Set to true, if all python packages should be reinstalled. :param debug_args: Can be used to overwrite sys.argv in debug mode. """ packages_path = SetupUtility.setup_pip(user_required_packages, blender_path, major_version, reinstall_packages) if not SetupUtility.main_setup_called: SetupUtility.main_setup_called = True sys.path.append(packages_path) is_debug_mode = "--background" not in sys.argv # Setup temporary directory if is_debug_mode: SetupUtility.setup_utility_paths("examples/debugging/temp") else: SetupUtility.setup_utility_paths(sys.argv[sys.argv.index("--") + 2]) # Only prepare args in non-debug mode (In debug mode the arguments are already ready to use) if not is_debug_mode: # Cut off blender specific arguments sys.argv = sys.argv[sys.argv.index("--") + 1:sys.argv.index("--") + 2] + sys.argv[sys.argv.index("--") + 3:] elif debug_args is not None: sys.argv = ["debug"] + debug_args return sys.argv
[ "def", "setup", "(", "user_required_packages", ":", "Optional", "[", "List", "[", "str", "]", "]", "=", "None", ",", "blender_path", ":", "Optional", "[", "str", "]", "=", "None", ",", "major_version", ":", "Optional", "[", "str", "]", "=", "None", ","...
https://github.com/DLR-RM/BlenderProc/blob/e04e03f34b66702bbca45d1ac701599b6d764609/blenderproc/python/utility/SetupUtility.py#L24-L56
mozilla/zamboni
14b1a44658e47b9f048962fa52dbf00a3beaaf30
lib/utils.py
python
update_csp
()
After settings, including DEBUG has loaded, see if we need to update CSP.
After settings, including DEBUG has loaded, see if we need to update CSP.
[ "After", "settings", "including", "DEBUG", "has", "loaded", "see", "if", "we", "need", "to", "update", "CSP", "." ]
def update_csp(): """ After settings, including DEBUG has loaded, see if we need to update CSP. """ # This list will expand as we implement more CSP enforcement for key in ('CSP_SCRIPT_SRC',): values = getattr(settings, key) new = set() for value in values: # If we are in debug mode, mirror any HTTPS resources as a # HTTP url. if value.startswith('https://') and settings.DEBUG: res = value.replace('https://', 'http://') for v in value, res: new.add(v) continue # If there's a HTTP url in there and we are not in debug mode # don't add it in. elif value.startswith('http://') and not settings.DEBUG: continue # Add in anything like 'self'. else: new.add(value) setattr(settings, key, tuple(new))
[ "def", "update_csp", "(", ")", ":", "# This list will expand as we implement more CSP enforcement", "for", "key", "in", "(", "'CSP_SCRIPT_SRC'", ",", ")", ":", "values", "=", "getattr", "(", "settings", ",", "key", ")", "new", "=", "set", "(", ")", "for", "val...
https://github.com/mozilla/zamboni/blob/14b1a44658e47b9f048962fa52dbf00a3beaaf30/lib/utils.py#L82-L106
stared/livelossplot
0afb02397af89739c2cd1c36dfc974554ee32215
livelossplot/inputs/poutyne.py
python
PlotLossesCallback.__init__
(self, **kwargs)
Args: **kwargs: keyword arguments that will be passed to PlotLosses constructor
Args: **kwargs: keyword arguments that will be passed to PlotLosses constructor
[ "Args", ":", "**", "kwargs", ":", "keyword", "arguments", "that", "will", "be", "passed", "to", "PlotLosses", "constructor" ]
def __init__(self, **kwargs): """ Args: **kwargs: keyword arguments that will be passed to PlotLosses constructor """ super(PlotLossesCallback, self).__init__() self.liveplot = PlotLosses(**kwargs) self.metrics = None
[ "def", "__init__", "(", "self", ",", "*", "*", "kwargs", ")", ":", "super", "(", "PlotLossesCallback", ",", "self", ")", ".", "__init__", "(", ")", "self", ".", "liveplot", "=", "PlotLosses", "(", "*", "*", "kwargs", ")", "self", ".", "metrics", "=",...
https://github.com/stared/livelossplot/blob/0afb02397af89739c2cd1c36dfc974554ee32215/livelossplot/inputs/poutyne.py#L9-L16
pyca/pyopenssl
fb26edde0aa27670c7bb24c0daeb05516e83d7b0
src/OpenSSL/crypto.py
python
_new_mem_buf
(buffer=None)
return bio
Allocate a new OpenSSL memory BIO. Arrange for the garbage collector to clean it up automatically. :param buffer: None or some bytes to use to put into the BIO so that they can be read out.
Allocate a new OpenSSL memory BIO.
[ "Allocate", "a", "new", "OpenSSL", "memory", "BIO", "." ]
def _new_mem_buf(buffer=None): """ Allocate a new OpenSSL memory BIO. Arrange for the garbage collector to clean it up automatically. :param buffer: None or some bytes to use to put into the BIO so that they can be read out. """ if buffer is None: bio = _lib.BIO_new(_lib.BIO_s_mem()) free = _lib.BIO_free else: data = _ffi.new("char[]", buffer) bio = _lib.BIO_new_mem_buf(data, len(buffer)) # Keep the memory alive as long as the bio is alive! def free(bio, ref=data): return _lib.BIO_free(bio) _openssl_assert(bio != _ffi.NULL) bio = _ffi.gc(bio, free) return bio
[ "def", "_new_mem_buf", "(", "buffer", "=", "None", ")", ":", "if", "buffer", "is", "None", ":", "bio", "=", "_lib", ".", "BIO_new", "(", "_lib", ".", "BIO_s_mem", "(", ")", ")", "free", "=", "_lib", ".", "BIO_free", "else", ":", "data", "=", "_ffi"...
https://github.com/pyca/pyopenssl/blob/fb26edde0aa27670c7bb24c0daeb05516e83d7b0/src/OpenSSL/crypto.py#L105-L128
jgagneastro/coffeegrindsize
22661ebd21831dba4cf32bfc6ba59fe3d49f879c
App/dist/coffeegrindsize.app/Contents/Resources/lib/python3.7/matplotlib/cbook/__init__.py
python
_reshape_2D
(X, name)
Use Fortran ordering to convert ndarrays and lists of iterables to lists of 1D arrays. Lists of iterables are converted by applying `np.asarray` to each of their elements. 1D ndarrays are returned in a singleton list containing them. 2D ndarrays are converted to the list of their *columns*. *name* is used to generate the error message for invalid inputs.
Use Fortran ordering to convert ndarrays and lists of iterables to lists of 1D arrays.
[ "Use", "Fortran", "ordering", "to", "convert", "ndarrays", "and", "lists", "of", "iterables", "to", "lists", "of", "1D", "arrays", "." ]
def _reshape_2D(X, name): """ Use Fortran ordering to convert ndarrays and lists of iterables to lists of 1D arrays. Lists of iterables are converted by applying `np.asarray` to each of their elements. 1D ndarrays are returned in a singleton list containing them. 2D ndarrays are converted to the list of their *columns*. *name* is used to generate the error message for invalid inputs. """ # Iterate over columns for ndarrays, over rows otherwise. X = np.atleast_1d(X.T if isinstance(X, np.ndarray) else np.asarray(X)) if X.ndim == 1 and X.dtype.type != np.object_: # 1D array of scalars: directly return it. return [X] elif X.ndim in [1, 2]: # 2D array, or 1D array of iterables: flatten them first. return [np.reshape(x, -1) for x in X] else: raise ValueError("{} must have 2 or fewer dimensions".format(name))
[ "def", "_reshape_2D", "(", "X", ",", "name", ")", ":", "# Iterate over columns for ndarrays, over rows otherwise.", "X", "=", "np", ".", "atleast_1d", "(", "X", ".", "T", "if", "isinstance", "(", "X", ",", "np", ".", "ndarray", ")", "else", "np", ".", "asa...
https://github.com/jgagneastro/coffeegrindsize/blob/22661ebd21831dba4cf32bfc6ba59fe3d49f879c/App/dist/coffeegrindsize.app/Contents/Resources/lib/python3.7/matplotlib/cbook/__init__.py#L1383-L1403
titusjan/argos
5a9c31a8a9a2ca825bbf821aa1e685740e3682d7
argos/repo/iconfactory.py
python
RtiIconFactory.loadIcon
(self, fileName, color=None)
return self._icons[key]
Reads SVG from a file name and creates an QIcon from it. Optionally replaces the color. Caches the created icons. :param fileName: absolute path to an icon file. If False/empty/None, None returned, which yields no icon. :param color: '#RRGGBB' string (e.g. '#FF0000' for red) :return: QtGui.QIcon
Reads SVG from a file name and creates an QIcon from it.
[ "Reads", "SVG", "from", "a", "file", "name", "and", "creates", "an", "QIcon", "from", "it", "." ]
def loadIcon(self, fileName, color=None): """ Reads SVG from a file name and creates an QIcon from it. Optionally replaces the color. Caches the created icons. :param fileName: absolute path to an icon file. If False/empty/None, None returned, which yields no icon. :param color: '#RRGGBB' string (e.g. '#FF0000' for red) :return: QtGui.QIcon """ if not fileName: return None key = (fileName, color) if key not in self._icons: try: with open(fileName, 'r') as input: svg = input.read() self._icons[key] = self.createIconFromSvg(svg, color=color) except Exception as ex: # It's preferable to show no icon in case of an error rather than letting # the application fail. Icons are a (very) nice to have. logger.warning("Unable to read icon: {}".format(ex)) if DEBUGGING: raise else: return None return self._icons[key]
[ "def", "loadIcon", "(", "self", ",", "fileName", ",", "color", "=", "None", ")", ":", "if", "not", "fileName", ":", "return", "None", "key", "=", "(", "fileName", ",", "color", ")", "if", "key", "not", "in", "self", ".", "_icons", ":", "try", ":", ...
https://github.com/titusjan/argos/blob/5a9c31a8a9a2ca825bbf821aa1e685740e3682d7/argos/repo/iconfactory.py#L153-L182
sahana/eden
1696fa50e90ce967df69f66b571af45356cc18da
modules/templates/historic/RLP/helpers.py
python
get_cms_intro
(module, resource, name, cmsxml=False)
return XML(row.body) if cmsxml else row.body
Get intro from CMS @param module: the module prefix @param resource: the resource name @param name: the post name @param cmsxml: whether to XML-escape the contents or not @returns: the post contents, or None if not available
Get intro from CMS
[ "Get", "intro", "from", "CMS" ]
def get_cms_intro(module, resource, name, cmsxml=False): """ Get intro from CMS @param module: the module prefix @param resource: the resource name @param name: the post name @param cmsxml: whether to XML-escape the contents or not @returns: the post contents, or None if not available """ # Get intro text from CMS db = current.db s3db = current.s3db ctable = s3db.cms_post ltable = s3db.cms_post_module join = ltable.on((ltable.post_id == ctable.id) & \ (ltable.module == module) & \ (ltable.resource == resource) & \ (ltable.deleted == False)) query = (ctable.name == name) & \ (ctable.deleted == False) row = db(query).select(ctable.body, join = join, cache = s3db.cache, limitby = (0, 1), ).first() if not row: return None return XML(row.body) if cmsxml else row.body
[ "def", "get_cms_intro", "(", "module", ",", "resource", ",", "name", ",", "cmsxml", "=", "False", ")", ":", "# Get intro text from CMS", "db", "=", "current", ".", "db", "s3db", "=", "current", ".", "s3db", "ctable", "=", "s3db", ".", "cms_post", "ltable",...
https://github.com/sahana/eden/blob/1696fa50e90ce967df69f66b571af45356cc18da/modules/templates/historic/RLP/helpers.py#L226-L259
apeterswu/RL4NMT
3c66a2d8142abc5ce73db63e05d3cc9bf4663b65
tensor2tensor/models/transformer_moe.py
python
transformer_moe_12k
()
return hparams
Hyper parameters specifics for long sequence generation.
Hyper parameters specifics for long sequence generation.
[ "Hyper", "parameters", "specifics", "for", "long", "sequence", "generation", "." ]
def transformer_moe_12k(): """Hyper parameters specifics for long sequence generation.""" hparams = transformer_moe_8k() hparams.batch_size = 12000 # At 12k, the softmax become the memory bottleneck hparams.factored_logit = True return hparams
[ "def", "transformer_moe_12k", "(", ")", ":", "hparams", "=", "transformer_moe_8k", "(", ")", "hparams", ".", "batch_size", "=", "12000", "# At 12k, the softmax become the memory bottleneck", "hparams", ".", "factored_logit", "=", "True", "return", "hparams" ]
https://github.com/apeterswu/RL4NMT/blob/3c66a2d8142abc5ce73db63e05d3cc9bf4663b65/tensor2tensor/models/transformer_moe.py#L302-L308
webpy/webpy.github.com
c6ccc32b6581edcc1b3e5991ad8cc30df14b5632
static/web-0.134.py
python
transact
()
Start a transaction.
Start a transaction.
[ "Start", "a", "transaction", "." ]
def transact(): """Start a transaction.""" # commit everything up to now, so we don't rollback it later ctx.db.commit() ctx.db_transaction = True
[ "def", "transact", "(", ")", ":", "# commit everything up to now, so we don't rollback it later", "ctx", ".", "db", ".", "commit", "(", ")", "ctx", ".", "db_transaction", "=", "True" ]
https://github.com/webpy/webpy.github.com/blob/c6ccc32b6581edcc1b3e5991ad8cc30df14b5632/static/web-0.134.py#L513-L517
mcfletch/pyopengl
02d11dad9ff18e50db10e975c4756e17bf198464
OpenGL/wrapper.py
python
Wrapper.cArgIndex
( self, argName )
Return the C-argument index for the given argument name
Return the C-argument index for the given argument name
[ "Return", "the", "C", "-", "argument", "index", "for", "the", "given", "argument", "name" ]
def cArgIndex( self, argName ): """Return the C-argument index for the given argument name""" argNames = self.wrappedOperation.argNames try: return asList( argNames ).index( argName ) except (ValueError,IndexError): raise KeyError( """No argument %r in argument list %r"""%( argName, argNames ))
[ "def", "cArgIndex", "(", "self", ",", "argName", ")", ":", "argNames", "=", "self", ".", "wrappedOperation", ".", "argNames", "try", ":", "return", "asList", "(", "argNames", ")", ".", "index", "(", "argName", ")", "except", "(", "ValueError", ",", "Inde...
https://github.com/mcfletch/pyopengl/blob/02d11dad9ff18e50db10e975c4756e17bf198464/OpenGL/wrapper.py#L117-L125
yianjiajia/django_web_ansible
1103343082a65abf9d37310f5048514d74930753
devops/pagination/paginator.py
python
InfinitePage.has_next
(self)
return True
Checks for one more item than last on this page.
Checks for one more item than last on this page.
[ "Checks", "for", "one", "more", "item", "than", "last", "on", "this", "page", "." ]
def has_next(self): """ Checks for one more item than last on this page. """ try: next_item = self.paginator.object_list[ self.number * self.paginator.per_page] except IndexError: return False return True
[ "def", "has_next", "(", "self", ")", ":", "try", ":", "next_item", "=", "self", ".", "paginator", ".", "object_list", "[", "self", ".", "number", "*", "self", ".", "paginator", ".", "per_page", "]", "except", "IndexError", ":", "return", "False", "return...
https://github.com/yianjiajia/django_web_ansible/blob/1103343082a65abf9d37310f5048514d74930753/devops/pagination/paginator.py#L79-L88
nlloyd/SubliminalCollaborator
5c619e17ddbe8acb9eea8996ec038169ddcd50a1
libs/twisted/words/protocols/jabber/sasl.py
python
SASLInitiatingInitializer.onFailure
(self, failure)
Clean up observers, parse the failure and errback the deferred. @param failure: the failure protocol element. Holds details on the error condition. @type failure: L{domish.Element}
Clean up observers, parse the failure and errback the deferred.
[ "Clean", "up", "observers", "parse", "the", "failure", "and", "errback", "the", "deferred", "." ]
def onFailure(self, failure): """ Clean up observers, parse the failure and errback the deferred. @param failure: the failure protocol element. Holds details on the error condition. @type failure: L{domish.Element} """ self.xmlstream.removeObserver('/challenge', self.onChallenge) self.xmlstream.removeObserver('/success', self.onSuccess) try: condition = failure.firstChildElement().name except AttributeError: condition = None self._deferred.errback(SASLAuthError(condition))
[ "def", "onFailure", "(", "self", ",", "failure", ")", ":", "self", ".", "xmlstream", ".", "removeObserver", "(", "'/challenge'", ",", "self", ".", "onChallenge", ")", "self", ".", "xmlstream", ".", "removeObserver", "(", "'/success'", ",", "self", ".", "on...
https://github.com/nlloyd/SubliminalCollaborator/blob/5c619e17ddbe8acb9eea8996ec038169ddcd50a1/libs/twisted/words/protocols/jabber/sasl.py#L228-L243
mdiazcl/fuzzbunch-debian
2b76c2249ade83a389ae3badb12a1bd09901fd2c
windows/Resources/Python/Core/Lib/_pyio.py
python
BufferedReader.peek
(self, n=0)
Returns buffered bytes without advancing the position. The argument indicates a desired minimal number of bytes; we do at most one raw read to satisfy it. We never return more than self.buffer_size.
Returns buffered bytes without advancing the position. The argument indicates a desired minimal number of bytes; we do at most one raw read to satisfy it. We never return more than self.buffer_size.
[ "Returns", "buffered", "bytes", "without", "advancing", "the", "position", ".", "The", "argument", "indicates", "a", "desired", "minimal", "number", "of", "bytes", ";", "we", "do", "at", "most", "one", "raw", "read", "to", "satisfy", "it", ".", "We", "neve...
def peek(self, n=0): """Returns buffered bytes without advancing the position. The argument indicates a desired minimal number of bytes; we do at most one raw read to satisfy it. We never return more than self.buffer_size. """ with self._read_lock: return self._peek_unlocked(n)
[ "def", "peek", "(", "self", ",", "n", "=", "0", ")", ":", "with", "self", ".", "_read_lock", ":", "return", "self", ".", "_peek_unlocked", "(", "n", ")" ]
https://github.com/mdiazcl/fuzzbunch-debian/blob/2b76c2249ade83a389ae3badb12a1bd09901fd2c/windows/Resources/Python/Core/Lib/_pyio.py#L898-L906
secureworks/flowsynth
de58ed4ad137bfc55c59857934f76f481edf1978
src/flowsynth.py
python
output_handler
()
decide what to do about output
decide what to do about output
[ "decide", "what", "to", "do", "about", "output" ]
def output_handler(): """ decide what to do about output """ global ARGS global COMPILER_OUTPUT global COMPILER_TIMELINE global COMPILER_INSTRUCTIONS global START_TIME global END_TIME global RUNTIME if (ARGS.output_format == "hex"): hex_output() else: pcap_output() #print the output summary END_TIME = time.time() RUNTIME = round(END_TIME - START_TIME, 3)
[ "def", "output_handler", "(", ")", ":", "global", "ARGS", "global", "COMPILER_OUTPUT", "global", "COMPILER_TIMELINE", "global", "COMPILER_INSTRUCTIONS", "global", "START_TIME", "global", "END_TIME", "global", "RUNTIME", "if", "(", "ARGS", ".", "output_format", "==", ...
https://github.com/secureworks/flowsynth/blob/de58ed4ad137bfc55c59857934f76f481edf1978/src/flowsynth.py#L879-L896
ganeti/ganeti
d340a9ddd12f501bef57da421b5f9b969a4ba905
lib/config/__init__.py
python
ConfigWriter.GetNodeGroupInfoByName
(self, nodegroup_name)
return None
Get the L{objects.NodeGroup} object for a named node group. @param nodegroup_name: name of the node group to get information for @type nodegroup_name: string @return: the corresponding L{objects.NodeGroup} instance or None if no information is available
Get the L{objects.NodeGroup} object for a named node group.
[ "Get", "the", "L", "{", "objects", ".", "NodeGroup", "}", "object", "for", "a", "named", "node", "group", "." ]
def GetNodeGroupInfoByName(self, nodegroup_name): """Get the L{objects.NodeGroup} object for a named node group. @param nodegroup_name: name of the node group to get information for @type nodegroup_name: string @return: the corresponding L{objects.NodeGroup} instance or None if no information is available """ for nodegroup in self._UnlockedGetAllNodeGroupsInfo().values(): if nodegroup.name == nodegroup_name: return nodegroup return None
[ "def", "GetNodeGroupInfoByName", "(", "self", ",", "nodegroup_name", ")", ":", "for", "nodegroup", "in", "self", ".", "_UnlockedGetAllNodeGroupsInfo", "(", ")", ".", "values", "(", ")", ":", "if", "nodegroup", ".", "name", "==", "nodegroup_name", ":", "return"...
https://github.com/ganeti/ganeti/blob/d340a9ddd12f501bef57da421b5f9b969a4ba905/lib/config/__init__.py#L2304-L2316
plotly/plotly.py
cfad7862594b35965c0e000813bd7805e8494a5b
packages/python/plotly/plotly/graph_objs/_scatterpolargl.py
python
Scatterpolargl.marker
(self)
return self["marker"]
The 'marker' property is an instance of Marker that may be specified as: - An instance of :class:`plotly.graph_objs.scatterpolargl.Marker` - A dict of string/value properties that will be passed to the Marker constructor Supported dict properties: autocolorscale Determines whether the colorscale is a default palette (`autocolorscale: true`) or the palette determined by `marker.colorscale`. Has an effect only if in `marker.color`is set to a numerical array. In case `colorscale` is unspecified or `autocolorscale` is true, the default palette will be chosen according to whether numbers in the `color` array are all positive, all negative or mixed. cauto Determines whether or not the color domain is computed with respect to the input data (here in `marker.color`) or the bounds set in `marker.cmin` and `marker.cmax` Has an effect only if in `marker.color`is set to a numerical array. Defaults to `false` when `marker.cmin` and `marker.cmax` are set by the user. cmax Sets the upper bound of the color domain. Has an effect only if in `marker.color`is set to a numerical array. Value should have the same units as in `marker.color` and if set, `marker.cmin` must be set as well. cmid Sets the mid-point of the color domain by scaling `marker.cmin` and/or `marker.cmax` to be equidistant to this point. Has an effect only if in `marker.color`is set to a numerical array. Value should have the same units as in `marker.color`. Has no effect when `marker.cauto` is `false`. cmin Sets the lower bound of the color domain. Has an effect only if in `marker.color`is set to a numerical array. Value should have the same units as in `marker.color` and if set, `marker.cmax` must be set as well. color Sets themarkercolor. It accepts either a specific color or an array of numbers that are mapped to the colorscale relative to the max and min values of the array or relative to `marker.cmin` and `marker.cmax` if set. coloraxis Sets a reference to a shared color axis. References to these shared color axes are "coloraxis", "coloraxis2", "coloraxis3", etc. Settings for these shared color axes are set in the layout, under `layout.coloraxis`, `layout.coloraxis2`, etc. Note that multiple color scales can be linked to the same color axis. colorbar :class:`plotly.graph_objects.scatterpolargl.mar ker.ColorBar` instance or dict with compatible properties colorscale Sets the colorscale. Has an effect only if in `marker.color`is set to a numerical array. The colorscale must be an array containing arrays mapping a normalized value to an rgb, rgba, hex, hsl, hsv, or named color string. At minimum, a mapping for the lowest (0) and highest (1) values are required. For example, `[[0, 'rgb(0,0,255)'], [1, 'rgb(255,0,0)']]`. To control the bounds of the colorscale in color space, use`marker.cmin` and `marker.cmax`. Alternatively, `colorscale` may be a palette name string of the following list: Blackbody,Bluered,Blues,Cividis,Earth,Electric, Greens,Greys,Hot,Jet,Picnic,Portland,Rainbow,Rd Bu,Reds,Viridis,YlGnBu,YlOrRd. colorsrc Sets the source reference on Chart Studio Cloud for `color`. line :class:`plotly.graph_objects.scatterpolargl.mar ker.Line` instance or dict with compatible properties opacity Sets the marker opacity. opacitysrc Sets the source reference on Chart Studio Cloud for `opacity`. reversescale Reverses the color mapping if true. Has an effect only if in `marker.color`is set to a numerical array. If true, `marker.cmin` will correspond to the last color in the array and `marker.cmax` will correspond to the first color. showscale Determines whether or not a colorbar is displayed for this trace. Has an effect only if in `marker.color`is set to a numerical array. size Sets the marker size (in px). sizemin Has an effect only if `marker.size` is set to a numerical array. Sets the minimum size (in px) of the rendered marker points. sizemode Has an effect only if `marker.size` is set to a numerical array. Sets the rule for which the data in `size` is converted to pixels. sizeref Has an effect only if `marker.size` is set to a numerical array. Sets the scale factor used to determine the rendered size of marker points. Use with `sizemin` and `sizemode`. sizesrc Sets the source reference on Chart Studio Cloud for `size`. symbol Sets the marker symbol type. Adding 100 is equivalent to appending "-open" to a symbol name. Adding 200 is equivalent to appending "-dot" to a symbol name. Adding 300 is equivalent to appending "-open-dot" or "dot- open" to a symbol name. symbolsrc Sets the source reference on Chart Studio Cloud for `symbol`. Returns ------- plotly.graph_objs.scatterpolargl.Marker
The 'marker' property is an instance of Marker that may be specified as: - An instance of :class:`plotly.graph_objs.scatterpolargl.Marker` - A dict of string/value properties that will be passed to the Marker constructor Supported dict properties: autocolorscale Determines whether the colorscale is a default palette (`autocolorscale: true`) or the palette determined by `marker.colorscale`. Has an effect only if in `marker.color`is set to a numerical array. In case `colorscale` is unspecified or `autocolorscale` is true, the default palette will be chosen according to whether numbers in the `color` array are all positive, all negative or mixed. cauto Determines whether or not the color domain is computed with respect to the input data (here in `marker.color`) or the bounds set in `marker.cmin` and `marker.cmax` Has an effect only if in `marker.color`is set to a numerical array. Defaults to `false` when `marker.cmin` and `marker.cmax` are set by the user. cmax Sets the upper bound of the color domain. Has an effect only if in `marker.color`is set to a numerical array. Value should have the same units as in `marker.color` and if set, `marker.cmin` must be set as well. cmid Sets the mid-point of the color domain by scaling `marker.cmin` and/or `marker.cmax` to be equidistant to this point. Has an effect only if in `marker.color`is set to a numerical array. Value should have the same units as in `marker.color`. Has no effect when `marker.cauto` is `false`. cmin Sets the lower bound of the color domain. Has an effect only if in `marker.color`is set to a numerical array. Value should have the same units as in `marker.color` and if set, `marker.cmax` must be set as well. color Sets themarkercolor. It accepts either a specific color or an array of numbers that are mapped to the colorscale relative to the max and min values of the array or relative to `marker.cmin` and `marker.cmax` if set. coloraxis Sets a reference to a shared color axis. References to these shared color axes are "coloraxis", "coloraxis2", "coloraxis3", etc. Settings for these shared color axes are set in the layout, under `layout.coloraxis`, `layout.coloraxis2`, etc. Note that multiple color scales can be linked to the same color axis. colorbar :class:`plotly.graph_objects.scatterpolargl.mar ker.ColorBar` instance or dict with compatible properties colorscale Sets the colorscale. Has an effect only if in `marker.color`is set to a numerical array. The colorscale must be an array containing arrays mapping a normalized value to an rgb, rgba, hex, hsl, hsv, or named color string. At minimum, a mapping for the lowest (0) and highest (1) values are required. For example, `[[0, 'rgb(0,0,255)'], [1, 'rgb(255,0,0)']]`. To control the bounds of the colorscale in color space, use`marker.cmin` and `marker.cmax`. Alternatively, `colorscale` may be a palette name string of the following list: Blackbody,Bluered,Blues,Cividis,Earth,Electric, Greens,Greys,Hot,Jet,Picnic,Portland,Rainbow,Rd Bu,Reds,Viridis,YlGnBu,YlOrRd. colorsrc Sets the source reference on Chart Studio Cloud for `color`. line :class:`plotly.graph_objects.scatterpolargl.mar ker.Line` instance or dict with compatible properties opacity Sets the marker opacity. opacitysrc Sets the source reference on Chart Studio Cloud for `opacity`. reversescale Reverses the color mapping if true. Has an effect only if in `marker.color`is set to a numerical array. If true, `marker.cmin` will correspond to the last color in the array and `marker.cmax` will correspond to the first color. showscale Determines whether or not a colorbar is displayed for this trace. Has an effect only if in `marker.color`is set to a numerical array. size Sets the marker size (in px). sizemin Has an effect only if `marker.size` is set to a numerical array. Sets the minimum size (in px) of the rendered marker points. sizemode Has an effect only if `marker.size` is set to a numerical array. Sets the rule for which the data in `size` is converted to pixels. sizeref Has an effect only if `marker.size` is set to a numerical array. Sets the scale factor used to determine the rendered size of marker points. Use with `sizemin` and `sizemode`. sizesrc Sets the source reference on Chart Studio Cloud for `size`. symbol Sets the marker symbol type. Adding 100 is equivalent to appending "-open" to a symbol name. Adding 200 is equivalent to appending "-dot" to a symbol name. Adding 300 is equivalent to appending "-open-dot" or "dot- open" to a symbol name. symbolsrc Sets the source reference on Chart Studio Cloud for `symbol`.
[ "The", "marker", "property", "is", "an", "instance", "of", "Marker", "that", "may", "be", "specified", "as", ":", "-", "An", "instance", "of", ":", "class", ":", "plotly", ".", "graph_objs", ".", "scatterpolargl", ".", "Marker", "-", "A", "dict", "of", ...
def marker(self): """ The 'marker' property is an instance of Marker that may be specified as: - An instance of :class:`plotly.graph_objs.scatterpolargl.Marker` - A dict of string/value properties that will be passed to the Marker constructor Supported dict properties: autocolorscale Determines whether the colorscale is a default palette (`autocolorscale: true`) or the palette determined by `marker.colorscale`. Has an effect only if in `marker.color`is set to a numerical array. In case `colorscale` is unspecified or `autocolorscale` is true, the default palette will be chosen according to whether numbers in the `color` array are all positive, all negative or mixed. cauto Determines whether or not the color domain is computed with respect to the input data (here in `marker.color`) or the bounds set in `marker.cmin` and `marker.cmax` Has an effect only if in `marker.color`is set to a numerical array. Defaults to `false` when `marker.cmin` and `marker.cmax` are set by the user. cmax Sets the upper bound of the color domain. Has an effect only if in `marker.color`is set to a numerical array. Value should have the same units as in `marker.color` and if set, `marker.cmin` must be set as well. cmid Sets the mid-point of the color domain by scaling `marker.cmin` and/or `marker.cmax` to be equidistant to this point. Has an effect only if in `marker.color`is set to a numerical array. Value should have the same units as in `marker.color`. Has no effect when `marker.cauto` is `false`. cmin Sets the lower bound of the color domain. Has an effect only if in `marker.color`is set to a numerical array. Value should have the same units as in `marker.color` and if set, `marker.cmax` must be set as well. color Sets themarkercolor. It accepts either a specific color or an array of numbers that are mapped to the colorscale relative to the max and min values of the array or relative to `marker.cmin` and `marker.cmax` if set. coloraxis Sets a reference to a shared color axis. References to these shared color axes are "coloraxis", "coloraxis2", "coloraxis3", etc. Settings for these shared color axes are set in the layout, under `layout.coloraxis`, `layout.coloraxis2`, etc. Note that multiple color scales can be linked to the same color axis. colorbar :class:`plotly.graph_objects.scatterpolargl.mar ker.ColorBar` instance or dict with compatible properties colorscale Sets the colorscale. Has an effect only if in `marker.color`is set to a numerical array. The colorscale must be an array containing arrays mapping a normalized value to an rgb, rgba, hex, hsl, hsv, or named color string. At minimum, a mapping for the lowest (0) and highest (1) values are required. For example, `[[0, 'rgb(0,0,255)'], [1, 'rgb(255,0,0)']]`. To control the bounds of the colorscale in color space, use`marker.cmin` and `marker.cmax`. Alternatively, `colorscale` may be a palette name string of the following list: Blackbody,Bluered,Blues,Cividis,Earth,Electric, Greens,Greys,Hot,Jet,Picnic,Portland,Rainbow,Rd Bu,Reds,Viridis,YlGnBu,YlOrRd. colorsrc Sets the source reference on Chart Studio Cloud for `color`. line :class:`plotly.graph_objects.scatterpolargl.mar ker.Line` instance or dict with compatible properties opacity Sets the marker opacity. opacitysrc Sets the source reference on Chart Studio Cloud for `opacity`. reversescale Reverses the color mapping if true. Has an effect only if in `marker.color`is set to a numerical array. If true, `marker.cmin` will correspond to the last color in the array and `marker.cmax` will correspond to the first color. showscale Determines whether or not a colorbar is displayed for this trace. Has an effect only if in `marker.color`is set to a numerical array. size Sets the marker size (in px). sizemin Has an effect only if `marker.size` is set to a numerical array. Sets the minimum size (in px) of the rendered marker points. sizemode Has an effect only if `marker.size` is set to a numerical array. Sets the rule for which the data in `size` is converted to pixels. sizeref Has an effect only if `marker.size` is set to a numerical array. Sets the scale factor used to determine the rendered size of marker points. Use with `sizemin` and `sizemode`. sizesrc Sets the source reference on Chart Studio Cloud for `size`. symbol Sets the marker symbol type. Adding 100 is equivalent to appending "-open" to a symbol name. Adding 200 is equivalent to appending "-dot" to a symbol name. Adding 300 is equivalent to appending "-open-dot" or "dot- open" to a symbol name. symbolsrc Sets the source reference on Chart Studio Cloud for `symbol`. Returns ------- plotly.graph_objs.scatterpolargl.Marker """ return self["marker"]
[ "def", "marker", "(", "self", ")", ":", "return", "self", "[", "\"marker\"", "]" ]
https://github.com/plotly/plotly.py/blob/cfad7862594b35965c0e000813bd7805e8494a5b/packages/python/plotly/plotly/graph_objs/_scatterpolargl.py#L644-L783
jkwill87/mnamer
c8bbc63a8847e9b15b0f512f7ae01de0b98cf739
mnamer/providers.py
python
Provider.__init__
(self, api_key: str = None, cache: bool = True)
Initializes the provider.
Initializes the provider.
[ "Initializes", "the", "provider", "." ]
def __init__(self, api_key: str = None, cache: bool = True): """Initializes the provider.""" if api_key: self.api_key = api_key if cache: self.cache = cache
[ "def", "__init__", "(", "self", ",", "api_key", ":", "str", "=", "None", ",", "cache", ":", "bool", "=", "True", ")", ":", "if", "api_key", ":", "self", ".", "api_key", "=", "api_key", "if", "cache", ":", "self", ".", "cache", "=", "cache" ]
https://github.com/jkwill87/mnamer/blob/c8bbc63a8847e9b15b0f512f7ae01de0b98cf739/mnamer/providers.py#L25-L30
yzhao062/pyod
13b0cd5f50d5ea5c5321da88c46232ae6f24dff7
pyod/models/abod.py
python
ABOD._fit_default
(self)
return self
Default ABOD method. Use all training points with high complexity O(n^3). For internal use only.
Default ABOD method. Use all training points with high complexity O(n^3). For internal use only.
[ "Default", "ABOD", "method", ".", "Use", "all", "training", "points", "with", "high", "complexity", "O", "(", "n^3", ")", ".", "For", "internal", "use", "only", "." ]
def _fit_default(self): """Default ABOD method. Use all training points with high complexity O(n^3). For internal use only. """ for i in range(self.n_train_): curr_pt = self.X_train_[i, :] # get the index pairs of the neighbors, remove itself from index X_ind = list(range(0, self.n_train_)) X_ind.remove(i) self.decision_scores_[i, 0] = _calculate_wocs(curr_pt, self.X_train_, X_ind) return self
[ "def", "_fit_default", "(", "self", ")", ":", "for", "i", "in", "range", "(", "self", ".", "n_train_", ")", ":", "curr_pt", "=", "self", ".", "X_train_", "[", "i", ",", ":", "]", "# get the index pairs of the neighbors, remove itself from index", "X_ind", "=",...
https://github.com/yzhao062/pyod/blob/13b0cd5f50d5ea5c5321da88c46232ae6f24dff7/pyod/models/abod.py#L182-L196
daoluan/decode-Django
d46a858b45b56de48b0355f50dd9e45402d04cfd
Django-1.5.1/django/contrib/auth/forms.py
python
AuthenticationForm.__init__
(self, request=None, *args, **kwargs)
If request is passed in, the form will validate that cookies are enabled. Note that the request (a HttpRequest object) must have set a cookie with the key TEST_COOKIE_NAME and value TEST_COOKIE_VALUE before running this validation.
If request is passed in, the form will validate that cookies are enabled. Note that the request (a HttpRequest object) must have set a cookie with the key TEST_COOKIE_NAME and value TEST_COOKIE_VALUE before running this validation.
[ "If", "request", "is", "passed", "in", "the", "form", "will", "validate", "that", "cookies", "are", "enabled", ".", "Note", "that", "the", "request", "(", "a", "HttpRequest", "object", ")", "must", "have", "set", "a", "cookie", "with", "the", "key", "TES...
def __init__(self, request=None, *args, **kwargs): """ If request is passed in, the form will validate that cookies are enabled. Note that the request (a HttpRequest object) must have set a cookie with the key TEST_COOKIE_NAME and value TEST_COOKIE_VALUE before running this validation. """ self.request = request self.user_cache = None super(AuthenticationForm, self).__init__(*args, **kwargs) # Set the label for the "username" field. UserModel = get_user_model() self.username_field = UserModel._meta.get_field(UserModel.USERNAME_FIELD) if not self.fields['username'].label: self.fields['username'].label = capfirst(self.username_field.verbose_name)
[ "def", "__init__", "(", "self", ",", "request", "=", "None", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "request", "=", "request", "self", ".", "user_cache", "=", "None", "super", "(", "AuthenticationForm", ",", "self", ")", "....
https://github.com/daoluan/decode-Django/blob/d46a858b45b56de48b0355f50dd9e45402d04cfd/Django-1.5.1/django/contrib/auth/forms.py#L158-L173
huawei-noah/vega
d9f13deede7f2b584e4b1d32ffdb833856129989
vega/core/search_space/forbidden.py
python
ForbiddenAndConjunction.__new__
(cls, forbidden_list)
return object.__new__(cls)
Build new class.
Build new class.
[ "Build", "new", "class", "." ]
def __new__(cls, forbidden_list): """Build new class.""" if not isinstance(forbidden_list, list): raise ValueError('Invalid forbidden_list type {}, should be List type.'.format(type(forbidden_list))) for forbidden in forbidden_list: if not isinstance(forbidden, ForbiddenEqualsClause): raise ValueError( 'Invalid forbidden of list type {}, should be ' 'ForbiddenEqualsClause type.'.format(type(forbidden))) return object.__new__(cls)
[ "def", "__new__", "(", "cls", ",", "forbidden_list", ")", ":", "if", "not", "isinstance", "(", "forbidden_list", ",", "list", ")", ":", "raise", "ValueError", "(", "'Invalid forbidden_list type {}, should be List type.'", ".", "format", "(", "type", "(", "forbidde...
https://github.com/huawei-noah/vega/blob/d9f13deede7f2b584e4b1d32ffdb833856129989/vega/core/search_space/forbidden.py#L52-L61
algorhythms/HackerRankAlgorithms
439bf2e31fd395d19d40f79e969153e50e5358b5
Knapsack.py
python
Solution.solve
(self, cipher)
return f[n][k]
repeatable knapsack, dp f[i][c] represents the max possible value at the index i given the capacity c normally: f[i][c] = max{f[i-1][c], f[i-1][c-w_i]+v_i} since repeatable: f[i][c] = max{f[i-1][c], f[i-1][c-w_i]+v_i, f[i][c-w_i]+v_i} since f[i][c] represent the max possible value at i, c; thus only need to consider f[i-1][c-w_i] among others :param cipher: the cipher
repeatable knapsack, dp
[ "repeatable", "knapsack", "dp" ]
def solve(self, cipher): """ repeatable knapsack, dp f[i][c] represents the max possible value at the index i given the capacity c normally: f[i][c] = max{f[i-1][c], f[i-1][c-w_i]+v_i} since repeatable: f[i][c] = max{f[i-1][c], f[i-1][c-w_i]+v_i, f[i][c-w_i]+v_i} since f[i][c] represent the max possible value at i, c; thus only need to consider f[i-1][c-w_i] among others :param cipher: the cipher """ n, k, A = cipher f = [[0 for _ in xrange(k + 1)] for _ in xrange(n + 1)] # f[0, :] is dummies for i in xrange(n + 1): for c in xrange(k + 1): f[i][c] = f[i - 1][c] temp = c - A[i - 1] if temp >= 0: f[i][c] = max(f[i - 1][c], f[i - 1][c - A[i - 1]] + A[i - 1], f[i][c - A[i - 1]] + A[i - 1]) return f[n][k]
[ "def", "solve", "(", "self", ",", "cipher", ")", ":", "n", ",", "k", ",", "A", "=", "cipher", "f", "=", "[", "[", "0", "for", "_", "in", "xrange", "(", "k", "+", "1", ")", "]", "for", "_", "in", "xrange", "(", "n", "+", "1", ")", "]", "...
https://github.com/algorhythms/HackerRankAlgorithms/blob/439bf2e31fd395d19d40f79e969153e50e5358b5/Knapsack.py#L23-L45
pwnieexpress/pwn_plug_sources
1a23324f5dc2c3de20f9c810269b6a29b2758cad
src/set/src/core/digitalsig/disitool.py
python
DeleteDigitalSignature
(SignedFile, UnsignedFile=None)
return new_file_data
Deletes the digital signature from file SignedFile When UnsignedFile is not None, writes the modified file to UnsignedFile Returns the modified file as a PE file
Deletes the digital signature from file SignedFile When UnsignedFile is not None, writes the modified file to UnsignedFile Returns the modified file as a PE file
[ "Deletes", "the", "digital", "signature", "from", "file", "SignedFile", "When", "UnsignedFile", "is", "not", "None", "writes", "the", "modified", "file", "to", "UnsignedFile", "Returns", "the", "modified", "file", "as", "a", "PE", "file" ]
def DeleteDigitalSignature(SignedFile, UnsignedFile=None): """Deletes the digital signature from file SignedFile When UnsignedFile is not None, writes the modified file to UnsignedFile Returns the modified file as a PE file """ pe = pefile.PE(SignedFile) address = pe.OPTIONAL_HEADER.DATA_DIRECTORY[pefile.DIRECTORY_ENTRY['IMAGE_DIRECTORY_ENTRY_SECURITY']].VirtualAddress pe.OPTIONAL_HEADER.DATA_DIRECTORY[pefile.DIRECTORY_ENTRY['IMAGE_DIRECTORY_ENTRY_SECURITY']].VirtualAddress = 0 pe.OPTIONAL_HEADER.DATA_DIRECTORY[pefile.DIRECTORY_ENTRY['IMAGE_DIRECTORY_ENTRY_SECURITY']].Size = 0 if address != 0: new_file_data = pe.write()[0:address] else: new_file_data = pe.write() if UnsignedFile: f = file(UnsignedFile, 'wb+') f.write(new_file_data) f.close() return new_file_data
[ "def", "DeleteDigitalSignature", "(", "SignedFile", ",", "UnsignedFile", "=", "None", ")", ":", "pe", "=", "pefile", ".", "PE", "(", "SignedFile", ")", "address", "=", "pe", ".", "OPTIONAL_HEADER", ".", "DATA_DIRECTORY", "[", "pefile", ".", "DIRECTORY_ENTRY", ...
https://github.com/pwnieexpress/pwn_plug_sources/blob/1a23324f5dc2c3de20f9c810269b6a29b2758cad/src/set/src/core/digitalsig/disitool.py#L49-L70
aimagelab/meshed-memory-transformer
e0fe3fae68091970407e82e5b907cbc423f25df2
evaluation/bleu/bleu_scorer.py
python
BleuScorer.score_ratio_str
(self, option=None)
return "%.4f (%.2f)" % self.score_ratio(option)
[]
def score_ratio_str(self, option=None): return "%.4f (%.2f)" % self.score_ratio(option)
[ "def", "score_ratio_str", "(", "self", ",", "option", "=", "None", ")", ":", "return", "\"%.4f (%.2f)\"", "%", "self", ".", "score_ratio", "(", "option", ")" ]
https://github.com/aimagelab/meshed-memory-transformer/blob/e0fe3fae68091970407e82e5b907cbc423f25df2/evaluation/bleu/bleu_scorer.py#L139-L140
ltworf/typedload
a115d7ca1c354a03b392607b60de84ce91d5e106
typedload/typechecks.py
python
is_any
(type_: Type[Any])
return type_ == Any
Check if it is a typing.Any
Check if it is a typing.Any
[ "Check", "if", "it", "is", "a", "typing", ".", "Any" ]
def is_any(type_: Type[Any]) -> bool: ''' Check if it is a typing.Any ''' return type_ == Any
[ "def", "is_any", "(", "type_", ":", "Type", "[", "Any", "]", ")", "->", "bool", ":", "return", "type_", "==", "Any" ]
https://github.com/ltworf/typedload/blob/a115d7ca1c354a03b392607b60de84ce91d5e106/typedload/typechecks.py#L240-L244
p2pool/p2pool
53c438bbada06b9d4a9a465bc13f7694a7a322b7
wstools/logging.py
python
sendUDP
(url, outputStr)
[]
def sendUDP(url, outputStr): from socket import socket, AF_INET, SOCK_DGRAM idx1 = url.find('://') + 3; idx2 = url.find('/', idx1) if idx2 < idx1: idx2 = len(url) netloc = url[idx1:idx2] host,port = (netloc.split(':')+[80])[0:2] socket(AF_INET, SOCK_DGRAM).sendto( outputStr, (host,int(port)), )
[ "def", "sendUDP", "(", "url", ",", "outputStr", ")", ":", "from", "socket", "import", "socket", ",", "AF_INET", ",", "SOCK_DGRAM", "idx1", "=", "url", ".", "find", "(", "'://'", ")", "+", "3", "idx2", "=", "url", ".", "find", "(", "'/'", ",", "idx1...
https://github.com/p2pool/p2pool/blob/53c438bbada06b9d4a9a465bc13f7694a7a322b7/wstools/logging.py#L212-L218
google-research/torchsde
53038a3efcd77f6c9f3cfd0310700a59be5d5d2d
torchsde/_core/adjoint_sde.py
python
AdjointSDE.get_state
(self, t, y_aug, v=None, extra_states=False)
return y, adj_y, extra_states, requires_grad
Unpacks y_aug, whilst enforcing the necessary checks so that we can calculate derivatives wrt state.
Unpacks y_aug, whilst enforcing the necessary checks so that we can calculate derivatives wrt state.
[ "Unpacks", "y_aug", "whilst", "enforcing", "the", "necessary", "checks", "so", "that", "we", "can", "calculate", "derivatives", "wrt", "state", "." ]
def get_state(self, t, y_aug, v=None, extra_states=False): """Unpacks y_aug, whilst enforcing the necessary checks so that we can calculate derivatives wrt state.""" # These leaf checks are very important. # get_state is used where we want to compute: # ``` # with torch.enable_grad(): # s = some_function(y) # torch.autograd.grad(s, [y] + params, ...) # ``` # where `some_function` implicitly depends on `params`. # However if y has history of its own then in principle it could _also_ depend upon `params`, and this call to # `grad` will go all the way back to that. To avoid this, we require that every input tensor be a leaf tensor. # # This is also the reason for the `y0.detach()` in adjoint.py::_SdeintAdjointMethod.forward. If we don't detach, # then y0 may have a history and these checks will fail. This is a spurious failure as # `torch.autograd.Function.forward` has an implicit `torch.no_grad()` guard, i.e. we definitely don't want to # use its history there. assert t.is_leaf, "Internal error: please report a bug to torchsde" assert y_aug.is_leaf, "Internal error: please report a bug to torchsde" if v is not None: assert v.is_leaf, "Internal error: please report a bug to torchsde" requires_grad = torch.is_grad_enabled() if extra_states: shapes = self._shapes else: shapes = self._shapes[:2] numel = sum(shape.numel() for shape in shapes) y, adj_y, *extra_states = misc.flat_to_shape(y_aug.squeeze(0)[:numel], shapes) # To support the later differentiation wrt y, we set it to require_grad if it doesn't already. if not y.requires_grad: y = y.detach().requires_grad_() return y, adj_y, extra_states, requires_grad
[ "def", "get_state", "(", "self", ",", "t", ",", "y_aug", ",", "v", "=", "None", ",", "extra_states", "=", "False", ")", ":", "# These leaf checks are very important.", "# get_state is used where we want to compute:", "# ```", "# with torch.enable_grad():", "# s = some...
https://github.com/google-research/torchsde/blob/53038a3efcd77f6c9f3cfd0310700a59be5d5d2d/torchsde/_core/adjoint_sde.py#L74-L109
tensorflow/lattice
784eca50cbdfedf39f183cc7d298c9fe376b69c0
tensorflow_lattice/python/cdf_layer.py
python
CDF.call
(self, inputs)
return result
Standard Keras call() method.
Standard Keras call() method.
[ "Standard", "Keras", "call", "()", "method", "." ]
def call(self, inputs): """Standard Keras call() method.""" input_dim = int(inputs.shape[-1]) # We add new axes to enable broadcasting. x = inputs[..., tf.newaxis, tf.newaxis] # Shape: (batch, input_dim, 1, 1) # --> (batch, input_dim, num_keypoints, units / factor) # --> (batch, input_dim, units / factor) if self.activation == "relu6": cdfs = tf.reduce_mean( tf.nn.relu6(self.input_scaling * (x - self.kernel)), axis=2) / 6 elif self.activation == "sigmoid": cdfs = tf.reduce_mean( tf.nn.sigmoid(self.input_scaling * (x - self.kernel)), axis=2) else: raise ValueError("Invalid activation: {}".format(self.activation)) result = cdfs if self.sparsity_factor != 1: # Shape: (batch, input_dim, units / factor) # --> (batch, input_dim / factor, units) result = tf.reshape( result, [-1, int(input_dim // self.sparsity_factor), self.units]) # Shape: (batch, input_dim / factor, units) #. --> (batch, units) if self.reduction == "mean": result = tf.reduce_mean(result, axis=1) elif self.reduction == "geometric_mean": num_terms = input_dim // self.sparsity_factor result = tf.math.exp( tf.reduce_sum(tf.math.log(result + 1e-3), axis=1) / num_terms) # we use the log form above so that we can add the epsilon term # tf.pow(tf.reduce_prod(cdfs, axis=1), 1. / num_terms) elif self.reduction != "none": raise ValueError("Invalid reduction: {}".format(self.reduction)) return result
[ "def", "call", "(", "self", ",", "inputs", ")", ":", "input_dim", "=", "int", "(", "inputs", ".", "shape", "[", "-", "1", "]", ")", "# We add new axes to enable broadcasting.", "x", "=", "inputs", "[", "...", ",", "tf", ".", "newaxis", ",", "tf", ".", ...
https://github.com/tensorflow/lattice/blob/784eca50cbdfedf39f183cc7d298c9fe376b69c0/tensorflow_lattice/python/cdf_layer.py#L197-L236
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/lib/python2.7/site-packages/dateutil/tz/tz.py
python
_ttinfo.__eq__
(self, other)
return (self.offset == other.offset and self.delta == other.delta and self.isdst == other.isdst and self.abbr == other.abbr and self.isstd == other.isstd and self.isgmt == other.isgmt and self.dstoffset == other.dstoffset)
[]
def __eq__(self, other): if not isinstance(other, _ttinfo): return NotImplemented return (self.offset == other.offset and self.delta == other.delta and self.isdst == other.isdst and self.abbr == other.abbr and self.isstd == other.isstd and self.isgmt == other.isgmt and self.dstoffset == other.dstoffset)
[ "def", "__eq__", "(", "self", ",", "other", ")", ":", "if", "not", "isinstance", "(", "other", ",", "_ttinfo", ")", ":", "return", "NotImplemented", "return", "(", "self", ".", "offset", "==", "other", ".", "offset", "and", "self", ".", "delta", "==", ...
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/lib/python2.7/site-packages/dateutil/tz/tz.py#L332-L342
holzschu/Carnets
44effb10ddfc6aa5c8b0687582a724ba82c6b547
Library/lib/python3.7/site-packages/docutils/utils/smartquotes.py
python
educateDashes
(text)
return text
Parameter: String (unicode or bytes). Returns: The `text`, with each instance of "--" translated to an em-dash character.
Parameter: String (unicode or bytes). Returns: The `text`, with each instance of "--" translated to an em-dash character.
[ "Parameter", ":", "String", "(", "unicode", "or", "bytes", ")", ".", "Returns", ":", "The", "text", "with", "each", "instance", "of", "--", "translated", "to", "an", "em", "-", "dash", "character", "." ]
def educateDashes(text): """ Parameter: String (unicode or bytes). Returns: The `text`, with each instance of "--" translated to an em-dash character. """ text = re.sub(r"""---""", smartchars.endash, text) # en (yes, backwards) text = re.sub(r"""--""", smartchars.emdash, text) # em (yes, backwards) return text
[ "def", "educateDashes", "(", "text", ")", ":", "text", "=", "re", ".", "sub", "(", "r\"\"\"---\"\"\"", ",", "smartchars", ".", "endash", ",", "text", ")", "# en (yes, backwards)", "text", "=", "re", ".", "sub", "(", "r\"\"\"--\"\"\"", ",", "smartchars", "...
https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/site-packages/docutils/utils/smartquotes.py#L767-L776
reviewboard/reviewboard
7395902e4c181bcd1d633f61105012ffb1d18e1b
reviewboard/webapi/resources/hosting_service_account.py
python
HostingServiceAccountResource.create
(self, request, username, service_id, password=None, hosting_url=None, local_site_name=None, *args, **kwargs)
return 201, { self.item_result_key: account, }
Creates a hosting service account. The ``service_id`` is a registered HostingService ID. This must be known beforehand, and can be looked up in the Review Board administration UI.
Creates a hosting service account.
[ "Creates", "a", "hosting", "service", "account", "." ]
def create(self, request, username, service_id, password=None, hosting_url=None, local_site_name=None, *args, **kwargs): """Creates a hosting service account. The ``service_id`` is a registered HostingService ID. This must be known beforehand, and can be looked up in the Review Board administration UI. """ local_site = self._get_local_site(local_site_name) if not HostingServiceAccount.objects.can_create(request.user, local_site): return self.get_no_access_error(request) # Validate the service. service = get_hosting_service(service_id) if not service: return INVALID_FORM_DATA, { 'fields': { 'service': ['This is not a valid service name'], } } if service.self_hosted and not hosting_url: return INVALID_FORM_DATA, { 'fields': { 'hosting_url': ['This field is required'], } } account = HostingServiceAccount(service_name=service_id, username=username, hosting_url=hosting_url, local_site=local_site) service = account.service if service.needs_authorization: try: service.authorize(request, username, password, hosting_url, local_site_name) except AuthorizationError as e: return HOSTINGSVC_AUTH_ERROR, { 'reason': six.text_type(e), } account.save() return 201, { self.item_result_key: account, }
[ "def", "create", "(", "self", ",", "request", ",", "username", ",", "service_id", ",", "password", "=", "None", ",", "hosting_url", "=", "None", ",", "local_site_name", "=", "None", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "local_site", "="...
https://github.com/reviewboard/reviewboard/blob/7395902e4c181bcd1d633f61105012ffb1d18e1b/reviewboard/webapi/resources/hosting_service_account.py#L166-L216
ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework
cb692f527e4e819b6c228187c5702d990a180043
bin/x86/Debug/scripting_engine/Lib/warnings.py
python
catch_warnings.__init__
(self, record=False, module=None)
Specify whether to record warnings and if an alternative module should be used other than sys.modules['warnings']. For compatibility with Python 3.0, please consider all arguments to be keyword-only.
Specify whether to record warnings and if an alternative module should be used other than sys.modules['warnings'].
[ "Specify", "whether", "to", "record", "warnings", "and", "if", "an", "alternative", "module", "should", "be", "used", "other", "than", "sys", ".", "modules", "[", "warnings", "]", "." ]
def __init__(self, record=False, module=None): """Specify whether to record warnings and if an alternative module should be used other than sys.modules['warnings']. For compatibility with Python 3.0, please consider all arguments to be keyword-only. """ self._record = record self._module = sys.modules['warnings'] if module is None else module self._entered = False
[ "def", "__init__", "(", "self", ",", "record", "=", "False", ",", "module", "=", "None", ")", ":", "self", ".", "_record", "=", "record", "self", ".", "_module", "=", "sys", ".", "modules", "[", "'warnings'", "]", "if", "module", "is", "None", "else"...
https://github.com/ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework/blob/cb692f527e4e819b6c228187c5702d990a180043/bin/x86/Debug/scripting_engine/Lib/warnings.py#L318-L328
omergertel/pyformance
b71056eaf9af6cafd3e3c4a416412ae425bdc82e
pyformance/reporters/syslog_reporter.py
python
SysLogReporter.__init__
( self, registry=None, reporting_interval=5, tag="pyformance", clock=None, address=DEFAULT_SYSLOG_ADDRESS, socktype=DEFAULT_SYSLOG_SOCKTYPE, facility=DEFAULT_SYSLOG_FACILITY, )
[]
def __init__( self, registry=None, reporting_interval=5, tag="pyformance", clock=None, address=DEFAULT_SYSLOG_ADDRESS, socktype=DEFAULT_SYSLOG_SOCKTYPE, facility=DEFAULT_SYSLOG_FACILITY, ): super(SysLogReporter, self).__init__(registry, reporting_interval, clock) handler = logging.handlers.SysLogHandler( address=address, facility=facility, socktype=socktype ) handler.append_nul = False if tag is not None and tag != "": if sys.version_info >= (3, 3): handler.ident = tag + ": " else: formatter = logging.Formatter("{}: %(message)s".format(tag)) handler.setFormatter(formatter) logger = logging.getLogger("pyformance") logger.setLevel(logging.INFO) logger.addHandler(handler) self.logger = logger
[ "def", "__init__", "(", "self", ",", "registry", "=", "None", ",", "reporting_interval", "=", "5", ",", "tag", "=", "\"pyformance\"", ",", "clock", "=", "None", ",", "address", "=", "DEFAULT_SYSLOG_ADDRESS", ",", "socktype", "=", "DEFAULT_SYSLOG_SOCKTYPE", ","...
https://github.com/omergertel/pyformance/blob/b71056eaf9af6cafd3e3c4a416412ae425bdc82e/pyformance/reporters/syslog_reporter.py#L22-L49
oracle/oci-python-sdk
3c1604e4e212008fb6718e2f68cdb5ef71fd5793
src/oci/service_catalog/service_catalog_client.py
python
ServiceCatalogClient.get_private_application
(self, private_application_id, **kwargs)
Gets the details of the specified private application. :param str private_application_id: (required) The unique identifier for the private application. :param str opc_request_id: (optional) Unique Oracle-assigned identifier for the request. If you need to contact Oracle about a particular request, please provide the request ID. :param obj retry_strategy: (optional) A retry strategy to apply to this specific operation/call. This will override any retry strategy set at the client-level. This should be one of the strategies available in the :py:mod:`~oci.retry` module. This operation will not retry by default, users can also use the convenient :py:data:`~oci.retry.DEFAULT_RETRY_STRATEGY` provided by the SDK to enable retries for it. The specifics of the default retry strategy are described `here <https://docs.oracle.com/en-us/iaas/tools/python/latest/sdk_behaviors/retries.html>`__. To have this operation explicitly not perform any retries, pass an instance of :py:class:`~oci.retry.NoneRetryStrategy`. :return: A :class:`~oci.response.Response` object with data of type :class:`~oci.service_catalog.models.PrivateApplication` :rtype: :class:`~oci.response.Response` :example: Click `here <https://docs.cloud.oracle.com/en-us/iaas/tools/python-sdk-examples/latest/servicecatalog/get_private_application.py.html>`__ to see an example of how to use get_private_application API.
Gets the details of the specified private application.
[ "Gets", "the", "details", "of", "the", "specified", "private", "application", "." ]
def get_private_application(self, private_application_id, **kwargs): """ Gets the details of the specified private application. :param str private_application_id: (required) The unique identifier for the private application. :param str opc_request_id: (optional) Unique Oracle-assigned identifier for the request. If you need to contact Oracle about a particular request, please provide the request ID. :param obj retry_strategy: (optional) A retry strategy to apply to this specific operation/call. This will override any retry strategy set at the client-level. This should be one of the strategies available in the :py:mod:`~oci.retry` module. This operation will not retry by default, users can also use the convenient :py:data:`~oci.retry.DEFAULT_RETRY_STRATEGY` provided by the SDK to enable retries for it. The specifics of the default retry strategy are described `here <https://docs.oracle.com/en-us/iaas/tools/python/latest/sdk_behaviors/retries.html>`__. To have this operation explicitly not perform any retries, pass an instance of :py:class:`~oci.retry.NoneRetryStrategy`. :return: A :class:`~oci.response.Response` object with data of type :class:`~oci.service_catalog.models.PrivateApplication` :rtype: :class:`~oci.response.Response` :example: Click `here <https://docs.cloud.oracle.com/en-us/iaas/tools/python-sdk-examples/latest/servicecatalog/get_private_application.py.html>`__ to see an example of how to use get_private_application API. """ resource_path = "/privateApplications/{privateApplicationId}" method = "GET" # Don't accept unknown kwargs expected_kwargs = [ "retry_strategy", "opc_request_id" ] extra_kwargs = [_key for _key in six.iterkeys(kwargs) if _key not in expected_kwargs] if extra_kwargs: raise ValueError( "get_private_application got unknown kwargs: {!r}".format(extra_kwargs)) path_params = { "privateApplicationId": private_application_id } path_params = {k: v for (k, v) in six.iteritems(path_params) if v is not missing} for (k, v) in six.iteritems(path_params): if v is None or (isinstance(v, six.string_types) and len(v.strip()) == 0): raise ValueError('Parameter {} cannot be None, whitespace or empty string'.format(k)) header_params = { "accept": "application/json", "content-type": "application/json", "opc-request-id": kwargs.get("opc_request_id", missing) } header_params = {k: v for (k, v) in six.iteritems(header_params) if v is not missing and v is not None} retry_strategy = self.base_client.get_preferred_retry_strategy( operation_retry_strategy=kwargs.get('retry_strategy'), client_retry_strategy=self.retry_strategy ) if retry_strategy: if not isinstance(retry_strategy, retry.NoneRetryStrategy): self.base_client.add_opc_client_retries_header(header_params) retry_strategy.add_circuit_breaker_callback(self.circuit_breaker_callback) return retry_strategy.make_retrying_call( self.base_client.call_api, resource_path=resource_path, method=method, path_params=path_params, header_params=header_params, response_type="PrivateApplication") else: return self.base_client.call_api( resource_path=resource_path, method=method, path_params=path_params, header_params=header_params, response_type="PrivateApplication")
[ "def", "get_private_application", "(", "self", ",", "private_application_id", ",", "*", "*", "kwargs", ")", ":", "resource_path", "=", "\"/privateApplications/{privateApplicationId}\"", "method", "=", "\"GET\"", "# Don't accept unknown kwargs", "expected_kwargs", "=", "[", ...
https://github.com/oracle/oci-python-sdk/blob/3c1604e4e212008fb6718e2f68cdb5ef71fd5793/src/oci/service_catalog/service_catalog_client.py#L863-L941
alteryx/featuretools
d59e11082962f163540fd6e185901f65c506326a
featuretools/utils/koalas_utils.py
python
replace_categorical_columns
(pdf)
return new_df
[]
def replace_categorical_columns(pdf): new_df = pd.DataFrame() for c in pdf.columns: col = pdf[c] if col.dtype.name == 'category': new_df[c] = col.astype('string') else: new_df[c] = pdf[c] return new_df
[ "def", "replace_categorical_columns", "(", "pdf", ")", ":", "new_df", "=", "pd", ".", "DataFrame", "(", ")", "for", "c", "in", "pdf", ".", "columns", ":", "col", "=", "pdf", "[", "c", "]", "if", "col", ".", "dtype", ".", "name", "==", "'category'", ...
https://github.com/alteryx/featuretools/blob/d59e11082962f163540fd6e185901f65c506326a/featuretools/utils/koalas_utils.py#L25-L33
okpy/ok
50a00190f05363d096478dd8e53aa1a36dd40c4a
server/models.py
python
Version.save
(self)
[]
def save(self): cache.delete_memoized(Version.get_current_versions, self.name) cache.delete_memoized(Version.get_current_versions, None) db.session.add(self) db.session.commit()
[ "def", "save", "(", "self", ")", ":", "cache", ".", "delete_memoized", "(", "Version", ".", "get_current_versions", ",", "self", ".", "name", ")", "cache", ".", "delete_memoized", "(", "Version", ".", "get_current_versions", ",", "None", ")", "db", ".", "s...
https://github.com/okpy/ok/blob/50a00190f05363d096478dd8e53aa1a36dd40c4a/server/models.py#L1392-L1396
japerk/nltk-trainer
1d48784a6e7558641ed40875d426fe376d41e11c
nltk_trainer/featx/phonetics.py
python
caverphone
(term)
return caverphoneCode
returns the language key using the caverphone algorithm 2.0
returns the language key using the caverphone algorithm 2.0
[ "returns", "the", "language", "key", "using", "the", "caverphone", "algorithm", "2", ".", "0" ]
def caverphone (term): "returns the language key using the caverphone algorithm 2.0" # Developed at the University of Otago, New Zealand. # Project: Caversham Project (http://caversham.otago.ac.nz) # Developer: David Hood, University of Otago, New Zealand # Contact: caversham@otago.ac.nz # Project Technical Paper: http://caversham.otago.ac.nz/files/working/ctp150804.pdf # Version 2.0 (2004-08-15) code = "" i = 0 term_length = len(term) if (term_length == 0): # empty string ? return code # end if # convert to lowercase code = string.lower(term) # remove anything not in the standard alphabet (a-z) code = re.sub(r'[^a-z]', '', code) # remove final e if code.endswith("e"): code = code[:-1] # if the name starts with cough, rough, tough, enough or trough -> cou2f (rou2f, tou2f, enou2f, trough) code = re.sub(r'^([crt]|(en)|(tr))ough', r'\1ou2f', code) # if the name starts with gn -> 2n code = re.sub(r'^gn', r'2n', code) # if the name ends with mb -> m2 code = re.sub(r'mb$', r'm2', code) # replace cq -> 2q code = re.sub(r'cq', r'2q', code) # replace c[i,e,y] -> s[i,e,y] code = re.sub(r'c([iey])', r's\1', code) # replace tch -> 2ch code = re.sub(r'tch', r'2ch', code) # replace c,q,x -> k code = re.sub(r'[cqx]', r'k', code) # replace v -> f code = re.sub(r'v', r'f', code) # replace dg -> 2g code = re.sub(r'dg', r'2g', code) # replace ti[o,a] -> si[o,a] code = re.sub(r'ti([oa])', r'si\1', code) # replace d -> t code = re.sub(r'd', r't', code) # replace ph -> fh code = re.sub(r'ph', r'fh', code) # replace b -> p code = re.sub(r'b', r'p', code) # replace sh -> s2 code = re.sub(r'sh', r's2', code) # replace z -> s code = re.sub(r'z', r's', code) # replace initial vowel [aeiou] -> A code = re.sub(r'^[aeiou]', r'A', code) # replace all other vowels [aeiou] -> 3 code = re.sub(r'[aeiou]', r'3', code) # replace j -> y code = re.sub(r'j', r'y', code) # replace an initial y3 -> Y3 code = re.sub(r'^y3', r'Y3', code) # replace an initial y -> A code = re.sub(r'^y', r'A', code) # replace y -> 3 code = re.sub(r'y', r'3', code) # replace 3gh3 -> 3kh3 code = re.sub(r'3gh3', r'3kh3', code) # replace gh -> 22 code = re.sub(r'gh', r'22', code) # replace g -> k code = re.sub(r'g', r'k', code) # replace groups of s,t,p,k,f,m,n by its single, upper-case equivalent for single_letter in ["s", "t", "p", "k", "f", "m", "n"]: otherParts = re.split(single_letter + "+", code) code = string.join(otherParts, string.upper(single_letter)) # replace w[3,h3] by W[3,h3] code = re.sub(r'w(h?3)', r'W\1', code) # replace final w with 3 code = re.sub(r'w$', r'3', code) # replace w -> 2 code = re.sub(r'w', r'2', code) # replace h at the beginning with an A code = re.sub(r'^h', r'A', code) # replace all other occurrences of h with a 2 code = re.sub(r'h', r'2', code) # replace r3 with R3 code = re.sub(r'r3', r'R3', code) # replace final r -> 3 code = re.sub(r'r$', r'3', code) # replace r with 2 code = re.sub(r'r', r'2', code) # replace l3 with L3 code = re.sub(r'l3', r'L3', code) # replace final l -> 3 code = re.sub(r'l$', r'3', code) # replace l with 2 code = re.sub(r'l', r'2', code) # remove all 2's code = re.sub(r'2', r'', code) # replace the final 3 -> A code = re.sub(r'3$', r'A', code) # remove all 3's code = re.sub(r'3', r'', code) # extend the code by 10 '1' (one) code += '1' * 10 # take the first 10 characters caverphoneCode = code[:10] # return caverphone code return caverphoneCode
[ "def", "caverphone", "(", "term", ")", ":", "# Developed at the University of Otago, New Zealand.", "# Project: Caversham Project (http://caversham.otago.ac.nz)", "# Developer: David Hood, University of Otago, New Zealand", "# Contact: caversham@otago.ac.nz", "# Project Technical Paper: http://c...
https://github.com/japerk/nltk-trainer/blob/1d48784a6e7558641ed40875d426fe376d41e11c/nltk_trainer/featx/phonetics.py#L441-L597
materialsproject/fireworks
83a907c19baf2a5c9fdcf63996f9797c3c85b785
fireworks/core/launchpad.py
python
LazyFirework.__init__
(self, fw_id, fw_coll, launch_coll, fallback_fs)
Args: fw_id (int): firework id fw_coll (pymongo.collection): fireworks collection launch_coll (pymongo.collection): launches collection
Args: fw_id (int): firework id fw_coll (pymongo.collection): fireworks collection launch_coll (pymongo.collection): launches collection
[ "Args", ":", "fw_id", "(", "int", ")", ":", "firework", "id", "fw_coll", "(", "pymongo", ".", "collection", ")", ":", "fireworks", "collection", "launch_coll", "(", "pymongo", ".", "collection", ")", ":", "launches", "collection" ]
def __init__(self, fw_id, fw_coll, launch_coll, fallback_fs): """ Args: fw_id (int): firework id fw_coll (pymongo.collection): fireworks collection launch_coll (pymongo.collection): launches collection """ # This is the only attribute known w/o a DB query self.fw_id = fw_id self._fwc, self._lc, self._ffs = fw_coll, launch_coll, fallback_fs self._launches = {k: False for k in self.db_launch_fields} self._fw, self._lids, self._state = None, None, None
[ "def", "__init__", "(", "self", ",", "fw_id", ",", "fw_coll", ",", "launch_coll", ",", "fallback_fs", ")", ":", "# This is the only attribute known w/o a DB query", "self", ".", "fw_id", "=", "fw_id", "self", ".", "_fwc", ",", "self", ".", "_lc", ",", "self", ...
https://github.com/materialsproject/fireworks/blob/83a907c19baf2a5c9fdcf63996f9797c3c85b785/fireworks/core/launchpad.py#L2044-L2055
open-mmlab/mmclassification
5232965b17b6c050f9b328b3740c631ed4034624
mmcls/core/evaluation/eval_metrics.py
python
f1_score
(pred, target, average_mode='macro', thrs=0.)
return f1_scores
Calculate F1 score according to the prediction and target. Args: pred (torch.Tensor | np.array): The model prediction with shape (N, C). target (torch.Tensor | np.array): The target of each prediction with shape (N, 1) or (N,). average_mode (str): The type of averaging performed on the result. Options are 'macro' and 'none'. If 'none', the scores for each class are returned. If 'macro', calculate metrics for each class, and find their unweighted mean. Defaults to 'macro'. thrs (Number | tuple[Number], optional): Predictions with scores under the thresholds are considered negative. Default to 0. Returns: float | np.array | list[float | np.array]: F1 score. +----------------------------+--------------------+-------------------+ | Args | ``thrs`` is number | ``thrs`` is tuple | +============================+====================+===================+ | ``average_mode`` = "macro" | float | list[float] | +----------------------------+--------------------+-------------------+ | ``average_mode`` = "none" | np.array | list[np.array] | +----------------------------+--------------------+-------------------+
Calculate F1 score according to the prediction and target.
[ "Calculate", "F1", "score", "according", "to", "the", "prediction", "and", "target", "." ]
def f1_score(pred, target, average_mode='macro', thrs=0.): """Calculate F1 score according to the prediction and target. Args: pred (torch.Tensor | np.array): The model prediction with shape (N, C). target (torch.Tensor | np.array): The target of each prediction with shape (N, 1) or (N,). average_mode (str): The type of averaging performed on the result. Options are 'macro' and 'none'. If 'none', the scores for each class are returned. If 'macro', calculate metrics for each class, and find their unweighted mean. Defaults to 'macro'. thrs (Number | tuple[Number], optional): Predictions with scores under the thresholds are considered negative. Default to 0. Returns: float | np.array | list[float | np.array]: F1 score. +----------------------------+--------------------+-------------------+ | Args | ``thrs`` is number | ``thrs`` is tuple | +============================+====================+===================+ | ``average_mode`` = "macro" | float | list[float] | +----------------------------+--------------------+-------------------+ | ``average_mode`` = "none" | np.array | list[np.array] | +----------------------------+--------------------+-------------------+ """ _, _, f1_scores = precision_recall_f1(pred, target, average_mode, thrs) return f1_scores
[ "def", "f1_score", "(", "pred", ",", "target", ",", "average_mode", "=", "'macro'", ",", "thrs", "=", "0.", ")", ":", "_", ",", "_", ",", "f1_scores", "=", "precision_recall_f1", "(", "pred", ",", "target", ",", "average_mode", ",", "thrs", ")", "retur...
https://github.com/open-mmlab/mmclassification/blob/5232965b17b6c050f9b328b3740c631ed4034624/mmcls/core/evaluation/eval_metrics.py#L198-L225
openedx/edx-platform
68dd185a0ab45862a2a61e0f803d7e03d2be71b5
openedx/features/enterprise_support/signals.py
python
handle_enterprise_learner_passing_grade
(sender, user, course_id, **kwargs)
Listen for a learner passing a course, transmit data to relevant integrated channel
Listen for a learner passing a course, transmit data to relevant integrated channel
[ "Listen", "for", "a", "learner", "passing", "a", "course", "transmit", "data", "to", "relevant", "integrated", "channel" ]
def handle_enterprise_learner_passing_grade(sender, user, course_id, **kwargs): # pylint: disable=unused-argument """ Listen for a learner passing a course, transmit data to relevant integrated channel """ if is_enterprise_learner(user): kwargs = { 'username': str(user.username), 'course_run_id': str(course_id) } transmit_single_learner_data.apply_async(kwargs=kwargs)
[ "def", "handle_enterprise_learner_passing_grade", "(", "sender", ",", "user", ",", "course_id", ",", "*", "*", "kwargs", ")", ":", "# pylint: disable=unused-argument", "if", "is_enterprise_learner", "(", "user", ")", ":", "kwargs", "=", "{", "'username'", ":", "st...
https://github.com/openedx/edx-platform/blob/68dd185a0ab45862a2a61e0f803d7e03d2be71b5/openedx/features/enterprise_support/signals.py#L60-L70
huggingface/transformers
623b4f7c63f60cce917677ee704d6c93ee960b4b
examples/research_projects/quantization-qdqbert/quant_trainer.py
python
finish_calibration
(model, args)
Disable calibration and load amax for all "*_input_quantizer modules in model.
Disable calibration and load amax for all "*_input_quantizer modules in model.
[ "Disable", "calibration", "and", "load", "amax", "for", "all", "*", "_input_quantizer", "modules", "in", "model", "." ]
def finish_calibration(model, args): """Disable calibration and load amax for all "*_input_quantizer modules in model.""" logger.info("Loading calibrated amax") for name, module in model.named_modules(): if name.endswith("_quantizer"): if module._calibrator is not None: if isinstance(module._calibrator, calib.MaxCalibrator): module.load_calib_amax() else: module.load_calib_amax("percentile", percentile=args.percentile) module.enable_quant() module.disable_calib() else: module.enable() model.cuda() print_quant_summary(model)
[ "def", "finish_calibration", "(", "model", ",", "args", ")", ":", "logger", ".", "info", "(", "\"Loading calibrated amax\"", ")", "for", "name", ",", "module", "in", "model", ".", "named_modules", "(", ")", ":", "if", "name", ".", "endswith", "(", "\"_quan...
https://github.com/huggingface/transformers/blob/623b4f7c63f60cce917677ee704d6c93ee960b4b/examples/research_projects/quantization-qdqbert/quant_trainer.py#L128-L144
linxid/Machine_Learning_Study_Path
558e82d13237114bbb8152483977806fc0c222af
Machine Learning In Action/Chapter4-NaiveBayes/venv/Lib/site-packages/pip/_vendor/cachecontrol/caches/file_cache.py
python
FileCache.delete
(self, key)
[]
def delete(self, key): name = self._fn(key) if not self.forever: os.remove(name)
[ "def", "delete", "(", "self", ",", "key", ")", ":", "name", "=", "self", ".", "_fn", "(", "key", ")", "if", "not", "self", ".", "forever", ":", "os", ".", "remove", "(", "name", ")" ]
https://github.com/linxid/Machine_Learning_Study_Path/blob/558e82d13237114bbb8152483977806fc0c222af/Machine Learning In Action/Chapter4-NaiveBayes/venv/Lib/site-packages/pip/_vendor/cachecontrol/caches/file_cache.py#L104-L107
mathics/Mathics
318e06dea8f1c70758a50cb2f95c9900150e3a68
mathics/core/util.py
python
subsets_2
(items, min, max, without_duplicates=True)
max may only be 1 or None (= infinity). Respects include property of items
max may only be 1 or None (= infinity). Respects include property of items
[ "max", "may", "only", "be", "1", "or", "None", "(", "=", "infinity", ")", ".", "Respects", "include", "property", "of", "items" ]
def subsets_2(items, min, max, without_duplicates=True): """max may only be 1 or None (= infinity). Respects include property of items """ if min <= max == 1: for index in range(len(items)): if items[index].include: yield [items[index]], ([], items[:index] + items[index + 1 :]) if min == 0: yield [], ([], items) else: counts = {} for item in items: if item.include: if item in counts: counts[item] += 1 else: counts[item] = 1 already = set() def decide(chosen, not_chosen, rest): if not rest: if len(chosen) >= min: """if False and len(chosen) > 1 and ( permutate_until is None or len(chosen) <= permutate_until): for perm in permutations(chosen): yield perm, ([], not_chosen) else:""" yield chosen, ([], not_chosen) else: if rest[0].include: for set in decide(chosen + [rest[0]], not_chosen, rest[1:]): yield set for set in decide(chosen, not_chosen + [rest[0]], rest[1:]): yield set for subset in decide([], [], list(counts.keys())): t = tuple(subset[0]) if t not in already: yield subset already.add(t) else: print("already taken")
[ "def", "subsets_2", "(", "items", ",", "min", ",", "max", ",", "without_duplicates", "=", "True", ")", ":", "if", "min", "<=", "max", "==", "1", ":", "for", "index", "in", "range", "(", "len", "(", "items", ")", ")", ":", "if", "items", "[", "ind...
https://github.com/mathics/Mathics/blob/318e06dea8f1c70758a50cb2f95c9900150e3a68/mathics/core/util.py#L125-L169
mars-project/mars
6afd7ed86db77f29cc9470485698ef192ecc6d33
mars/dataframe/indexing/at.py
python
at
(a)
return DataFrameAt(a)
Access a single value for a row/column label pair. Similar to ``loc``, in that both provide label-based lookups. Use ``at`` if you only need to get or set a single value in a DataFrame or Series. Raises ------ KeyError If 'label' does not exist in DataFrame. See Also -------- DataFrame.iat : Access a single value for a row/column pair by integer position. DataFrame.loc : Access a group of rows and columns by label(s). Series.at : Access a single value using a label. Examples -------- >>> import mars.dataframe as md >>> df = md.DataFrame([[0, 2, 3], [0, 4, 1], [10, 20, 30]], ... index=[4, 5, 6], columns=['A', 'B', 'C']) >>> df.execute() A B C 4 0 2 3 5 0 4 1 6 10 20 30 Get value at specified row/column pair >>> df.at[4, 'B'].execute() 2 # Set value at specified row/column pair # # >>> df.at[4, 'B'] = 10 # >>> df.at[4, 'B'] # 10 Get value within a Series >>> df.loc[5].at['B'].execute() 4
Access a single value for a row/column label pair.
[ "Access", "a", "single", "value", "for", "a", "row", "/", "column", "label", "pair", "." ]
def at(a): """ Access a single value for a row/column label pair. Similar to ``loc``, in that both provide label-based lookups. Use ``at`` if you only need to get or set a single value in a DataFrame or Series. Raises ------ KeyError If 'label' does not exist in DataFrame. See Also -------- DataFrame.iat : Access a single value for a row/column pair by integer position. DataFrame.loc : Access a group of rows and columns by label(s). Series.at : Access a single value using a label. Examples -------- >>> import mars.dataframe as md >>> df = md.DataFrame([[0, 2, 3], [0, 4, 1], [10, 20, 30]], ... index=[4, 5, 6], columns=['A', 'B', 'C']) >>> df.execute() A B C 4 0 2 3 5 0 4 1 6 10 20 30 Get value at specified row/column pair >>> df.at[4, 'B'].execute() 2 # Set value at specified row/column pair # # >>> df.at[4, 'B'] = 10 # >>> df.at[4, 'B'] # 10 Get value within a Series >>> df.loc[5].at['B'].execute() 4 """ return DataFrameAt(a)
[ "def", "at", "(", "a", ")", ":", "return", "DataFrameAt", "(", "a", ")" ]
https://github.com/mars-project/mars/blob/6afd7ed86db77f29cc9470485698ef192ecc6d33/mars/dataframe/indexing/at.py#L36-L83
w-digital-scanner/w9scan
aa725571897f095635c4b7660db5ce90c655946c
w9scan.py
python
modulePath
()
return getUnicode(os.path.dirname(os.path.realpath(_)), encoding=sys.getfilesystemencoding())
This will get us the program's directory, even if we are frozen using py2exe
This will get us the program's directory, even if we are frozen using py2exe
[ "This", "will", "get", "us", "the", "program", "s", "directory", "even", "if", "we", "are", "frozen", "using", "py2exe" ]
def modulePath(): """ This will get us the program's directory, even if we are frozen using py2exe """ try: _ = sys.executable if weAreFrozen() else __file__ except NameError: _ = inspect.getsourcefile(modulePath) return getUnicode(os.path.dirname(os.path.realpath(_)), encoding=sys.getfilesystemencoding())
[ "def", "modulePath", "(", ")", ":", "try", ":", "_", "=", "sys", ".", "executable", "if", "weAreFrozen", "(", ")", "else", "__file__", "except", "NameError", ":", "_", "=", "inspect", ".", "getsourcefile", "(", "modulePath", ")", "return", "getUnicode", ...
https://github.com/w-digital-scanner/w9scan/blob/aa725571897f095635c4b7660db5ce90c655946c/w9scan.py#L33-L44
home-assistant/core
265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1
homeassistant/components/smappee/switch.py
python
SmappeeActuator.turn_on
(self, **kwargs)
Turn on Comport Plug.
Turn on Comport Plug.
[ "Turn", "on", "Comport", "Plug", "." ]
def turn_on(self, **kwargs): """Turn on Comport Plug.""" if self._actuator_type in ("SWITCH", "COMFORT_PLUG"): self._service_location.set_actuator_state(self._actuator_id, state="ON_ON") elif self._actuator_type == "INFINITY_OUTPUT_MODULE": self._service_location.set_actuator_state( self._actuator_id, state=self._actuator_state_option )
[ "def", "turn_on", "(", "self", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "_actuator_type", "in", "(", "\"SWITCH\"", ",", "\"COMFORT_PLUG\"", ")", ":", "self", ".", "_service_location", ".", "set_actuator_state", "(", "self", ".", "_actuator_id", ...
https://github.com/home-assistant/core/blob/265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1/homeassistant/components/smappee/switch.py#L111-L118
py2neo-org/py2neo
2e46bbf4d622f53282e796ffc521fc4bc6d0b60d
py2neo/ogm/__init__.py
python
RelatedObjects.add
(self, obj, properties=None, **kwproperties)
return 1
Add or update a related object. This method returns the number of new related objects that were added: 0 if an existing object was updated, or 1 if a new object was added. :param obj: :py:class:`.Model` to relate. :param properties: Dictionary of properties to attach to the relationship (optional). :param kwproperties: Additional keyword properties (optional). :returns: Number of new related objects that were added.
Add or update a related object.
[ "Add", "or", "update", "a", "related", "object", "." ]
def add(self, obj, properties=None, **kwproperties): """ Add or update a related object. This method returns the number of new related objects that were added: 0 if an existing object was updated, or 1 if a new object was added. :param obj: :py:class:`.Model` to relate. :param properties: Dictionary of properties to attach to the relationship (optional). :param kwproperties: Additional keyword properties (optional). :returns: Number of new related objects that were added. """ if not isinstance(obj, Model): raise TypeError("Related objects must be Model instances") related_objects = self._related_objects properties = dict(properties or {}, **kwproperties) for i, (related_object, p) in enumerate(related_objects): if related_object == obj: related_objects[i] = (obj, PropertyDict(p, **properties)) return 0 # existing object was updated related_objects.append((obj, properties)) return 1
[ "def", "add", "(", "self", ",", "obj", ",", "properties", "=", "None", ",", "*", "*", "kwproperties", ")", ":", "if", "not", "isinstance", "(", "obj", ",", "Model", ")", ":", "raise", "TypeError", "(", "\"Related objects must be Model instances\"", ")", "r...
https://github.com/py2neo-org/py2neo/blob/2e46bbf4d622f53282e796ffc521fc4bc6d0b60d/py2neo/ogm/__init__.py#L251-L277
TensorMSA/tensormsa
c36b565159cd934533636429add3c7d7263d622b
cluster/preprocess/pre_node_feed_img2cnn.py
python
PreNodeFeedImg2Cnn.run
(self, conf_data)
override init class
override init class
[ "override", "init", "class" ]
def run(self, conf_data): """ override init class """ super(PreNodeFeedImg2Cnn, self).run(conf_data) self._init_node_parm(conf_data['node_id'])
[ "def", "run", "(", "self", ",", "conf_data", ")", ":", "super", "(", "PreNodeFeedImg2Cnn", ",", "self", ")", ".", "run", "(", "conf_data", ")", "self", ".", "_init_node_parm", "(", "conf_data", "[", "'node_id'", "]", ")" ]
https://github.com/TensorMSA/tensormsa/blob/c36b565159cd934533636429add3c7d7263d622b/cluster/preprocess/pre_node_feed_img2cnn.py#L9-L14
aws-cloudformation/cfn-lint
16df5d0ca0d8ebcf9330ebea701e83d883b47217
src/cfnlint/rules/resources/events/RuleTargetsLimit.py
python
RuleTargetsLimit.match_resource_properties
(self, properties, _, path, cfn)
return matches
Check CloudFormation Properties
Check CloudFormation Properties
[ "Check", "CloudFormation", "Properties" ]
def match_resource_properties(self, properties, _, path, cfn): """Check CloudFormation Properties""" matches = [] matches.extend( cfn.check_value( obj=properties, key='Targets', path=path[:], check_value=self.check_value )) for _, limit in self.limits.items(): if limit['count'] > self.max_count: message = 'An Events Rule can have up to {0} Targets' matches.append(RuleMatch(limit['path'], message.format(self.max_count))) return matches
[ "def", "match_resource_properties", "(", "self", ",", "properties", ",", "_", ",", "path", ",", "cfn", ")", ":", "matches", "=", "[", "]", "matches", ".", "extend", "(", "cfn", ".", "check_value", "(", "obj", "=", "properties", ",", "key", "=", "'Targe...
https://github.com/aws-cloudformation/cfn-lint/blob/16df5d0ca0d8ebcf9330ebea701e83d883b47217/src/cfnlint/rules/resources/events/RuleTargetsLimit.py#L45-L60
stanfordmlgroup/nlc
af40dc1451cd9fe9d58e947ca6093d0530794fad
nlc_data.py
python
maybe_download
(directory, filename, url)
return filepath
Download filename from url unless it's already in directory.
Download filename from url unless it's already in directory.
[ "Download", "filename", "from", "url", "unless", "it", "s", "already", "in", "directory", "." ]
def maybe_download(directory, filename, url): """Download filename from url unless it's already in directory.""" if not os.path.exists(directory): print("Creating directory %s" % directory) os.mkdir(directory) filepath = os.path.join(directory, filename) if not os.path.exists(filepath): print("Downloading %s to %s" % (url, filepath)) filepath, _ = urllib.request.urlretrieve(url, filepath) statinfo = os.stat(filepath) print("Succesfully downloaded", filename, statinfo.st_size, "bytes") return filepath
[ "def", "maybe_download", "(", "directory", ",", "filename", ",", "url", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "directory", ")", ":", "print", "(", "\"Creating directory %s\"", "%", "directory", ")", "os", ".", "mkdir", "(", "direc...
https://github.com/stanfordmlgroup/nlc/blob/af40dc1451cd9fe9d58e947ca6093d0530794fad/nlc_data.py#L51-L62
chaoss/grimoirelab-perceval
ba19bfd5e40bffdd422ca8e68526326b47f97491
perceval/backends/core/pagure.py
python
PagureClient.__get_url_namespace_repository
(self)
return urijoin(self.base_url, self.namespace, self.repository)
Build URL for a repository within a namespace
Build URL for a repository within a namespace
[ "Build", "URL", "for", "a", "repository", "within", "a", "namespace" ]
def __get_url_namespace_repository(self): """Build URL for a repository within a namespace""" return urijoin(self.base_url, self.namespace, self.repository)
[ "def", "__get_url_namespace_repository", "(", "self", ")", ":", "return", "urijoin", "(", "self", ".", "base_url", ",", "self", ".", "namespace", ",", "self", ".", "repository", ")" ]
https://github.com/chaoss/grimoirelab-perceval/blob/ba19bfd5e40bffdd422ca8e68526326b47f97491/perceval/backends/core/pagure.py#L380-L383
wbond/asn1crypto
9ae350f212532dfee7f185f6b3eda24753249cf3
asn1crypto/core.py
python
AbstractString._copy
(self, other, copy_func)
Copies the contents of another AbstractString object to itself :param object: Another instance of the same class :param copy_func: An reference of copy.copy() or copy.deepcopy() to use when copying lists, dicts and objects
Copies the contents of another AbstractString object to itself
[ "Copies", "the", "contents", "of", "another", "AbstractString", "object", "to", "itself" ]
def _copy(self, other, copy_func): """ Copies the contents of another AbstractString object to itself :param object: Another instance of the same class :param copy_func: An reference of copy.copy() or copy.deepcopy() to use when copying lists, dicts and objects """ super(AbstractString, self)._copy(other, copy_func) self._unicode = other._unicode
[ "def", "_copy", "(", "self", ",", "other", ",", "copy_func", ")", ":", "super", "(", "AbstractString", ",", "self", ")", ".", "_copy", "(", "other", ",", "copy_func", ")", "self", ".", "_unicode", "=", "other", ".", "_unicode" ]
https://github.com/wbond/asn1crypto/blob/9ae350f212532dfee7f185f6b3eda24753249cf3/asn1crypto/core.py#L1817-L1830
lovelylain/pyctp
fd304de4b50c4ddc31a4190b1caaeb5dec66bc5d
stock/ctp/ApiStruct.py
python
MarketDataAveragePrice.__init__
(self, AveragePrice=0.0)
[]
def __init__(self, AveragePrice=0.0): self.AveragePrice = 'Price'
[ "def", "__init__", "(", "self", ",", "AveragePrice", "=", "0.0", ")", ":", "self", ".", "AveragePrice", "=", "'Price'" ]
https://github.com/lovelylain/pyctp/blob/fd304de4b50c4ddc31a4190b1caaeb5dec66bc5d/stock/ctp/ApiStruct.py#L3152-L3153
DataDog/integrations-core
934674b29d94b70ccc008f76ea172d0cdae05e1e
airflow/datadog_checks/airflow/config_models/defaults.py
python
instance_tls_ignore_warning
(field, value)
return False
[]
def instance_tls_ignore_warning(field, value): return False
[ "def", "instance_tls_ignore_warning", "(", "field", ",", "value", ")", ":", "return", "False" ]
https://github.com/DataDog/integrations-core/blob/934674b29d94b70ccc008f76ea172d0cdae05e1e/airflow/datadog_checks/airflow/config_models/defaults.py#L157-L158
googleworkspace/hangouts-chat-samples
cacaba5094864150f23d4fab1fb0c7e418ad2c80
python/card-bot/main.py
python
respond_to_interactive_card_click
(action_name, custom_params)
return { 'actionResponse': { 'type': action_response }, 'cards': [ { 'header': { 'title': BOT_HEADER, 'subtitle': 'Interactive card clicked', 'imageUrl': 'https://goo.gl/5obRKj', 'imageStyle': 'IMAGE' } }, { 'sections': [ { 'widgets': [ { 'textParagraph': { 'text': message } }, { 'keyValue': { 'topLabel': 'Original message', 'content': original_message } } ] } ] } ] }
Creates a response for when the user clicks on an interactive card. See the guide for creating interactive cards https://developers.google.com/hangouts/chat/how-tos/cards-onclick Args: action_name: the name of the custom action defined in the original bot response custom_params: the parameters defined in the original bot response
Creates a response for when the user clicks on an interactive card.
[ "Creates", "a", "response", "for", "when", "the", "user", "clicks", "on", "an", "interactive", "card", "." ]
def respond_to_interactive_card_click(action_name, custom_params): """Creates a response for when the user clicks on an interactive card. See the guide for creating interactive cards https://developers.google.com/hangouts/chat/how-tos/cards-onclick Args: action_name: the name of the custom action defined in the original bot response custom_params: the parameters defined in the original bot response """ message = 'You clicked {}'.format( 'a text button' if action_name == INTERACTIVE_TEXT_BUTTON_ACTION else 'an image button') original_message = "" if custom_params[0]['key'] == INTERACTIVE_BUTTON_PARAMETER_KEY: original_message = custom_params[0]['value'] else: original_message = '<i>Cannot determine original message</i>' # If you want to respond to the same room but with a new message, # change the following value to NEW_MESSAGE. action_response = 'UPDATE_MESSAGE' return { 'actionResponse': { 'type': action_response }, 'cards': [ { 'header': { 'title': BOT_HEADER, 'subtitle': 'Interactive card clicked', 'imageUrl': 'https://goo.gl/5obRKj', 'imageStyle': 'IMAGE' } }, { 'sections': [ { 'widgets': [ { 'textParagraph': { 'text': message } }, { 'keyValue': { 'topLabel': 'Original message', 'content': original_message } } ] } ] } ] }
[ "def", "respond_to_interactive_card_click", "(", "action_name", ",", "custom_params", ")", ":", "message", "=", "'You clicked {}'", ".", "format", "(", "'a text button'", "if", "action_name", "==", "INTERACTIVE_TEXT_BUTTON_ACTION", "else", "'an image button'", ")", "origi...
https://github.com/googleworkspace/hangouts-chat-samples/blob/cacaba5094864150f23d4fab1fb0c7e418ad2c80/python/card-bot/main.py#L220-L279
ChineseGLUE/ChineseGLUE
1591b85cf5427c2ff60f718d359ecb71d2b44879
baselines/models_pytorch/classifier_pytorch/transformers/tokenization_bert.py
python
_is_whitespace
(char)
return False
Checks whether `chars` is a whitespace character.
Checks whether `chars` is a whitespace character.
[ "Checks", "whether", "chars", "is", "a", "whitespace", "character", "." ]
def _is_whitespace(char): """Checks whether `chars` is a whitespace character.""" # \t, \n, and \r are technically contorl characters but we treat them # as whitespace since they are generally considered as such. if char == " " or char == "\t" or char == "\n" or char == "\r": return True cat = unicodedata.category(char) if cat == "Zs": return True return False
[ "def", "_is_whitespace", "(", "char", ")", ":", "# \\t, \\n, and \\r are technically contorl characters but we treat them", "# as whitespace since they are generally considered as such.", "if", "char", "==", "\" \"", "or", "char", "==", "\"\\t\"", "or", "char", "==", "\"\\n\"",...
https://github.com/ChineseGLUE/ChineseGLUE/blob/1591b85cf5427c2ff60f718d359ecb71d2b44879/baselines/models_pytorch/classifier_pytorch/transformers/tokenization_bert.py#L465-L474
mchristopher/PokemonGo-DesktopMap
ec37575f2776ee7d64456e2a1f6b6b78830b4fe0
app/pywin/Lib/mimetypes.py
python
MimeTypes.guess_all_extensions
(self, type, strict=True)
return extensions
Guess the extensions for a file based on its MIME type. Return value is a list of strings giving the possible filename extensions, including the leading dot ('.'). The extension is not guaranteed to have been associated with any particular data stream, but would be mapped to the MIME type `type' by guess_type(). Optional `strict' argument when false adds a bunch of commonly found, but non-standard types.
Guess the extensions for a file based on its MIME type.
[ "Guess", "the", "extensions", "for", "a", "file", "based", "on", "its", "MIME", "type", "." ]
def guess_all_extensions(self, type, strict=True): """Guess the extensions for a file based on its MIME type. Return value is a list of strings giving the possible filename extensions, including the leading dot ('.'). The extension is not guaranteed to have been associated with any particular data stream, but would be mapped to the MIME type `type' by guess_type(). Optional `strict' argument when false adds a bunch of commonly found, but non-standard types. """ type = type.lower() extensions = self.types_map_inv[True].get(type, []) if not strict: for ext in self.types_map_inv[False].get(type, []): if ext not in extensions: extensions.append(ext) return extensions
[ "def", "guess_all_extensions", "(", "self", ",", "type", ",", "strict", "=", "True", ")", ":", "type", "=", "type", ".", "lower", "(", ")", "extensions", "=", "self", ".", "types_map_inv", "[", "True", "]", ".", "get", "(", "type", ",", "[", "]", "...
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/ec37575f2776ee7d64456e2a1f6b6b78830b4fe0/app/pywin/Lib/mimetypes.py#L157-L174
pyexcel-webwares/Flask-Excel
cae311b069998f5c238c0c0467348bb95e4745d4
setup.py
python
read_files
(*files)
return text
Read files into setup
Read files into setup
[ "Read", "files", "into", "setup" ]
def read_files(*files): """Read files into setup""" text = "" for single_file in files: content = read(single_file) text = text + content + "\n" return text
[ "def", "read_files", "(", "*", "files", ")", ":", "text", "=", "\"\"", "for", "single_file", "in", "files", ":", "content", "=", "read", "(", "single_file", ")", "text", "=", "text", "+", "content", "+", "\"\\n\"", "return", "text" ]
https://github.com/pyexcel-webwares/Flask-Excel/blob/cae311b069998f5c238c0c0467348bb95e4745d4/setup.py#L162-L168
IndicoDataSolutions/finetune
83ba222eed331df64b2fa7157bb64f0a2eef4a2c
finetune/util/group_metrics.py
python
attach_entities
(groups, entities)
return groups
Attaches a documents entities to the documents groups :param groups: A list of groups :param entities: A list of entities :return: A copy of the groups param with an additional "entities" key added to each group containing all entities that appear within the group
Attaches a documents entities to the documents groups
[ "Attaches", "a", "documents", "entities", "to", "the", "documents", "groups" ]
def attach_entities(groups, entities): """ Attaches a documents entities to the documents groups :param groups: A list of groups :param entities: A list of entities :return: A copy of the groups param with an additional "entities" key added to each group containing all entities that appear within the group """ # Copy so we don't modify input groups = deepcopy(groups) for group in groups: group["entities"] = [] for entity in entities: if entity_in_group(entity, group): group["entities"].append(entity) return groups
[ "def", "attach_entities", "(", "groups", ",", "entities", ")", ":", "# Copy so we don't modify input", "groups", "=", "deepcopy", "(", "groups", ")", "for", "group", "in", "groups", ":", "group", "[", "\"entities\"", "]", "=", "[", "]", "for", "entity", "in"...
https://github.com/IndicoDataSolutions/finetune/blob/83ba222eed331df64b2fa7157bb64f0a2eef4a2c/finetune/util/group_metrics.py#L470-L486
mateuszmalinowski/visual_turing_test-tutorial
69aace8075f110a3b58175c8cc5055e46fdf7028
kraino/utils/model_visualization.py
python
model_picture
(model, to_file='local/model.png')
[]
def model_picture(model, to_file='local/model.png'): graph = pydot.Dot(graph_type='digraph') if isinstance(model,Sequential): previous_node = None written_nodes = [] n = 1 for node in model.get_config()['layers']: # append number in case layers have same name to differentiate if (node['name'] + str(n)) in written_nodes: n += 1 current_node = pydot.Node(node['name'] + str(n)) written_nodes.append(node['name'] + str(n)) graph.add_node(current_node) if previous_node: graph.add_edge(pydot.Edge(previous_node, current_node)) previous_node = current_node graph.write_png(to_file) elif isinstance(model,Graph): # don't need to append number for names since all nodes labeled for input_node in model.input_config: graph.add_node(pydot.Node(input_node['name'])) # intermediate and output nodes have input defined for layer_config in [model.node_config, model.output_config]: for node in layer_config: graph.add_node(pydot.Node(node['name'])) # possible to have multiple 'inputs' vs 1 'input' if node['inputs']: for e in node['inputs']: graph.add_edge(pydot.Edge(e, node['name'])) else: graph.add_edge(pydot.Edge(node['input'], node['name'])) graph.write_png(to_file)
[ "def", "model_picture", "(", "model", ",", "to_file", "=", "'local/model.png'", ")", ":", "graph", "=", "pydot", ".", "Dot", "(", "graph_type", "=", "'digraph'", ")", "if", "isinstance", "(", "model", ",", "Sequential", ")", ":", "previous_node", "=", "Non...
https://github.com/mateuszmalinowski/visual_turing_test-tutorial/blob/69aace8075f110a3b58175c8cc5055e46fdf7028/kraino/utils/model_visualization.py#L13-L48
openhatch/oh-mainline
ce29352a034e1223141dcc2f317030bbc3359a51
vendor/packages/twisted/twisted/cred/credentials.py
python
DigestedCredentials.checkHash
(self, digestHash)
return expected == response
Verify that the credentials represented by this object agree with the credentials represented by the I{H(A1)} given in C{digestHash}. @param digestHash: A precomputed H(A1) value based on the username, realm, and password associate with this credentials object.
Verify that the credentials represented by this object agree with the credentials represented by the I{H(A1)} given in C{digestHash}.
[ "Verify", "that", "the", "credentials", "represented", "by", "this", "object", "agree", "with", "the", "credentials", "represented", "by", "the", "I", "{", "H", "(", "A1", ")", "}", "given", "in", "C", "{", "digestHash", "}", "." ]
def checkHash(self, digestHash): """ Verify that the credentials represented by this object agree with the credentials represented by the I{H(A1)} given in C{digestHash}. @param digestHash: A precomputed H(A1) value based on the username, realm, and password associate with this credentials object. """ response = self.fields.get('response') uri = self.fields.get('uri') nonce = self.fields.get('nonce') cnonce = self.fields.get('cnonce') nc = self.fields.get('nc') algo = self.fields.get('algorithm', 'md5').lower() qop = self.fields.get('qop', 'auth') expected = calcResponse( calcHA1(algo, None, None, None, nonce, cnonce, preHA1=digestHash), calcHA2(algo, self.method, uri, qop, None), algo, nonce, nc, cnonce, qop) return expected == response
[ "def", "checkHash", "(", "self", ",", "digestHash", ")", ":", "response", "=", "self", ".", "fields", ".", "get", "(", "'response'", ")", "uri", "=", "self", ".", "fields", ".", "get", "(", "'uri'", ")", "nonce", "=", "self", ".", "fields", ".", "g...
https://github.com/openhatch/oh-mainline/blob/ce29352a034e1223141dcc2f317030bbc3359a51/vendor/packages/twisted/twisted/cred/credentials.py#L147-L168
microsoft/azure-devops-python-api
451cade4c475482792cbe9e522c1fee32393139e
azure-devops/azure/devops/v5_1/service_hooks/service_hooks_client.py
python
ServiceHooksClient.list_consumer_actions
(self, consumer_id, publisher_id=None)
return self._deserialize('[ConsumerAction]', self._unwrap_collection(response))
ListConsumerActions. Get a list of consumer actions for a specific consumer. :param str consumer_id: ID for a consumer. :param str publisher_id: :rtype: [ConsumerAction]
ListConsumerActions. Get a list of consumer actions for a specific consumer. :param str consumer_id: ID for a consumer. :param str publisher_id: :rtype: [ConsumerAction]
[ "ListConsumerActions", ".", "Get", "a", "list", "of", "consumer", "actions", "for", "a", "specific", "consumer", ".", ":", "param", "str", "consumer_id", ":", "ID", "for", "a", "consumer", ".", ":", "param", "str", "publisher_id", ":", ":", "rtype", ":", ...
def list_consumer_actions(self, consumer_id, publisher_id=None): """ListConsumerActions. Get a list of consumer actions for a specific consumer. :param str consumer_id: ID for a consumer. :param str publisher_id: :rtype: [ConsumerAction] """ route_values = {} if consumer_id is not None: route_values['consumerId'] = self._serialize.url('consumer_id', consumer_id, 'str') query_parameters = {} if publisher_id is not None: query_parameters['publisherId'] = self._serialize.query('publisher_id', publisher_id, 'str') response = self._send(http_method='GET', location_id='c3428e90-7a69-4194-8ed8-0f153185ee0d', version='5.1', route_values=route_values, query_parameters=query_parameters) return self._deserialize('[ConsumerAction]', self._unwrap_collection(response))
[ "def", "list_consumer_actions", "(", "self", ",", "consumer_id", ",", "publisher_id", "=", "None", ")", ":", "route_values", "=", "{", "}", "if", "consumer_id", "is", "not", "None", ":", "route_values", "[", "'consumerId'", "]", "=", "self", ".", "_serialize...
https://github.com/microsoft/azure-devops-python-api/blob/451cade4c475482792cbe9e522c1fee32393139e/azure-devops/azure/devops/v5_1/service_hooks/service_hooks_client.py#L51-L69
nosmokingbandit/Watcher3
0217e75158b563bdefc8e01c3be7620008cf3977
lib/sqlalchemy/sql/elements.py
python
UnaryExpression._create_asc
(cls, column)
return UnaryExpression( _literal_as_label_reference(column), modifier=operators.asc_op, wraps_column_expression=False)
Produce an ascending ``ORDER BY`` clause element. e.g.:: from sqlalchemy import asc stmt = select([users_table]).order_by(asc(users_table.c.name)) will produce SQL as:: SELECT id, name FROM user ORDER BY name ASC The :func:`.asc` function is a standalone version of the :meth:`.ColumnElement.asc` method available on all SQL expressions, e.g.:: stmt = select([users_table]).order_by(users_table.c.name.asc()) :param column: A :class:`.ColumnElement` (e.g. scalar SQL expression) with which to apply the :func:`.asc` operation. .. seealso:: :func:`.desc` :func:`.nullsfirst` :func:`.nullslast` :meth:`.Select.order_by`
Produce an ascending ``ORDER BY`` clause element.
[ "Produce", "an", "ascending", "ORDER", "BY", "clause", "element", "." ]
def _create_asc(cls, column): """Produce an ascending ``ORDER BY`` clause element. e.g.:: from sqlalchemy import asc stmt = select([users_table]).order_by(asc(users_table.c.name)) will produce SQL as:: SELECT id, name FROM user ORDER BY name ASC The :func:`.asc` function is a standalone version of the :meth:`.ColumnElement.asc` method available on all SQL expressions, e.g.:: stmt = select([users_table]).order_by(users_table.c.name.asc()) :param column: A :class:`.ColumnElement` (e.g. scalar SQL expression) with which to apply the :func:`.asc` operation. .. seealso:: :func:`.desc` :func:`.nullsfirst` :func:`.nullslast` :meth:`.Select.order_by` """ return UnaryExpression( _literal_as_label_reference(column), modifier=operators.asc_op, wraps_column_expression=False)
[ "def", "_create_asc", "(", "cls", ",", "column", ")", ":", "return", "UnaryExpression", "(", "_literal_as_label_reference", "(", "column", ")", ",", "modifier", "=", "operators", ".", "asc_op", ",", "wraps_column_expression", "=", "False", ")" ]
https://github.com/nosmokingbandit/Watcher3/blob/0217e75158b563bdefc8e01c3be7620008cf3977/lib/sqlalchemy/sql/elements.py#L2673-L2709
dimagi/commcare-hq
d67ff1d3b4c51fa050c19e60c3253a79d3452a39
corehq/apps/reports/standard/cases/basic.py
python
CaseListMixin.shared_pagination_GET_params
(self)
return shared_params
[]
def shared_pagination_GET_params(self): shared_params = super(CaseListMixin, self).shared_pagination_GET_params shared_params.append(dict( name=SelectOpenCloseFilter.slug, value=self.request.GET.get(SelectOpenCloseFilter.slug, '') )) return shared_params
[ "def", "shared_pagination_GET_params", "(", "self", ")", ":", "shared_params", "=", "super", "(", "CaseListMixin", ",", "self", ")", ".", "shared_pagination_GET_params", "shared_params", ".", "append", "(", "dict", "(", "name", "=", "SelectOpenCloseFilter", ".", "...
https://github.com/dimagi/commcare-hq/blob/d67ff1d3b4c51fa050c19e60c3253a79d3452a39/corehq/apps/reports/standard/cases/basic.py#L133-L139
kanzure/nanoengineer
874e4c9f8a9190f093625b267f9767e19f82e6c4
cad/src/model/part.py
python
Part.ensure_toplevel_group
(self)
return
Make sure this Part's toplevel node is a Group (of a kind which does not mind having arbitrary new members added to it), by Grouping it if not. @note: most operations which create new nodes and want to add them needn't call this directly, since they can call self.addnode or assy.addnode instead.
Make sure this Part's toplevel node is a Group (of a kind which does not mind having arbitrary new members added to it), by Grouping it if not.
[ "Make", "sure", "this", "Part", "s", "toplevel", "node", "is", "a", "Group", "(", "of", "a", "kind", "which", "does", "not", "mind", "having", "arbitrary", "new", "members", "added", "to", "it", ")", "by", "Grouping", "it", "if", "not", "." ]
def ensure_toplevel_group(self): #bruce 080318 revised so unopenables like DnaStrand don't count """ Make sure this Part's toplevel node is a Group (of a kind which does not mind having arbitrary new members added to it), by Grouping it if not. @note: most operations which create new nodes and want to add them needn't call this directly, since they can call self.addnode or assy.addnode instead. """ topnode = self.topnode assert topnode is not None if not topnode.is_group() or not topnode.MT_DND_can_drop_inside(): # REVIEW: is that the best condition? Do we need an argument # to help us know what kinds of groups are acceptable here? # And if the current one is not, what kind to create? # [bruce 080318 comment, and revised condition] self.create_new_toplevel_group() return
[ "def", "ensure_toplevel_group", "(", "self", ")", ":", "#bruce 080318 revised so unopenables like DnaStrand don't count", "topnode", "=", "self", ".", "topnode", "assert", "topnode", "is", "not", "None", "if", "not", "topnode", ".", "is_group", "(", ")", "or", "not"...
https://github.com/kanzure/nanoengineer/blob/874e4c9f8a9190f093625b267f9767e19f82e6c4/cad/src/model/part.py#L942-L960
edisonlz/fastor
342078a18363ac41d3c6b1ab29dbdd44fdb0b7b3
base/site-packages/tencentcloud/cvm/v20170312/models.py
python
RenewInstancesResponse.__init__
(self)
:param RequestId: 唯一请求ID,每次请求都会返回。定位问题时需要提供该次请求的RequestId。 :type RequestId: str
:param RequestId: 唯一请求ID,每次请求都会返回。定位问题时需要提供该次请求的RequestId。 :type RequestId: str
[ ":", "param", "RequestId", ":", "唯一请求ID,每次请求都会返回。定位问题时需要提供该次请求的RequestId。", ":", "type", "RequestId", ":", "str" ]
def __init__(self): """ :param RequestId: 唯一请求ID,每次请求都会返回。定位问题时需要提供该次请求的RequestId。 :type RequestId: str """ self.RequestId = None
[ "def", "__init__", "(", "self", ")", ":", "self", ".", "RequestId", "=", "None" ]
https://github.com/edisonlz/fastor/blob/342078a18363ac41d3c6b1ab29dbdd44fdb0b7b3/base/site-packages/tencentcloud/cvm/v20170312/models.py#L3355-L3360
jazzband/django-analytical
8d449868da5b824c4028a5f34e9222bbbb4a0090
analytical/templatetags/olark.py
python
olark
(parser, token)
return OlarkNode()
Olark set-up template tag. Renders Javascript code to set-up Olark chat. You must supply your site ID in the ``OLARK_SITE_ID`` setting.
Olark set-up template tag.
[ "Olark", "set", "-", "up", "template", "tag", "." ]
def olark(parser, token): """ Olark set-up template tag. Renders Javascript code to set-up Olark chat. You must supply your site ID in the ``OLARK_SITE_ID`` setting. """ bits = token.split_contents() if len(bits) > 1: raise TemplateSyntaxError("'%s' takes no arguments" % bits[0]) return OlarkNode()
[ "def", "olark", "(", "parser", ",", "token", ")", ":", "bits", "=", "token", ".", "split_contents", "(", ")", "if", "len", "(", "bits", ")", ">", "1", ":", "raise", "TemplateSyntaxError", "(", "\"'%s' takes no arguments\"", "%", "bits", "[", "0", "]", ...
https://github.com/jazzband/django-analytical/blob/8d449868da5b824c4028a5f34e9222bbbb4a0090/analytical/templatetags/olark.py#L43-L53
cogitas3d/OrtogOnBlender
881e93f5beb2263e44c270974dd0e81deca44762
DesenhaObjetos.py
python
CriaBezierUnido.execute
(self, context)
return {'FINISHED'}
[]
def execute(self, context): CriaBezierUnidoDef(self, context) return {'FINISHED'}
[ "def", "execute", "(", "self", ",", "context", ")", ":", "CriaBezierUnidoDef", "(", "self", ",", "context", ")", "return", "{", "'FINISHED'", "}" ]
https://github.com/cogitas3d/OrtogOnBlender/blob/881e93f5beb2263e44c270974dd0e81deca44762/DesenhaObjetos.py#L1018-L1022
chiphuyen/stanford-tensorflow-tutorials
51e53daaa2a32cfe7a1966f060b28dbbd081791c
examples/word2vec_utils.py
python
most_common_words
(visual_fld, num_visualize)
create a list of num_visualize most frequent words to visualize on TensorBoard. saved to visualization/vocab_[num_visualize].tsv
create a list of num_visualize most frequent words to visualize on TensorBoard. saved to visualization/vocab_[num_visualize].tsv
[ "create", "a", "list", "of", "num_visualize", "most", "frequent", "words", "to", "visualize", "on", "TensorBoard", ".", "saved", "to", "visualization", "/", "vocab_", "[", "num_visualize", "]", ".", "tsv" ]
def most_common_words(visual_fld, num_visualize): """ create a list of num_visualize most frequent words to visualize on TensorBoard. saved to visualization/vocab_[num_visualize].tsv """ words = open(os.path.join(visual_fld, 'vocab.tsv'), 'r').readlines()[:num_visualize] words = [word for word in words] file = open(os.path.join(visual_fld, 'vocab_' + str(num_visualize) + '.tsv'), 'w') for word in words: file.write(word) file.close()
[ "def", "most_common_words", "(", "visual_fld", ",", "num_visualize", ")", ":", "words", "=", "open", "(", "os", ".", "path", ".", "join", "(", "visual_fld", ",", "'vocab.tsv'", ")", ",", "'r'", ")", ".", "readlines", "(", ")", "[", ":", "num_visualize", ...
https://github.com/chiphuyen/stanford-tensorflow-tutorials/blob/51e53daaa2a32cfe7a1966f060b28dbbd081791c/examples/word2vec_utils.py#L58-L67
readbeyond/aeneas
4d200a050690903b30b3d885b44714fecb23f18a
aeneas/globalfunctions.py
python
safe_str
(string)
return string
Safely return the given Unicode string from a ``__str__`` function: as a byte string in Python 2, or as a Unicode string in Python 3. :param string string: the string to return :rtype: bytes or string
Safely return the given Unicode string from a ``__str__`` function: as a byte string in Python 2, or as a Unicode string in Python 3.
[ "Safely", "return", "the", "given", "Unicode", "string", "from", "a", "__str__", "function", ":", "as", "a", "byte", "string", "in", "Python", "2", "or", "as", "a", "Unicode", "string", "in", "Python", "3", "." ]
def safe_str(string): """ Safely return the given Unicode string from a ``__str__`` function: as a byte string in Python 2, or as a Unicode string in Python 3. :param string string: the string to return :rtype: bytes or string """ if string is None: return None if PY2: return string.encode("utf-8") return string
[ "def", "safe_str", "(", "string", ")", ":", "if", "string", "is", "None", ":", "return", "None", "if", "PY2", ":", "return", "string", ".", "encode", "(", "\"utf-8\"", ")", "return", "string" ]
https://github.com/readbeyond/aeneas/blob/4d200a050690903b30b3d885b44714fecb23f18a/aeneas/globalfunctions.py#L1176-L1189
tdeboissiere/DeepLearningImplementations
5c4094880fc6992cca2d6e336463b2525026f6e2
DenseNet/densenet.py
python
denseblock_altern
(x, concat_axis, nb_layers, nb_filter, growth_rate, dropout_rate=None, weight_decay=1E-4)
return x, nb_filter
Build a denseblock where the output of each conv_factory is fed to subsequent ones. (Alternative of a above) :param x: keras model :param concat_axis: int -- index of contatenate axis :param nb_layers: int -- the number of layers of conv_ factory to append to the model. :param nb_filter: int -- number of filters :param dropout_rate: int -- dropout rate :param weight_decay: int -- weight decay factor :returns: keras model with nb_layers of conv_factory appended :rtype: keras model * The main difference between this implementation and the implementation above is that the one above
Build a denseblock where the output of each conv_factory is fed to subsequent ones. (Alternative of a above)
[ "Build", "a", "denseblock", "where", "the", "output", "of", "each", "conv_factory", "is", "fed", "to", "subsequent", "ones", ".", "(", "Alternative", "of", "a", "above", ")" ]
def denseblock_altern(x, concat_axis, nb_layers, nb_filter, growth_rate, dropout_rate=None, weight_decay=1E-4): """Build a denseblock where the output of each conv_factory is fed to subsequent ones. (Alternative of a above) :param x: keras model :param concat_axis: int -- index of contatenate axis :param nb_layers: int -- the number of layers of conv_ factory to append to the model. :param nb_filter: int -- number of filters :param dropout_rate: int -- dropout rate :param weight_decay: int -- weight decay factor :returns: keras model with nb_layers of conv_factory appended :rtype: keras model * The main difference between this implementation and the implementation above is that the one above """ for i in range(nb_layers): merge_tensor = conv_factory(x, concat_axis, growth_rate, dropout_rate, weight_decay) x = Concatenate(axis=concat_axis)([merge_tensor, x]) nb_filter += growth_rate return x, nb_filter
[ "def", "denseblock_altern", "(", "x", ",", "concat_axis", ",", "nb_layers", ",", "nb_filter", ",", "growth_rate", ",", "dropout_rate", "=", "None", ",", "weight_decay", "=", "1E-4", ")", ":", "for", "i", "in", "range", "(", "nb_layers", ")", ":", "merge_te...
https://github.com/tdeboissiere/DeepLearningImplementations/blob/5c4094880fc6992cca2d6e336463b2525026f6e2/DenseNet/densenet.py#L102-L128
awslabs/aws-ec2rescue-linux
8ecf40e7ea0d2563dac057235803fca2221029d2
ec2rlcore/programversion.py
python
ProgramVersion.__lt__
(self, other)
Implementation enables the rich comparison operator '<'. Python 2.5+ will infer the other operators, le, gt, and ge.
Implementation enables the rich comparison operator '<'. Python 2.5+ will infer the other operators, le, gt, and ge.
[ "Implementation", "enables", "the", "rich", "comparison", "operator", "<", ".", "Python", "2", ".", "5", "+", "will", "infer", "the", "other", "operators", "le", "gt", "and", "ge", "." ]
def __lt__(self, other): """ Implementation enables the rich comparison operator '<'. Python 2.5+ will infer the other operators, le, gt, and ge. """ if isinstance(other, self.__class__): return int(other.major) > int(self.major) \ or (int(other.major) == int(self.major) and int(other.minor) > int(self.minor)) \ or (int(other.major) == int(self.major) and int(other.minor) == int(self.minor) and int(other.maintenance) > int(self.maintenance)) \ or (int(other.major) == int(self.major) and int(other.minor) == int(self.minor) and int(other.maintenance) == int(self.maintenance) and other.release_numerical > self.release_numerical) \ or (int(other.major) == int(self.major) and int(other.minor) == int(self.minor) and int(other.maintenance) == int(self.maintenance) and other.release_numerical == self.release_numerical and int(other.pre_release) > int(self.pre_release)) raise ProgramVersionInvalidComparisonError(type(other))
[ "def", "__lt__", "(", "self", ",", "other", ")", ":", "if", "isinstance", "(", "other", ",", "self", ".", "__class__", ")", ":", "return", "int", "(", "other", ".", "major", ")", ">", "int", "(", "self", ".", "major", ")", "or", "(", "int", "(", ...
https://github.com/awslabs/aws-ec2rescue-linux/blob/8ecf40e7ea0d2563dac057235803fca2221029d2/ec2rlcore/programversion.py#L123-L144
apple/ccs-calendarserver
13c706b985fb728b9aab42dc0fef85aae21921c3
twistedcaldav/directory/augment.py
python
AugmentXMLDB._parseXML
(self)
return results
Parse self.xmlFiles into AugmentRecords. If none of the xmlFiles exist, create a default record.
Parse self.xmlFiles into AugmentRecords.
[ "Parse", "self", ".", "xmlFiles", "into", "AugmentRecords", "." ]
def _parseXML(self): """ Parse self.xmlFiles into AugmentRecords. If none of the xmlFiles exist, create a default record. """ results = {} # If all augments files are missing, return a default record for xmlFile in self.xmlFiles: if os.path.exists(xmlFile): break else: results["Default"] = AugmentRecord( "Default", enabled=True, enabledForCalendaring=True, enabledForAddressBooks=True, enabledForLogin=True, ) # Compare previously seen modification time and size of each # xml file. If all are unchanged, skip. if self._shouldReparse(self.xmlFiles): for xmlFile in self.xmlFiles: if os.path.exists(xmlFile): # Creating a parser does the parse XMLAugmentsParser(xmlFile, results) newModTime = os.path.getmtime(xmlFile) newSize = os.path.getsize(xmlFile) self.xmlFileStats[xmlFile] = (newModTime, newSize) return results
[ "def", "_parseXML", "(", "self", ")", ":", "results", "=", "{", "}", "# If all augments files are missing, return a default record", "for", "xmlFile", "in", "self", ".", "xmlFiles", ":", "if", "os", ".", "path", ".", "exists", "(", "xmlFile", ")", ":", "break"...
https://github.com/apple/ccs-calendarserver/blob/13c706b985fb728b9aab42dc0fef85aae21921c3/twistedcaldav/directory/augment.py#L498-L531
johntruckenbrodt/pyroSAR
efac51134ba42d20120b259f968afe5a4ddcc46a
pyroSAR/gamma/parser_demo.py
python
DELFT_vec2
(SLC_par, DELFT_dir, nstate='-', interval='-', ODR='-', logpath=None, outdir=None, shellscript=None)
| Extract and interpolate DELFT ERS-1, ERS-2, and ENVISAT state vectors | Copyright 2012, Gamma Remote Sensing, v2.6 clw 24-Oct-2012 Parameters ---------- SLC_par: (input) ISP image parameter file DELFT_dir: directory containing Delft orbit arclist and ODR files for ERS-1, ERS-2 or ENVISAT * NOTE: enter . for current directory nstate: number of state vectors to generate (enter - for default (>= 15) interval: time interval between state vectors in the ISP image parameter file (s) (default: 10.0) ODR: ODR file to use (include path) rather than ODR file determined from the Delft orbit arclist logpath: str or None a directory to write command logfiles to outdir: str or None the directory to execute the command in shellscript: str or None a file to write the Gamma commands to in shell format
| Extract and interpolate DELFT ERS-1, ERS-2, and ENVISAT state vectors | Copyright 2012, Gamma Remote Sensing, v2.6 clw 24-Oct-2012
[ "|", "Extract", "and", "interpolate", "DELFT", "ERS", "-", "1", "ERS", "-", "2", "and", "ENVISAT", "state", "vectors", "|", "Copyright", "2012", "Gamma", "Remote", "Sensing", "v2", ".", "6", "clw", "24", "-", "Oct", "-", "2012" ]
def DELFT_vec2(SLC_par, DELFT_dir, nstate='-', interval='-', ODR='-', logpath=None, outdir=None, shellscript=None): """ | Extract and interpolate DELFT ERS-1, ERS-2, and ENVISAT state vectors | Copyright 2012, Gamma Remote Sensing, v2.6 clw 24-Oct-2012 Parameters ---------- SLC_par: (input) ISP image parameter file DELFT_dir: directory containing Delft orbit arclist and ODR files for ERS-1, ERS-2 or ENVISAT * NOTE: enter . for current directory nstate: number of state vectors to generate (enter - for default (>= 15) interval: time interval between state vectors in the ISP image parameter file (s) (default: 10.0) ODR: ODR file to use (include path) rather than ODR file determined from the Delft orbit arclist logpath: str or None a directory to write command logfiles to outdir: str or None the directory to execute the command in shellscript: str or None a file to write the Gamma commands to in shell format """ process(['/usr/local/GAMMA_SOFTWARE-20180703/ISP/bin/DELFT_vec2', SLC_par, DELFT_dir, nstate, interval, ODR], logpath=logpath, outdir=outdir, shellscript=shellscript)
[ "def", "DELFT_vec2", "(", "SLC_par", ",", "DELFT_dir", ",", "nstate", "=", "'-'", ",", "interval", "=", "'-'", ",", "ODR", "=", "'-'", ",", "logpath", "=", "None", ",", "outdir", "=", "None", ",", "shellscript", "=", "None", ")", ":", "process", "(",...
https://github.com/johntruckenbrodt/pyroSAR/blob/efac51134ba42d20120b259f968afe5a4ddcc46a/pyroSAR/gamma/parser_demo.py#L820-L847
programa-stic/barf-project
9547ef843b8eb021c2c32c140e36173c0b4eafa3
barf/analysis/gadgets/classifier.py
python
GadgetClassifier._classify_jump
(self, regs_init, regs_fini, mem_fini, written_regs, read_regs)
return matches
Classify jump gadgets.
Classify jump gadgets.
[ "Classify", "jump", "gadgets", "." ]
def _classify_jump(self, regs_init, regs_fini, mem_fini, written_regs, read_regs): """Classify jump gadgets. """ # TODO: Implement. matches = [] return matches
[ "def", "_classify_jump", "(", "self", ",", "regs_init", ",", "regs_fini", ",", "mem_fini", ",", "written_regs", ",", "read_regs", ")", ":", "# TODO: Implement.", "matches", "=", "[", "]", "return", "matches" ]
https://github.com/programa-stic/barf-project/blob/9547ef843b8eb021c2c32c140e36173c0b4eafa3/barf/analysis/gadgets/classifier.py#L148-L155
openshift/openshift-tools
1188778e728a6e4781acf728123e5b356380fe6f
openshift/installer/vendored/openshift-ansible-3.10.0-0.29.0/roles/lib_openshift/src/lib/base.py
python
Utils.cleanup
(files)
Clean up on exit
Clean up on exit
[ "Clean", "up", "on", "exit" ]
def cleanup(files): '''Clean up on exit ''' for sfile in files: if os.path.exists(sfile): if os.path.isdir(sfile): shutil.rmtree(sfile) elif os.path.isfile(sfile): os.remove(sfile)
[ "def", "cleanup", "(", "files", ")", ":", "for", "sfile", "in", "files", ":", "if", "os", ".", "path", ".", "exists", "(", "sfile", ")", ":", "if", "os", ".", "path", ".", "isdir", "(", "sfile", ")", ":", "shutil", ".", "rmtree", "(", "sfile", ...
https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/openshift/installer/vendored/openshift-ansible-3.10.0-0.29.0/roles/lib_openshift/src/lib/base.py#L392-L399
ducksboard/libsaas
615981a3336f65be9d51ae95a48aed9ad3bd1c3c
libsaas/services/github/repocommits.py
python
RepoCommitsComment.get
(self, format=None)
return http.Request('GET', self.get_url(), params), parsers.parse_json
Fetch the comment. :var format: Which format should be requested, either `raw`, `text`, `html` or `full`. For details on formats, see http://developer.github.com/v3/mime/#comment-body-properties.
Fetch the comment.
[ "Fetch", "the", "comment", "." ]
def get(self, format=None): """ Fetch the comment. :var format: Which format should be requested, either `raw`, `text`, `html` or `full`. For details on formats, see http://developer.github.com/v3/mime/#comment-body-properties. """ params = base.get_params(('format', ), locals()) return http.Request('GET', self.get_url(), params), parsers.parse_json
[ "def", "get", "(", "self", ",", "format", "=", "None", ")", ":", "params", "=", "base", ".", "get_params", "(", "(", "'format'", ",", ")", ",", "locals", "(", ")", ")", "return", "http", ".", "Request", "(", "'GET'", ",", "self", ".", "get_url", ...
https://github.com/ducksboard/libsaas/blob/615981a3336f65be9d51ae95a48aed9ad3bd1c3c/libsaas/services/github/repocommits.py#L18-L28
xtiankisutsa/MARA_Framework
ac4ac88bfd38f33ae8780a606ed09ab97177c562
tools/qark/qark/lib/bs4/element.py
python
Tag.select
(self, selector, _candidate_generator=None)
return current_context
Perform a CSS selection operation on the current element.
Perform a CSS selection operation on the current element.
[ "Perform", "a", "CSS", "selection", "operation", "on", "the", "current", "element", "." ]
def select(self, selector, _candidate_generator=None): """Perform a CSS selection operation on the current element.""" tokens = selector.split() current_context = [self] if tokens[-1] in self._selector_combinators: raise ValueError( 'Final combinator "%s" is missing an argument.' % tokens[-1]) if self._select_debug: print 'Running CSS selector "%s"' % selector for index, token in enumerate(tokens): if self._select_debug: print ' Considering token "%s"' % token recursive_candidate_generator = None tag_name = None if tokens[index-1] in self._selector_combinators: # This token was consumed by the previous combinator. Skip it. if self._select_debug: print ' Token was consumed by the previous combinator.' continue # Each operation corresponds to a checker function, a rule # for determining whether a candidate matches the # selector. Candidates are generated by the active # iterator. checker = None m = self.attribselect_re.match(token) if m is not None: # Attribute selector tag_name, attribute, operator, value = m.groups() checker = self._attribute_checker(operator, attribute, value) elif '#' in token: # ID selector tag_name, tag_id = token.split('#', 1) def id_matches(tag): return tag.get('id', None) == tag_id checker = id_matches elif '.' in token: # Class selector tag_name, klass = token.split('.', 1) classes = set(klass.split('.')) def classes_match(candidate): return classes.issubset(candidate.get('class', [])) checker = classes_match elif ':' in token: # Pseudo-class tag_name, pseudo = token.split(':', 1) if tag_name == '': raise ValueError( "A pseudo-class must be prefixed with a tag name.") pseudo_attributes = re.match('([a-zA-Z\d-]+)\(([a-zA-Z\d]+)\)', pseudo) found = [] if pseudo_attributes is not None: pseudo_type, pseudo_value = pseudo_attributes.groups() if pseudo_type == 'nth-of-type': try: pseudo_value = int(pseudo_value) except: raise NotImplementedError( 'Only numeric values are currently supported for the nth-of-type pseudo-class.') if pseudo_value < 1: raise ValueError( 'nth-of-type pseudo-class value must be at least 1.') class Counter(object): def __init__(self, destination): self.count = 0 self.destination = destination def nth_child_of_type(self, tag): self.count += 1 if self.count == self.destination: return True if self.count > self.destination: # Stop the generator that's sending us # these things. raise StopIteration() return False checker = Counter(pseudo_value).nth_child_of_type else: raise NotImplementedError( 'Only the following pseudo-classes are implemented: nth-of-type.') elif token == '*': # Star selector -- matches everything pass elif token == '>': # Run the next token as a CSS selector against the # direct children of each tag in the current context. recursive_candidate_generator = lambda tag: tag.children elif token == '~': # Run the next token as a CSS selector against the # siblings of each tag in the current context. recursive_candidate_generator = lambda tag: tag.next_siblings elif token == '+': # For each tag in the current context, run the next # token as a CSS selector against the tag's next # sibling that's a tag. def next_tag_sibling(tag): yield tag.find_next_sibling(True) recursive_candidate_generator = next_tag_sibling elif self.tag_name_re.match(token): # Just a tag name. tag_name = token else: raise ValueError( 'Unsupported or invalid CSS selector: "%s"' % token) if recursive_candidate_generator: # This happens when the selector looks like "> foo". # # The generator calls select() recursively on every # member of the current context, passing in a different # candidate generator and a different selector. # # In the case of "> foo", the candidate generator is # one that yields a tag's direct children (">"), and # the selector is "foo". next_token = tokens[index+1] def recursive_select(tag): if self._select_debug: print ' Calling select("%s") recursively on %s %s' % (next_token, tag.name, tag.attrs) print '-' * 40 for i in tag.select(next_token, recursive_candidate_generator): if self._select_debug: print '(Recursive select picked up candidate %s %s)' % (i.name, i.attrs) yield i if self._select_debug: print '-' * 40 _use_candidate_generator = recursive_select elif _candidate_generator is None: # By default, a tag's candidates are all of its # children. If tag_name is defined, only yield tags # with that name. if self._select_debug: if tag_name: check = "[any]" else: check = tag_name print ' Default candidate generator, tag name="%s"' % check if self._select_debug: # This is redundant with later code, but it stops # a bunch of bogus tags from cluttering up the # debug log. def default_candidate_generator(tag): for child in tag.descendants: if not isinstance(child, Tag): continue if tag_name and not child.name == tag_name: continue yield child _use_candidate_generator = default_candidate_generator else: _use_candidate_generator = lambda tag: tag.descendants else: _use_candidate_generator = _candidate_generator new_context = [] new_context_ids = set([]) for tag in current_context: if self._select_debug: print " Running candidate generator on %s %s" % ( tag.name, repr(tag.attrs)) for candidate in _use_candidate_generator(tag): if not isinstance(candidate, Tag): continue if tag_name and candidate.name != tag_name: continue if checker is not None: try: result = checker(candidate) except StopIteration: # The checker has decided we should no longer # run the generator. break if checker is None or result: if self._select_debug: print " SUCCESS %s %s" % (candidate.name, repr(candidate.attrs)) if id(candidate) not in new_context_ids: # If a tag matches a selector more than once, # don't include it in the context more than once. new_context.append(candidate) new_context_ids.add(id(candidate)) elif self._select_debug: print " FAILURE %s %s" % (candidate.name, repr(candidate.attrs)) current_context = new_context if self._select_debug: print "Final verdict:" for i in current_context: print " %s %s" % (i.name, i.attrs) return current_context
[ "def", "select", "(", "self", ",", "selector", ",", "_candidate_generator", "=", "None", ")", ":", "tokens", "=", "selector", ".", "split", "(", ")", "current_context", "=", "[", "self", "]", "if", "tokens", "[", "-", "1", "]", "in", "self", ".", "_s...
https://github.com/xtiankisutsa/MARA_Framework/blob/ac4ac88bfd38f33ae8780a606ed09ab97177c562/tools/qark/qark/lib/bs4/element.py#L1204-L1399
CouchPotato/CouchPotatoServer
7260c12f72447ddb6f062367c6dfbda03ecd4e9c
libs/pytwitter/__init__.py
python
User.GetVerified
(self)
return self._verified
Get the setting of verified for this user. Returns: True/False if user is a verified account
Get the setting of verified for this user.
[ "Get", "the", "setting", "of", "verified", "for", "this", "user", "." ]
def GetVerified(self): '''Get the setting of verified for this user. Returns: True/False if user is a verified account ''' return self._verified
[ "def", "GetVerified", "(", "self", ")", ":", "return", "self", ".", "_verified" ]
https://github.com/CouchPotato/CouchPotatoServer/blob/7260c12f72447ddb6f062367c6dfbda03ecd4e9c/libs/pytwitter/__init__.py#L1245-L1251
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/Python-2.7.9/Lib/SimpleXMLRPCServer.py
python
SimpleXMLRPCRequestHandler.do_POST
(self)
Handles the HTTP POST request. Attempts to interpret all HTTP POST requests as XML-RPC calls, which are forwarded to the server's _dispatch method for handling.
Handles the HTTP POST request.
[ "Handles", "the", "HTTP", "POST", "request", "." ]
def do_POST(self): """Handles the HTTP POST request. Attempts to interpret all HTTP POST requests as XML-RPC calls, which are forwarded to the server's _dispatch method for handling. """ # Check that the path is legal if not self.is_rpc_path_valid(): self.report_404() return try: # Get arguments by reading body of request. # We read this in chunks to avoid straining # socket.read(); around the 10 or 15Mb mark, some platforms # begin to have problems (bug #792570). max_chunk_size = 10*1024*1024 size_remaining = int(self.headers["content-length"]) L = [] while size_remaining: chunk_size = min(size_remaining, max_chunk_size) chunk = self.rfile.read(chunk_size) if not chunk: break L.append(chunk) size_remaining -= len(L[-1]) data = ''.join(L) data = self.decode_request_content(data) if data is None: return #response has been sent # In previous versions of SimpleXMLRPCServer, _dispatch # could be overridden in this class, instead of in # SimpleXMLRPCDispatcher. To maintain backwards compatibility, # check to see if a subclass implements _dispatch and dispatch # using that method if present. response = self.server._marshaled_dispatch( data, getattr(self, '_dispatch', None), self.path ) except Exception, e: # This should only happen if the module is buggy # internal error, report as HTTP server error self.send_response(500) # Send information about the exception if requested if hasattr(self.server, '_send_traceback_header') and \ self.server._send_traceback_header: self.send_header("X-exception", str(e)) self.send_header("X-traceback", traceback.format_exc()) self.send_header("Content-length", "0") self.end_headers() else: # got a valid XML RPC response self.send_response(200) self.send_header("Content-type", "text/xml") if self.encode_threshold is not None: if len(response) > self.encode_threshold: q = self.accept_encodings().get("gzip", 0) if q: try: response = xmlrpclib.gzip_encode(response) self.send_header("Content-Encoding", "gzip") except NotImplementedError: pass self.send_header("Content-length", str(len(response))) self.end_headers() self.wfile.write(response)
[ "def", "do_POST", "(", "self", ")", ":", "# Check that the path is legal", "if", "not", "self", ".", "is_rpc_path_valid", "(", ")", ":", "self", ".", "report_404", "(", ")", "return", "try", ":", "# Get arguments by reading body of request.", "# We read this in chunks...
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/Python-2.7.9/Lib/SimpleXMLRPCServer.py#L467-L535
GNS3/gns3-gui
da8adbaa18ab60e053af2a619efd468f4c8950f3
gns3/nodes_view.py
python
NodesView.mouseMoveEvent
(self, event)
Handles all mouse move events. This is the starting point to drag & drop a template on the scene. :param: QMouseEvent instance
Handles all mouse move events. This is the starting point to drag & drop a template on the scene.
[ "Handles", "all", "mouse", "move", "events", ".", "This", "is", "the", "starting", "point", "to", "drag", "&", "drop", "a", "template", "on", "the", "scene", "." ]
def mouseMoveEvent(self, event): """ Handles all mouse move events. This is the starting point to drag & drop a template on the scene. :param: QMouseEvent instance """ # Check that an item has been selected and left button clicked if self.currentItem() is not None and event.buttons() == QtCore.Qt.LeftButton: item = self.currentItem() icon = item.icon(0) mimedata = QtCore.QMimeData() assert item.data(1, QtCore.Qt.UserRole) == "template" template_id = item.data(0, QtCore.Qt.UserRole) mimedata.setData("application/x-gns3-template", template_id.encode()) drag = QtGui.QDrag(self) drag.setMimeData(mimedata) drag.setPixmap(icon.pixmap(self.iconSize())) drag.setHotSpot(QtCore.QPoint(drag.pixmap().width(), drag.pixmap().height())) drag.exec_(QtCore.Qt.CopyAction) event.accept()
[ "def", "mouseMoveEvent", "(", "self", ",", "event", ")", ":", "# Check that an item has been selected and left button clicked", "if", "self", ".", "currentItem", "(", ")", "is", "not", "None", "and", "event", ".", "buttons", "(", ")", "==", "QtCore", ".", "Qt", ...
https://github.com/GNS3/gns3-gui/blob/da8adbaa18ab60e053af2a619efd468f4c8950f3/gns3/nodes_view.py#L170-L193
Qirky/FoxDot
76318f9630bede48ff3994146ed644affa27bfa4
FoxDot/lib/OSC.py
python
OSCStreamingServer.stop
(self)
Stop the server thread and close the socket.
Stop the server thread and close the socket.
[ "Stop", "the", "server", "thread", "and", "close", "the", "socket", "." ]
def stop(self): """ Stop the server thread and close the socket. """ self.running = False self._server_thread.join() self.server_close()
[ "def", "stop", "(", "self", ")", ":", "self", ".", "running", "=", "False", "self", ".", "_server_thread", ".", "join", "(", ")", "self", ".", "server_close", "(", ")" ]
https://github.com/Qirky/FoxDot/blob/76318f9630bede48ff3994146ed644affa27bfa4/FoxDot/lib/OSC.py#L2650-L2654
plotly/plotly.py
cfad7862594b35965c0e000813bd7805e8494a5b
packages/python/plotly/plotly/graph_objs/_box.py
python
Box.notchwidth
(self)
return self["notchwidth"]
Sets the width of the notches relative to the box' width. For example, with 0, the notches are as wide as the box(es). The 'notchwidth' property is a number and may be specified as: - An int or float in the interval [0, 0.5] Returns ------- int|float
Sets the width of the notches relative to the box' width. For example, with 0, the notches are as wide as the box(es). The 'notchwidth' property is a number and may be specified as: - An int or float in the interval [0, 0.5]
[ "Sets", "the", "width", "of", "the", "notches", "relative", "to", "the", "box", "width", ".", "For", "example", "with", "0", "the", "notches", "are", "as", "wide", "as", "the", "box", "(", "es", ")", ".", "The", "notchwidth", "property", "is", "a", "...
def notchwidth(self): """ Sets the width of the notches relative to the box' width. For example, with 0, the notches are as wide as the box(es). The 'notchwidth' property is a number and may be specified as: - An int or float in the interval [0, 0.5] Returns ------- int|float """ return self["notchwidth"]
[ "def", "notchwidth", "(", "self", ")", ":", "return", "self", "[", "\"notchwidth\"", "]" ]
https://github.com/plotly/plotly.py/blob/cfad7862594b35965c0e000813bd7805e8494a5b/packages/python/plotly/plotly/graph_objs/_box.py#L1050-L1062