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
TencentCloud/tencentcloud-sdk-python
3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2
tencentcloud/cfw/v20190904/cfw_client.py
python
CfwClient.ModifyNatFwVpcDnsSwitch
(self, request)
nat 防火墙VPC DNS 开关切换 :param request: Request instance for ModifyNatFwVpcDnsSwitch. :type request: :class:`tencentcloud.cfw.v20190904.models.ModifyNatFwVpcDnsSwitchRequest` :rtype: :class:`tencentcloud.cfw.v20190904.models.ModifyNatFwVpcDnsSwitchResponse`
nat 防火墙VPC DNS 开关切换
[ "nat", "防火墙VPC", "DNS", "开关切换" ]
def ModifyNatFwVpcDnsSwitch(self, request): """nat 防火墙VPC DNS 开关切换 :param request: Request instance for ModifyNatFwVpcDnsSwitch. :type request: :class:`tencentcloud.cfw.v20190904.models.ModifyNatFwVpcDnsSwitchRequest` :rtype: :class:`tencentcloud.cfw.v20190904.models.ModifyNatFwVpcDnsSwitchResponse` """ try: params = request._serialize() body = self.call("ModifyNatFwVpcDnsSwitch", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.ModifyNatFwVpcDnsSwitchResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message)
[ "def", "ModifyNatFwVpcDnsSwitch", "(", "self", ",", "request", ")", ":", "try", ":", "params", "=", "request", ".", "_serialize", "(", ")", "body", "=", "self", ".", "call", "(", "\"ModifyNatFwVpcDnsSwitch\"", ",", "params", ")", "response", "=", "json", "...
https://github.com/TencentCloud/tencentcloud-sdk-python/blob/3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2/tencentcloud/cfw/v20190904/cfw_client.py#L1544-L1569
cloudera/hue
23f02102d4547c17c32bd5ea0eb24e9eadd657a4
desktop/core/ext-py/python-openid-2.2.5/openid/consumer/consumer.py
python
_httpResponseToMessage
(response, server_url)
return response_message
Adapt a POST response to a Message. @type response: L{openid.fetchers.HTTPResponse} @param response: Result of a POST to an OpenID endpoint. @rtype: L{openid.message.Message} @raises openid.fetchers.HTTPFetchingError: if the server returned a status of other than 200 or 400. @raises ServerError: if the server returned an OpenID error.
Adapt a POST response to a Message.
[ "Adapt", "a", "POST", "response", "to", "a", "Message", "." ]
def _httpResponseToMessage(response, server_url): """Adapt a POST response to a Message. @type response: L{openid.fetchers.HTTPResponse} @param response: Result of a POST to an OpenID endpoint. @rtype: L{openid.message.Message} @raises openid.fetchers.HTTPFetchingError: if the server returned a status of other than 200 or 400. @raises ServerError: if the server returned an OpenID error. """ # Should this function be named Message.fromHTTPResponse instead? response_message = Message.fromKVForm(response.body) if response.status == 400: raise ServerError.fromMessage(response_message) elif response.status not in (200, 206): fmt = 'bad status code from server %s: %s' error_message = fmt % (server_url, response.status) raise fetchers.HTTPFetchingError(error_message) return response_message
[ "def", "_httpResponseToMessage", "(", "response", ",", "server_url", ")", ":", "# Should this function be named Message.fromHTTPResponse instead?", "response_message", "=", "Message", ".", "fromKVForm", "(", "response", ".", "body", ")", "if", "response", ".", "status", ...
https://github.com/cloudera/hue/blob/23f02102d4547c17c32bd5ea0eb24e9eadd657a4/desktop/core/ext-py/python-openid-2.2.5/openid/consumer/consumer.py#L232-L255
mystor/git-revise
c06c8003870c776376e5f7bc4dd9f4dc97714b7c
gitrevise/odb.py
python
Index.git
( self, *cmd: str, cwd: Optional[Path] = None, stdin: Optional[bytes] = None, trim_newline: bool = True, env: Optional[Mapping[str, str]] = None, nocapture: bool = False, )
return self.repo.git( *cmd, cwd=cwd, stdin=stdin, trim_newline=trim_newline, env=env, nocapture=nocapture, )
Invoke git with the given index as active
Invoke git with the given index as active
[ "Invoke", "git", "with", "the", "given", "index", "as", "active" ]
def git( self, *cmd: str, cwd: Optional[Path] = None, stdin: Optional[bytes] = None, trim_newline: bool = True, env: Optional[Mapping[str, str]] = None, nocapture: bool = False, ) -> bytes: """Invoke git with the given index as active""" env = dict(**env) if env is not None else dict(**os.environ) env["GIT_INDEX_FILE"] = str(self.index_file) return self.repo.git( *cmd, cwd=cwd, stdin=stdin, trim_newline=trim_newline, env=env, nocapture=nocapture, )
[ "def", "git", "(", "self", ",", "*", "cmd", ":", "str", ",", "cwd", ":", "Optional", "[", "Path", "]", "=", "None", ",", "stdin", ":", "Optional", "[", "bytes", "]", "=", "None", ",", "trim_newline", ":", "bool", "=", "True", ",", "env", ":", "...
https://github.com/mystor/git-revise/blob/c06c8003870c776376e5f7bc4dd9f4dc97714b7c/gitrevise/odb.py#L813-L832
openshift/openshift-tools
1188778e728a6e4781acf728123e5b356380fe6f
openshift/installer/vendored/openshift-ansible-3.11.28-1/roles/lib_openshift/library/oc_adm_router.py
python
Service.get_ports
(self)
return self.get(Service.port_path) or []
get a list of ports
get a list of ports
[ "get", "a", "list", "of", "ports" ]
def get_ports(self): ''' get a list of ports ''' return self.get(Service.port_path) or []
[ "def", "get_ports", "(", "self", ")", ":", "return", "self", ".", "get", "(", "Service", ".", "port_path", ")", "or", "[", "]" ]
https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/openshift/installer/vendored/openshift-ansible-3.11.28-1/roles/lib_openshift/library/oc_adm_router.py#L1687-L1689
phimpme/phimpme-generator
ba6d11190b9016238f27672e1ad55e6a875b74a0
Phimpme/site-packages/coverage/files.py
python
sep
(s)
return the_sep
Find the path separator used in this string, or os.sep if none.
Find the path separator used in this string, or os.sep if none.
[ "Find", "the", "path", "separator", "used", "in", "this", "string", "or", "os", ".", "sep", "if", "none", "." ]
def sep(s): """Find the path separator used in this string, or os.sep if none.""" sep_match = re.search(r"[\\/]", s) if sep_match: the_sep = sep_match.group(0) else: the_sep = os.sep return the_sep
[ "def", "sep", "(", "s", ")", ":", "sep_match", "=", "re", ".", "search", "(", "r\"[\\\\/]\"", ",", "s", ")", "if", "sep_match", ":", "the_sep", "=", "sep_match", ".", "group", "(", "0", ")", "else", ":", "the_sep", "=", "os", ".", "sep", "return", ...
https://github.com/phimpme/phimpme-generator/blob/ba6d11190b9016238f27672e1ad55e6a875b74a0/Phimpme/site-packages/coverage/files.py#L196-L203
JiYou/openstack
8607dd488bde0905044b303eb6e52bdea6806923
packages/source/nova/nova/network/floating_ips.py
python
FloatingIP.deallocate_floating_ip
(self, context, address, affect_auto_assigned=False)
Returns a floating ip to the pool.
Returns a floating ip to the pool.
[ "Returns", "a", "floating", "ip", "to", "the", "pool", "." ]
def deallocate_floating_ip(self, context, address, affect_auto_assigned=False): """Returns a floating ip to the pool.""" floating_ip = self.db.floating_ip_get_by_address(context, address) # handle auto_assigned if not affect_auto_assigned and floating_ip.get('auto_assigned'): return use_quota = not floating_ip.get('auto_assigned') # make sure project owns this floating ip (allocated) self._floating_ip_owned_by_project(context, floating_ip) # make sure floating ip is not associated if floating_ip['fixed_ip_id']: floating_address = floating_ip['address'] raise exception.FloatingIpAssociated(address=floating_address) # clean up any associated DNS entries self._delete_all_entries_for_ip(context, floating_ip['address']) payload = dict(project_id=floating_ip['project_id'], floating_ip=floating_ip['address']) notifier.notify(context, notifier.publisher_id("network"), 'network.floating_ip.deallocate', notifier.INFO, payload=payload) # Get reservations... try: if use_quota: reservations = QUOTAS.reserve(context, floating_ips=-1) else: reservations = None except Exception: reservations = None LOG.exception(_("Failed to update usages deallocating " "floating IP")) self.db.floating_ip_deallocate(context, address) # Commit the reservations if reservations: QUOTAS.commit(context, reservations)
[ "def", "deallocate_floating_ip", "(", "self", ",", "context", ",", "address", ",", "affect_auto_assigned", "=", "False", ")", ":", "floating_ip", "=", "self", ".", "db", ".", "floating_ip_get_by_address", "(", "context", ",", "address", ")", "# handle auto_assigne...
https://github.com/JiYou/openstack/blob/8607dd488bde0905044b303eb6e52bdea6806923/packages/source/nova/nova/network/floating_ips.py#L245-L288
CouchPotato/CouchPotatoV1
135b3331d1b88ef645e29b76f2d4cc4a732c9232
library/sqlalchemy/engine/base.py
python
Connection.detach
(self)
Detach the underlying DB-API connection from its connection pool. This Connection instance will remain useable. When closed, the DB-API connection will be literally closed and not returned to its pool. The pool will typically lazily create a new connection to replace the detached connection. This method can be used to insulate the rest of an application from a modified state on a connection (such as a transaction isolation level or similar). Also see :class:`~sqlalchemy.interfaces.PoolListener` for a mechanism to modify connection state when connections leave and return to their connection pool.
Detach the underlying DB-API connection from its connection pool.
[ "Detach", "the", "underlying", "DB", "-", "API", "connection", "from", "its", "connection", "pool", "." ]
def detach(self): """Detach the underlying DB-API connection from its connection pool. This Connection instance will remain useable. When closed, the DB-API connection will be literally closed and not returned to its pool. The pool will typically lazily create a new connection to replace the detached connection. This method can be used to insulate the rest of an application from a modified state on a connection (such as a transaction isolation level or similar). Also see :class:`~sqlalchemy.interfaces.PoolListener` for a mechanism to modify connection state when connections leave and return to their connection pool. """ self.__connection.detach()
[ "def", "detach", "(", "self", ")", ":", "self", ".", "__connection", ".", "detach", "(", ")" ]
https://github.com/CouchPotato/CouchPotatoV1/blob/135b3331d1b88ef645e29b76f2d4cc4a732c9232/library/sqlalchemy/engine/base.py#L988-L1004
clinton-hall/nzbToMedia
27669389216902d1085660167e7bda0bd8527ecf
libs/common/setuptools/dist.py
python
Distribution._exclude_misc
(self, name, value)
Handle 'exclude()' for list/tuple attrs without a special handler
Handle 'exclude()' for list/tuple attrs without a special handler
[ "Handle", "exclude", "()", "for", "list", "/", "tuple", "attrs", "without", "a", "special", "handler" ]
def _exclude_misc(self, name, value): """Handle 'exclude()' for list/tuple attrs without a special handler""" if not isinstance(value, sequence): raise DistutilsSetupError( "%s: setting must be a list or tuple (%r)" % (name, value) ) try: old = getattr(self, name) except AttributeError: raise DistutilsSetupError( "%s: No such distribution setting" % name ) if old is not None and not isinstance(old, sequence): raise DistutilsSetupError( name + ": this setting cannot be changed via include/exclude" ) elif old: setattr(self, name, [item for item in old if item not in value])
[ "def", "_exclude_misc", "(", "self", ",", "name", ",", "value", ")", ":", "if", "not", "isinstance", "(", "value", ",", "sequence", ")", ":", "raise", "DistutilsSetupError", "(", "\"%s: setting must be a list or tuple (%r)\"", "%", "(", "name", ",", "value", "...
https://github.com/clinton-hall/nzbToMedia/blob/27669389216902d1085660167e7bda0bd8527ecf/libs/common/setuptools/dist.py#L800-L817
mlcommons/training
4a4d5a0b7efe99c680306b1940749211d4238a84
language_model/tensorflow/bert/modeling.py
python
gelu
(x)
return x * cdf
Gaussian Error Linear Unit. This is a smoother version of the RELU. Original paper: https://arxiv.org/abs/1606.08415 Args: x: float Tensor to perform activation. Returns: `x` with the GELU activation applied.
Gaussian Error Linear Unit.
[ "Gaussian", "Error", "Linear", "Unit", "." ]
def gelu(x): """Gaussian Error Linear Unit. This is a smoother version of the RELU. Original paper: https://arxiv.org/abs/1606.08415 Args: x: float Tensor to perform activation. Returns: `x` with the GELU activation applied. """ cdf = 0.5 * (1.0 + tf.tanh( (np.sqrt(2 / np.pi) * (x + 0.044715 * tf.pow(x, 3))))) return x * cdf
[ "def", "gelu", "(", "x", ")", ":", "cdf", "=", "0.5", "*", "(", "1.0", "+", "tf", ".", "tanh", "(", "(", "np", ".", "sqrt", "(", "2", "/", "np", ".", "pi", ")", "*", "(", "x", "+", "0.044715", "*", "tf", ".", "pow", "(", "x", ",", "3", ...
https://github.com/mlcommons/training/blob/4a4d5a0b7efe99c680306b1940749211d4238a84/language_model/tensorflow/bert/modeling.py#L263-L276
tp4a/teleport
1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad
server/www/packages/packages-windows/x86/PIL/PngImagePlugin.py
python
_fdat.write
(self, data)
[]
def write(self, data): self.chunk(self.fp, b"fdAT", o32(self.seq_num), data) self.seq_num += 1
[ "def", "write", "(", "self", ",", "data", ")", ":", "self", ".", "chunk", "(", "self", ".", "fp", ",", "b\"fdAT\"", ",", "o32", "(", "self", ".", "seq_num", ")", ",", "data", ")", "self", ".", "seq_num", "+=", "1" ]
https://github.com/tp4a/teleport/blob/1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad/server/www/packages/packages-windows/x86/PIL/PngImagePlugin.py#L1007-L1009
anatolikalysch/VMAttack
67dcce6087163d85bbe7780e3f6e6e9e72e2212a
lib/Optimize.py
python
size_to_str
(size)
@brief Determines a string representation for a given size
[]
def size_to_str(size): """ @brief Determines a string representation for a given size """ lookup = {1:'b', 2:'w', 4:'d', 8:'q'} try: return lookup[size] except: return ''
[ "def", "size_to_str", "(", "size", ")", ":", "lookup", "=", "{", "1", ":", "'b'", ",", "2", ":", "'w'", ",", "4", ":", "'d'", ",", "8", ":", "'q'", "}", "try", ":", "return", "lookup", "[", "size", "]", "except", ":", "return", "''" ]
https://github.com/anatolikalysch/VMAttack/blob/67dcce6087163d85bbe7780e3f6e6e9e72e2212a/lib/Optimize.py#L336-L344
pybuilder/pybuilder
12ea2f54e04f97daada375dc3309a3f525f1b5e1
src/main/python/pybuilder/_vendor/importlib_metadata/__init__.py
python
Distribution.version
(self)
return self.metadata['Version']
Return the 'Version' metadata for the distribution package.
Return the 'Version' metadata for the distribution package.
[ "Return", "the", "Version", "metadata", "for", "the", "distribution", "package", "." ]
def version(self): """Return the 'Version' metadata for the distribution package.""" return self.metadata['Version']
[ "def", "version", "(", "self", ")", ":", "return", "self", ".", "metadata", "[", "'Version'", "]" ]
https://github.com/pybuilder/pybuilder/blob/12ea2f54e04f97daada375dc3309a3f525f1b5e1/src/main/python/pybuilder/_vendor/importlib_metadata/__init__.py#L607-L609
wistbean/fxxkpython
88e16d79d8dd37236ba6ecd0d0ff11d63143968c
vip/qyxuan/projects/venv/lib/python3.6/site-packages/pip-19.0.3-py3.6.egg/pip/_vendor/retrying.py
python
Retrying.fixed_sleep
(self, previous_attempt_number, delay_since_first_attempt_ms)
return self._wait_fixed
Sleep a fixed amount of time between each retry.
Sleep a fixed amount of time between each retry.
[ "Sleep", "a", "fixed", "amount", "of", "time", "between", "each", "retry", "." ]
def fixed_sleep(self, previous_attempt_number, delay_since_first_attempt_ms): """Sleep a fixed amount of time between each retry.""" return self._wait_fixed
[ "def", "fixed_sleep", "(", "self", ",", "previous_attempt_number", ",", "delay_since_first_attempt_ms", ")", ":", "return", "self", ".", "_wait_fixed" ]
https://github.com/wistbean/fxxkpython/blob/88e16d79d8dd37236ba6ecd0d0ff11d63143968c/vip/qyxuan/projects/venv/lib/python3.6/site-packages/pip-19.0.3-py3.6.egg/pip/_vendor/retrying.py#L153-L155
pyparallel/pyparallel
11e8c6072d48c8f13641925d17b147bf36ee0ba3
Lib/copyreg.py
python
remove_extension
(module, name, code)
Unregister an extension code. For testing only.
Unregister an extension code. For testing only.
[ "Unregister", "an", "extension", "code", ".", "For", "testing", "only", "." ]
def remove_extension(module, name, code): """Unregister an extension code. For testing only.""" key = (module, name) if (_extension_registry.get(key) != code or _inverted_registry.get(code) != key): raise ValueError("key %s is not registered with code %s" % (key, code)) del _extension_registry[key] del _inverted_registry[code] if code in _extension_cache: del _extension_cache[code]
[ "def", "remove_extension", "(", "module", ",", "name", ",", "code", ")", ":", "key", "=", "(", "module", ",", "name", ")", "if", "(", "_extension_registry", ".", "get", "(", "key", ")", "!=", "code", "or", "_inverted_registry", ".", "get", "(", "code",...
https://github.com/pyparallel/pyparallel/blob/11e8c6072d48c8f13641925d17b147bf36ee0ba3/Lib/copyreg.py#L170-L180
tp4a/teleport
1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad
server/www/packages/packages-darwin/x64/tornado/http1connection.py
python
HTTP1Connection.close
(self)
[]
def close(self): if self.stream is not None: self.stream.close() self._clear_callbacks() if not self._finish_future.done(): future_set_result_unless_cancelled(self._finish_future, None)
[ "def", "close", "(", "self", ")", ":", "if", "self", ".", "stream", "is", "not", "None", ":", "self", ".", "stream", ".", "close", "(", ")", "self", ".", "_clear_callbacks", "(", ")", "if", "not", "self", ".", "_finish_future", ".", "done", "(", ")...
https://github.com/tp4a/teleport/blob/1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad/server/www/packages/packages-darwin/x64/tornado/http1connection.py#L304-L309
007gzs/dingtalk-sdk
7979da2e259fdbc571728cae2425a04dbc65850a
dingtalk/client/api/taobao.py
python
TbOttZhiFu.youku_ott_pay_order_queryorderbycp
( self, cp_order_no='' )
return self._top_request( "youku.ott.pay.order.queryorderbycp", { "cp_order_no": cp_order_no }, result_processor=lambda x: x["data"] )
订单查询接口(cp订单号查询) 给商户服务端查询订单状态 文档地址:https://open-doc.dingtalk.com/docs/api.htm?apiId=37270 :param cp_order_no: cp订单号
订单查询接口(cp订单号查询) 给商户服务端查询订单状态 文档地址:https://open-doc.dingtalk.com/docs/api.htm?apiId=37270
[ "订单查询接口", "(", "cp订单号查询", ")", "给商户服务端查询订单状态", "文档地址:https", ":", "//", "open", "-", "doc", ".", "dingtalk", ".", "com", "/", "docs", "/", "api", ".", "htm?apiId", "=", "37270" ]
def youku_ott_pay_order_queryorderbycp( self, cp_order_no='' ): """ 订单查询接口(cp订单号查询) 给商户服务端查询订单状态 文档地址:https://open-doc.dingtalk.com/docs/api.htm?apiId=37270 :param cp_order_no: cp订单号 """ return self._top_request( "youku.ott.pay.order.queryorderbycp", { "cp_order_no": cp_order_no }, result_processor=lambda x: x["data"] )
[ "def", "youku_ott_pay_order_queryorderbycp", "(", "self", ",", "cp_order_no", "=", "''", ")", ":", "return", "self", ".", "_top_request", "(", "\"youku.ott.pay.order.queryorderbycp\"", ",", "{", "\"cp_order_no\"", ":", "cp_order_no", "}", ",", "result_processor", "=",...
https://github.com/007gzs/dingtalk-sdk/blob/7979da2e259fdbc571728cae2425a04dbc65850a/dingtalk/client/api/taobao.py#L101573-L101590
J535D165/recordlinkage
5b3230f5cff92ef58968eedc451735e972035793
recordlinkage/utils.py
python
frame_indexing
(frame, multi_index, level_i, indexing_type='label')
return data
Index dataframe based on one level of MultiIndex. Arguments --------- frame : pandas.DataFrame The datafrme to select records from. multi_index : pandas.MultiIndex A pandas multiindex were one fo the levels is used to sample the dataframe with. level_i : int, str The level of the multiIndex to index on. indexing_type : str The type of indexing. The value can be 'label' or 'position'. Default 'label'.
Index dataframe based on one level of MultiIndex.
[ "Index", "dataframe", "based", "on", "one", "level", "of", "MultiIndex", "." ]
def frame_indexing(frame, multi_index, level_i, indexing_type='label'): """Index dataframe based on one level of MultiIndex. Arguments --------- frame : pandas.DataFrame The datafrme to select records from. multi_index : pandas.MultiIndex A pandas multiindex were one fo the levels is used to sample the dataframe with. level_i : int, str The level of the multiIndex to index on. indexing_type : str The type of indexing. The value can be 'label' or 'position'. Default 'label'. """ if indexing_type == "label": data = frame.loc[multi_index.get_level_values(level_i)] data.index = multi_index elif indexing_type == "position": data = frame.iloc[multi_index.get_level_values(level_i)] data.index = multi_index else: raise ValueError("indexing_type needs to be 'label' or 'position'") return data
[ "def", "frame_indexing", "(", "frame", ",", "multi_index", ",", "level_i", ",", "indexing_type", "=", "'label'", ")", ":", "if", "indexing_type", "==", "\"label\"", ":", "data", "=", "frame", ".", "loc", "[", "multi_index", ".", "get_level_values", "(", "lev...
https://github.com/J535D165/recordlinkage/blob/5b3230f5cff92ef58968eedc451735e972035793/recordlinkage/utils.py#L176-L203
naftaliharris/tauthon
5587ceec329b75f7caf6d65a036db61ac1bae214
Lib/decimal.py
python
Decimal.number_class
(self, context=None)
Returns an indication of the class of self. The class is one of the following strings: sNaN NaN -Infinity -Normal -Subnormal -Zero +Zero +Subnormal +Normal +Infinity
Returns an indication of the class of self.
[ "Returns", "an", "indication", "of", "the", "class", "of", "self", "." ]
def number_class(self, context=None): """Returns an indication of the class of self. The class is one of the following strings: sNaN NaN -Infinity -Normal -Subnormal -Zero +Zero +Subnormal +Normal +Infinity """ if self.is_snan(): return "sNaN" if self.is_qnan(): return "NaN" inf = self._isinfinity() if inf == 1: return "+Infinity" if inf == -1: return "-Infinity" if self.is_zero(): if self._sign: return "-Zero" else: return "+Zero" if context is None: context = getcontext() if self.is_subnormal(context=context): if self._sign: return "-Subnormal" else: return "+Subnormal" # just a normal, regular, boring number, :) if self._sign: return "-Normal" else: return "+Normal"
[ "def", "number_class", "(", "self", ",", "context", "=", "None", ")", ":", "if", "self", ".", "is_snan", "(", ")", ":", "return", "\"sNaN\"", "if", "self", ".", "is_qnan", "(", ")", ":", "return", "\"NaN\"", "inf", "=", "self", ".", "_isinfinity", "(...
https://github.com/naftaliharris/tauthon/blob/5587ceec329b75f7caf6d65a036db61ac1bae214/Lib/decimal.py#L3484-L3524
HazyResearch/metal
b54631e9b94a3dcf55f6043c53ec181e12f29eb1
metal/analysis.py
python
_overlapped_data_points
(L)
return np.where(np.ravel((L != 0).sum(axis=1)) > 1, 1, 0)
Returns an indicator vector where ith element = 1 if x_i is labeled by more than one LF.
Returns an indicator vector where ith element = 1 if x_i is labeled by more than one LF.
[ "Returns", "an", "indicator", "vector", "where", "ith", "element", "=", "1", "if", "x_i", "is", "labeled", "by", "more", "than", "one", "LF", "." ]
def _overlapped_data_points(L): """Returns an indicator vector where ith element = 1 if x_i is labeled by more than one LF.""" return np.where(np.ravel((L != 0).sum(axis=1)) > 1, 1, 0)
[ "def", "_overlapped_data_points", "(", "L", ")", ":", "return", "np", ".", "where", "(", "np", ".", "ravel", "(", "(", "L", "!=", "0", ")", ".", "sum", "(", "axis", "=", "1", ")", ")", ">", "1", ",", "1", ",", "0", ")" ]
https://github.com/HazyResearch/metal/blob/b54631e9b94a3dcf55f6043c53ec181e12f29eb1/metal/analysis.py#L19-L22
IndicoDataSolutions/finetune
83ba222eed331df64b2fa7157bb64f0a2eef4a2c
finetune/optimizers/adafactor.py
python
AdafactorOptimizer.__init__
(self, multiply_by_parameter_scale=True, learning_rate=0.01, decay_rate=None, adafactor_beta1=0.0, clipping_threshold=1.0, factored=True, parameter_encoding=None, use_locking=False, name="Adafactor", epsilon1=1e-30, epsilon2=1e-3, **kwargs)
Construct a new Adafactor optimizer. See class comment. Args: multiply_by_parameter_scale: a boolean adafactor_learning_rate: an optional Scalar. decay_rate: an optional Scalar. adafactor_beta1: a float value between 0 and 1 clipping_threshold: an optional float >= 1 factored: a boolean - whether to use factored second-moment estimator for 2d variables simulated_quantize_bits: train with simulated quantized parameters (experimental) parameter_encoding: a ParameterEncoding object to use in the case of bfloat16 variables. use_locking: If True use locks for update operations. name: Optional name for the operations created when applying gradients. Defaults to "AdafactorOptimizer". epsilon1: Regularization constant for squared gradient. epsilon2: Regularization constant for parameter scale. Raises: ValueError: if absolute_update_scale and relative_update_scale_fn are both present or both absent.
Construct a new Adafactor optimizer.
[ "Construct", "a", "new", "Adafactor", "optimizer", "." ]
def __init__(self, multiply_by_parameter_scale=True, learning_rate=0.01, decay_rate=None, adafactor_beta1=0.0, clipping_threshold=1.0, factored=True, parameter_encoding=None, use_locking=False, name="Adafactor", epsilon1=1e-30, epsilon2=1e-3, **kwargs): """Construct a new Adafactor optimizer. See class comment. Args: multiply_by_parameter_scale: a boolean adafactor_learning_rate: an optional Scalar. decay_rate: an optional Scalar. adafactor_beta1: a float value between 0 and 1 clipping_threshold: an optional float >= 1 factored: a boolean - whether to use factored second-moment estimator for 2d variables simulated_quantize_bits: train with simulated quantized parameters (experimental) parameter_encoding: a ParameterEncoding object to use in the case of bfloat16 variables. use_locking: If True use locks for update operations. name: Optional name for the operations created when applying gradients. Defaults to "AdafactorOptimizer". epsilon1: Regularization constant for squared gradient. epsilon2: Regularization constant for parameter scale. Raises: ValueError: if absolute_update_scale and relative_update_scale_fn are both present or both absent. """ super(AdafactorOptimizer, self).__init__(use_locking, name) self._multiply_by_parameter_scale = multiply_by_parameter_scale if learning_rate is None: raise ValueError("Set Yo Learning rate") learning_rate = self._learning_rate_default(multiply_by_parameter_scale) self._learning_rate = learning_rate if decay_rate is None: decay_rate = self._decay_rate_default() self._decay_rate = decay_rate self._beta1 = adafactor_beta1 self._clipping_threshold = clipping_threshold self._factored = factored self._parameter_encoding = parameter_encoding self._epsilon1 = epsilon1 self._epsilon2 = epsilon2
[ "def", "__init__", "(", "self", ",", "multiply_by_parameter_scale", "=", "True", ",", "learning_rate", "=", "0.01", ",", "decay_rate", "=", "None", ",", "adafactor_beta1", "=", "0.0", ",", "clipping_threshold", "=", "1.0", ",", "factored", "=", "True", ",", ...
https://github.com/IndicoDataSolutions/finetune/blob/83ba222eed331df64b2fa7157bb64f0a2eef4a2c/finetune/optimizers/adafactor.py#L124-L167
Flexget/Flexget
ffad58f206278abefc88d63a1ffaa80476fc4d98
flexget/components/managed_lists/lists/entry_list/cli.py
python
entry_list_lists
(options)
Show all entry lists
Show all entry lists
[ "Show", "all", "entry", "lists" ]
def entry_list_lists(options): """Show all entry lists""" with Session() as session: lists = db.get_entry_lists(session=session) table = TerminalTable('#', 'List Name', table_type=options.table_type) for entry_list in lists: table.add_row(str(entry_list.id), entry_list.name) console(table)
[ "def", "entry_list_lists", "(", "options", ")", ":", "with", "Session", "(", ")", "as", "session", ":", "lists", "=", "db", ".", "get_entry_lists", "(", "session", "=", "session", ")", "table", "=", "TerminalTable", "(", "'#'", ",", "'List Name'", ",", "...
https://github.com/Flexget/Flexget/blob/ffad58f206278abefc88d63a1ffaa80476fc4d98/flexget/components/managed_lists/lists/entry_list/cli.py#L50-L57
mrkipling/maraschino
c6be9286937783ae01df2d6d8cebfc8b2734a7d7
lib/flask/helpers.py
python
flash
(message, category='message')
Flashes a message to the next request. In order to remove the flashed message from the session and to display it to the user, the template has to call :func:`get_flashed_messages`. .. versionchanged: 0.3 `category` parameter added. :param message: the message to be flashed. :param category: the category for the message. The following values are recommended: ``'message'`` for any kind of message, ``'error'`` for errors, ``'info'`` for information messages and ``'warning'`` for warnings. However any kind of string can be used as category.
Flashes a message to the next request. In order to remove the flashed message from the session and to display it to the user, the template has to call :func:`get_flashed_messages`.
[ "Flashes", "a", "message", "to", "the", "next", "request", ".", "In", "order", "to", "remove", "the", "flashed", "message", "from", "the", "session", "and", "to", "display", "it", "to", "the", "user", "the", "template", "has", "to", "call", ":", "func", ...
def flash(message, category='message'): """Flashes a message to the next request. In order to remove the flashed message from the session and to display it to the user, the template has to call :func:`get_flashed_messages`. .. versionchanged: 0.3 `category` parameter added. :param message: the message to be flashed. :param category: the category for the message. The following values are recommended: ``'message'`` for any kind of message, ``'error'`` for errors, ``'info'`` for information messages and ``'warning'`` for warnings. However any kind of string can be used as category. """ session.setdefault('_flashes', []).append((category, message))
[ "def", "flash", "(", "message", ",", "category", "=", "'message'", ")", ":", "session", ".", "setdefault", "(", "'_flashes'", ",", "[", "]", ")", ".", "append", "(", "(", "category", ",", "message", ")", ")" ]
https://github.com/mrkipling/maraschino/blob/c6be9286937783ae01df2d6d8cebfc8b2734a7d7/lib/flask/helpers.py#L234-L249
cloudera/hue
23f02102d4547c17c32bd5ea0eb24e9eadd657a4
desktop/core/ext-py/Django-1.11.29/django/db/migrations/state.py
python
ModelState.clone
(self)
return self.__class__( app_label=self.app_label, name=self.name, fields=list(self.fields), # Since options are shallow-copied here, operations such as # AddIndex must replace their option (e.g 'indexes') rather # than mutating it. options=dict(self.options), bases=self.bases, managers=list(self.managers), )
Returns an exact copy of this ModelState
Returns an exact copy of this ModelState
[ "Returns", "an", "exact", "copy", "of", "this", "ModelState" ]
def clone(self): "Returns an exact copy of this ModelState" return self.__class__( app_label=self.app_label, name=self.name, fields=list(self.fields), # Since options are shallow-copied here, operations such as # AddIndex must replace their option (e.g 'indexes') rather # than mutating it. options=dict(self.options), bases=self.bases, managers=list(self.managers), )
[ "def", "clone", "(", "self", ")", ":", "return", "self", ".", "__class__", "(", "app_label", "=", "self", ".", "app_label", ",", "name", "=", "self", ".", "name", ",", "fields", "=", "list", "(", "self", ".", "fields", ")", ",", "# Since options are sh...
https://github.com/cloudera/hue/blob/23f02102d4547c17c32bd5ea0eb24e9eadd657a4/desktop/core/ext-py/Django-1.11.29/django/db/migrations/state.py#L581-L593
FSecureLABS/Jandroid
e31d0dab58a2bfd6ed8e0a387172b8bd7c893436
libs/platform-tools/platform-tools_windows/systrace/catapult/third_party/pyserial/serial/serialutil.py
python
FileLike.__del__
(self)
Destructor. Calls close().
Destructor. Calls close().
[ "Destructor", ".", "Calls", "close", "()", "." ]
def __del__(self): """Destructor. Calls close().""" # The try/except block is in case this is called at program # exit time, when it's possible that globals have already been # deleted, and then the close() call might fail. Since # there's nothing we can do about such failures and they annoy # the end users, we suppress the traceback. try: self.close() except: pass
[ "def", "__del__", "(", "self", ")", ":", "# The try/except block is in case this is called at program", "# exit time, when it's possible that globals have already been", "# deleted, and then the close() call might fail. Since", "# there's nothing we can do about such failures and they annoy", "...
https://github.com/FSecureLABS/Jandroid/blob/e31d0dab58a2bfd6ed8e0a387172b8bd7c893436/libs/platform-tools/platform-tools_windows/systrace/catapult/third_party/pyserial/serial/serialutil.py#L133-L143
dciabrin/ngdevkit
6d50d4f29c7f8f0ccca05d2bfe53ba2036d32ccf
tools/tiletool.py
python
sprite_converter.open_rom
(self, mode)
I/O for pair of ROM files xxx-c1.c1 and xxx-c2.c2
I/O for pair of ROM files xxx-c1.c1 and xxx-c2.c2
[ "I", "/", "O", "for", "pair", "of", "ROM", "files", "xxx", "-", "c1", ".", "c1", "and", "xxx", "-", "c2", ".", "c2" ]
def open_rom(self, mode): """I/O for pair of ROM files xxx-c1.c1 and xxx-c2.c2""" self.fd1 = open(self.in1 if mode == 'rb' else self.out1, mode) self.fd2 = open(self.in2 if mode == 'rb' else self.out2, mode)
[ "def", "open_rom", "(", "self", ",", "mode", ")", ":", "self", ".", "fd1", "=", "open", "(", "self", ".", "in1", "if", "mode", "==", "'rb'", "else", "self", ".", "out1", ",", "mode", ")", "self", ".", "fd2", "=", "open", "(", "self", ".", "in2"...
https://github.com/dciabrin/ngdevkit/blob/6d50d4f29c7f8f0ccca05d2bfe53ba2036d32ccf/tools/tiletool.py#L236-L239
lawlite19/MachineLearning_TensorFlow
398acabb892607adf7795c34962bc75aba9d4afc
CNN_for_CIFAR-10/download.py
python
maybe_download_and_extract
(url, download_dir)
Download and extract the data if it doesn't already exist. Assumes the url is a tar-ball file. :param url: Internet URL for the tar-file to download. Example: "https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz" :param download_dir: Directory where the downloaded file is saved. Example: "data/CIFAR-10/" :return: Nothing.
Download and extract the data if it doesn't already exist. Assumes the url is a tar-ball file.
[ "Download", "and", "extract", "the", "data", "if", "it", "doesn", "t", "already", "exist", ".", "Assumes", "the", "url", "is", "a", "tar", "-", "ball", "file", "." ]
def maybe_download_and_extract(url, download_dir): """ Download and extract the data if it doesn't already exist. Assumes the url is a tar-ball file. :param url: Internet URL for the tar-file to download. Example: "https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz" :param download_dir: Directory where the downloaded file is saved. Example: "data/CIFAR-10/" :return: Nothing. """ # Filename for saving the file downloaded from the internet. # Use the filename from the URL and add it to the download_dir. filename = url.split('/')[-1] file_path = os.path.join(download_dir, filename) # Check if the file already exists. # If it exists then we assume it has also been extracted, # otherwise we need to download and extract it now. if not os.path.exists(file_path): # Check if the download directory exists, otherwise create it. if not os.path.exists(download_dir): os.makedirs(download_dir) # Download the file from the internet. file_path, _ = urllib.request.urlretrieve(url=url, filename=file_path, reporthook=_print_download_progress) print() print("Download finished. Extracting files.") if file_path.endswith(".zip"): # Unpack the zip-file. zipfile.ZipFile(file=file_path, mode="r").extractall(download_dir) elif file_path.endswith((".tar.gz", ".tgz")): # Unpack the tar-ball. tarfile.open(name=file_path, mode="r:gz").extractall(download_dir) print("Done.") else: print("Data has apparently already been downloaded and unpacked.")
[ "def", "maybe_download_and_extract", "(", "url", ",", "download_dir", ")", ":", "# Filename for saving the file downloaded from the internet.", "# Use the filename from the URL and add it to the download_dir.", "filename", "=", "url", ".", "split", "(", "'/'", ")", "[", "-", ...
https://github.com/lawlite19/MachineLearning_TensorFlow/blob/398acabb892607adf7795c34962bc75aba9d4afc/CNN_for_CIFAR-10/download.py#L48-L95
athena-team/athena
e704884ec6a3a947769d892aa267578038e49ecb
athena/models/fastspeech.py
python
FastSpeech.get_loss
(self, outputs, samples, training=None)
return loss, metrics
get loss used for training
get loss used for training
[ "get", "loss", "used", "for", "training" ]
def get_loss(self, outputs, samples, training=None): """ get loss used for training """ loss = self.loss_function(outputs, samples) total_loss = sum(list(loss.values())) if isinstance(loss, dict) else loss self.metric.update_state(total_loss) metrics = {self.metric.name: self.metric.result()} return loss, metrics
[ "def", "get_loss", "(", "self", ",", "outputs", ",", "samples", ",", "training", "=", "None", ")", ":", "loss", "=", "self", ".", "loss_function", "(", "outputs", ",", "samples", ")", "total_loss", "=", "sum", "(", "list", "(", "loss", ".", "values", ...
https://github.com/athena-team/athena/blob/e704884ec6a3a947769d892aa267578038e49ecb/athena/models/fastspeech.py#L217-L223
vim-scripts/UltiSnips
5f88199e373a7eea4644b8dc1ff433688e8f2ebd
pythonx/UltiSnips/snippet_manager.py
python
SnippetManager._cs
(self)
return self._csnippets[-1]
The current snippet or None.
The current snippet or None.
[ "The", "current", "snippet", "or", "None", "." ]
def _cs(self): """The current snippet or None.""" if not len(self._csnippets): return None return self._csnippets[-1]
[ "def", "_cs", "(", "self", ")", ":", "if", "not", "len", "(", "self", ".", "_csnippets", ")", ":", "return", "None", "return", "self", ".", "_csnippets", "[", "-", "1", "]" ]
https://github.com/vim-scripts/UltiSnips/blob/5f88199e373a7eea4644b8dc1ff433688e8f2ebd/pythonx/UltiSnips/snippet_manager.py#L730-L734
makerbot/ReplicatorG
d6f2b07785a5a5f1e172fb87cb4303b17c575d5d
skein_engines/skeinforge-47/skeinforge_application/skeinforge_plugins/craft_plugins/splodge.py
python
SplodgeSkein.getInitialSplodgeLine
( self, line, location )
return self.getSplodgeLineGivenDistance( self.initialSplodgeFeedRateMinute, line, self.splodgeRepository.initialLiftOverExtraThickness.value, location, self.initialStartupDistance )
Add the initial splodge line.
Add the initial splodge line.
[ "Add", "the", "initial", "splodge", "line", "." ]
def getInitialSplodgeLine( self, line, location ): "Add the initial splodge line." if not self.isJustBeforeExtrusion(): return line self.hasInitialSplodgeBeenAdded = True if self.splodgeRepository.initialSplodgeQuantityLength.value < self.minimumQuantityLength: return line return self.getSplodgeLineGivenDistance( self.initialSplodgeFeedRateMinute, line, self.splodgeRepository.initialLiftOverExtraThickness.value, location, self.initialStartupDistance )
[ "def", "getInitialSplodgeLine", "(", "self", ",", "line", ",", "location", ")", ":", "if", "not", "self", ".", "isJustBeforeExtrusion", "(", ")", ":", "return", "line", "self", ".", "hasInitialSplodgeBeenAdded", "=", "True", "if", "self", ".", "splodgeReposito...
https://github.com/makerbot/ReplicatorG/blob/d6f2b07785a5a5f1e172fb87cb4303b17c575d5d/skein_engines/skeinforge-47/skeinforge_application/skeinforge_plugins/craft_plugins/splodge.py#L183-L190
robhagemans/pcbasic
c3a043b46af66623a801e18a38175be077251ada
pcbasic/basic/basicevents.py
python
ComHandler.triggered
(self)
return self.device.char_waiting()
[]
def triggered(self): return self.device.char_waiting()
[ "def", "triggered", "(", "self", ")", ":", "return", "self", ".", "device", ".", "char_waiting", "(", ")" ]
https://github.com/robhagemans/pcbasic/blob/c3a043b46af66623a801e18a38175be077251ada/pcbasic/basic/basicevents.py#L263-L264
nash-io/neo-ico-template
0ad1af882ea470c77570cce0d27c43c4e49ec3b9
nex/crowdsale.py
python
can_exchange
(ctx, attachments, verify_only)
return exchange_ok
Determines if the contract invocation meets all requirements for the ICO exchange of neo or gas into NEP5 Tokens. Note: This method can be called via both the Verification portion of an SC or the Application portion When called in the Verification portion of an SC, it can be used to reject TX that do not qualify for exchange, thereby reducing the need for manual NEO or GAS refunds considerably :param attachments:Attachments An attachments object with information about attached NEO/Gas assets :return: bool: Whether an invocation meets requirements for exchange
Determines if the contract invocation meets all requirements for the ICO exchange of neo or gas into NEP5 Tokens. Note: This method can be called via both the Verification portion of an SC or the Application portion
[ "Determines", "if", "the", "contract", "invocation", "meets", "all", "requirements", "for", "the", "ICO", "exchange", "of", "neo", "or", "gas", "into", "NEP5", "Tokens", ".", "Note", ":", "This", "method", "can", "be", "called", "via", "both", "the", "Veri...
def can_exchange(ctx, attachments, verify_only): """ Determines if the contract invocation meets all requirements for the ICO exchange of neo or gas into NEP5 Tokens. Note: This method can be called via both the Verification portion of an SC or the Application portion When called in the Verification portion of an SC, it can be used to reject TX that do not qualify for exchange, thereby reducing the need for manual NEO or GAS refunds considerably :param attachments:Attachments An attachments object with information about attached NEO/Gas assets :return: bool: Whether an invocation meets requirements for exchange """ # if you are accepting gas, use this # if attachments[3] == 0: # print("no gas attached") # return False # if youre accepting neo, use this if attachments[2] == 0: return False # the following looks up whether an address has been # registered with the contract for KYC regulations # this is not required for operation of the contract # status = get_kyc_status(attachments.sender_addr, storage) if not get_kyc_status(ctx, attachments[1]): return False # caluclate the amount requested amount_requested = attachments[2] * TOKENS_PER_NEO / 100000000 # this would work for accepting gas # amount_requested = attachments.gas_attached * token.tokens_per_gas / 100000000 exchange_ok = calculate_can_exchange(ctx, amount_requested, attachments[1], verify_only) return exchange_ok
[ "def", "can_exchange", "(", "ctx", ",", "attachments", ",", "verify_only", ")", ":", "# if you are accepting gas, use this", "# if attachments[3] == 0:", "# print(\"no gas attached\")", "# return False", "# if youre accepting neo, use this", "if", "attach...
https://github.com/nash-io/neo-ico-template/blob/0ad1af882ea470c77570cce0d27c43c4e49ec3b9/nex/crowdsale.py#L106-L146
getnikola/nikola
2da876e9322e42a93f8295f950e336465c6a4ee5
nikola/hierarchy_utils.py
python
TreeNode.__init__
(self, name, parent=None)
Initialize node.
Initialize node.
[ "Initialize", "node", "." ]
def __init__(self, name, parent=None): """Initialize node.""" self.name = name self.parent = parent self.children = []
[ "def", "__init__", "(", "self", ",", "name", ",", "parent", "=", "None", ")", ":", "self", ".", "name", "=", "name", "self", ".", "parent", "=", "parent", "self", ".", "children", "=", "[", "]" ]
https://github.com/getnikola/nikola/blob/2da876e9322e42a93f8295f950e336465c6a4ee5/nikola/hierarchy_utils.py#L73-L77
home-assistant/core
265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1
homeassistant/helpers/reload.py
python
_async_setup_platform
( hass: HomeAssistant, integration_name: str, integration_platform: str, platform_configs: list[dict[str, Any]], )
Platform for the first time when new configuration is added.
Platform for the first time when new configuration is added.
[ "Platform", "for", "the", "first", "time", "when", "new", "configuration", "is", "added", "." ]
async def _async_setup_platform( hass: HomeAssistant, integration_name: str, integration_platform: str, platform_configs: list[dict[str, Any]], ) -> None: """Platform for the first time when new configuration is added.""" if integration_platform not in hass.data: await async_setup_component( hass, integration_platform, {integration_platform: platform_configs} ) return entity_component = hass.data[integration_platform] tasks = [ entity_component.async_setup_platform(integration_name, p_config) for p_config in platform_configs ] await asyncio.gather(*tasks)
[ "async", "def", "_async_setup_platform", "(", "hass", ":", "HomeAssistant", ",", "integration_name", ":", "str", ",", "integration_platform", ":", "str", ",", "platform_configs", ":", "list", "[", "dict", "[", "str", ",", "Any", "]", "]", ",", ")", "->", "...
https://github.com/home-assistant/core/blob/265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1/homeassistant/helpers/reload.py#L103-L121
scipy/scipy
e0a749f01e79046642ccfdc419edbf9e7ca141ad
scipy/io/arff/_arffread.py
python
RelationalAttribute.parse_attribute
(cls, name, attr_string)
Parse the attribute line if it knows how. Returns the parsed attribute, or None. For date attributes, the attribute string would be like 'date <format>'.
Parse the attribute line if it knows how. Returns the parsed attribute, or None.
[ "Parse", "the", "attribute", "line", "if", "it", "knows", "how", ".", "Returns", "the", "parsed", "attribute", "or", "None", "." ]
def parse_attribute(cls, name, attr_string): """ Parse the attribute line if it knows how. Returns the parsed attribute, or None. For date attributes, the attribute string would be like 'date <format>'. """ attr_string_lower = attr_string.lower().strip() if attr_string_lower[:len('relational')] == 'relational': return cls(name) else: return None
[ "def", "parse_attribute", "(", "cls", ",", "name", ",", "attr_string", ")", ":", "attr_string_lower", "=", "attr_string", ".", "lower", "(", ")", ".", "strip", "(", ")", "if", "attr_string_lower", "[", ":", "len", "(", "'relational'", ")", "]", "==", "'r...
https://github.com/scipy/scipy/blob/e0a749f01e79046642ccfdc419edbf9e7ca141ad/scipy/io/arff/_arffread.py#L348-L362
moses-palmer/pystray
c986535e00fbd3dfa003e51660eb03ba7c0a7f17
lib/pystray/_base.py
python
Icon.name
(self)
return self._name
The name passed to the constructor.
The name passed to the constructor.
[ "The", "name", "passed", "to", "the", "constructor", "." ]
def name(self): """The name passed to the constructor. """ return self._name
[ "def", "name", "(", "self", ")", ":", "return", "self", ".", "_name" ]
https://github.com/moses-palmer/pystray/blob/c986535e00fbd3dfa003e51660eb03ba7c0a7f17/lib/pystray/_base.py#L108-L111
ziberna/i3-py
27f88a616e9ecc340e7d041d3d00782f8a1964c1
examples/wsbar.py
python
Colors.get_color
(self, workspace, output)
Returns a (foreground, background) tuple based on given workspace state.
Returns a (foreground, background) tuple based on given workspace state.
[ "Returns", "a", "(", "foreground", "background", ")", "tuple", "based", "on", "given", "workspace", "state", "." ]
def get_color(self, workspace, output): """ Returns a (foreground, background) tuple based on given workspace state. """ if workspace['focused']: if output['current_workspace'] == workspace['name']: return self.focused else: return self.active if workspace['urgent']: return self.urgent else: return self.inactive
[ "def", "get_color", "(", "self", ",", "workspace", ",", "output", ")", ":", "if", "workspace", "[", "'focused'", "]", ":", "if", "output", "[", "'current_workspace'", "]", "==", "workspace", "[", "'name'", "]", ":", "return", "self", ".", "focused", "els...
https://github.com/ziberna/i3-py/blob/27f88a616e9ecc340e7d041d3d00782f8a1964c1/examples/wsbar.py#L51-L64
mwaskom/seaborn
77e3b6b03763d24cc99a8134ee9a6f43b32b8e7b
seaborn/distributions.py
python
_DistributionPlotter._plot_single_rug
(self, sub_data, var, height, ax, kws)
Draw a rugplot along one axis of the plot.
Draw a rugplot along one axis of the plot.
[ "Draw", "a", "rugplot", "along", "one", "axis", "of", "the", "plot", "." ]
def _plot_single_rug(self, sub_data, var, height, ax, kws): """Draw a rugplot along one axis of the plot.""" vector = sub_data[var] n = len(vector) # Return data to linear domain # This needs an automatic solution; see GH2409 if self._log_scaled(var): vector = np.power(10, vector) # We'll always add a single collection with varying colors if "hue" in self.variables: colors = self._hue_map(sub_data["hue"]) else: colors = None # Build the array of values for the LineCollection if var == "x": trans = tx.blended_transform_factory(ax.transData, ax.transAxes) xy_pairs = np.column_stack([ np.repeat(vector, 2), np.tile([0, height], n) ]) if var == "y": trans = tx.blended_transform_factory(ax.transAxes, ax.transData) xy_pairs = np.column_stack([ np.tile([0, height], n), np.repeat(vector, 2) ]) # Draw the lines on the plot line_segs = xy_pairs.reshape([n, 2, 2]) ax.add_collection(LineCollection( line_segs, transform=trans, colors=colors, **kws )) ax.autoscale_view(scalex=var == "x", scaley=var == "y")
[ "def", "_plot_single_rug", "(", "self", ",", "sub_data", ",", "var", ",", "height", ",", "ax", ",", "kws", ")", ":", "vector", "=", "sub_data", "[", "var", "]", "n", "=", "len", "(", "vector", ")", "# Return data to linear domain", "# This needs an automatic...
https://github.com/mwaskom/seaborn/blob/77e3b6b03763d24cc99a8134ee9a6f43b32b8e7b/seaborn/distributions.py#L1302-L1339
jython/jython3
def4f8ec47cb7a9c799ea4c745f12badf92c5769
lib-python/3.5.1/imaplib.py
python
IMAP4.getacl
(self, mailbox)
return self._untagged_response(typ, dat, 'ACL')
Get the ACLs for a mailbox. (typ, [data]) = <instance>.getacl(mailbox)
Get the ACLs for a mailbox.
[ "Get", "the", "ACLs", "for", "a", "mailbox", "." ]
def getacl(self, mailbox): """Get the ACLs for a mailbox. (typ, [data]) = <instance>.getacl(mailbox) """ typ, dat = self._simple_command('GETACL', mailbox) return self._untagged_response(typ, dat, 'ACL')
[ "def", "getacl", "(", "self", ",", "mailbox", ")", ":", "typ", ",", "dat", "=", "self", ".", "_simple_command", "(", "'GETACL'", ",", "mailbox", ")", "return", "self", ".", "_untagged_response", "(", "typ", ",", "dat", ",", "'ACL'", ")" ]
https://github.com/jython/jython3/blob/def4f8ec47cb7a9c799ea4c745f12badf92c5769/lib-python/3.5.1/imaplib.py#L522-L528
nipy/nibabel
4703f4d8e32be4cec30e829c2d93ebe54759bb62
nibabel/streamlines/tractogram.py
python
Tractogram.__len__
(self)
return len(self.streamlines)
[]
def __len__(self): return len(self.streamlines)
[ "def", "__len__", "(", "self", ")", ":", "return", "len", "(", "self", ".", "streamlines", ")" ]
https://github.com/nipy/nibabel/blob/4703f4d8e32be4cec30e829c2d93ebe54759bb62/nibabel/streamlines/tractogram.py#L392-L393
windelbouwman/ppci
915c069e0667042c085ec42c78e9e3c9a5295324
ppci/lang/c/nodes/types.py
python
is_void
(typ)
return isinstance(typ, BasicType) and typ.type_id == BasicType.VOID
Check if the given type is void
Check if the given type is void
[ "Check", "if", "the", "given", "type", "is", "void" ]
def is_void(typ): """ Check if the given type is void """ return isinstance(typ, BasicType) and typ.type_id == BasicType.VOID
[ "def", "is_void", "(", "typ", ")", ":", "return", "isinstance", "(", "typ", ",", "BasicType", ")", "and", "typ", ".", "type_id", "==", "BasicType", ".", "VOID" ]
https://github.com/windelbouwman/ppci/blob/915c069e0667042c085ec42c78e9e3c9a5295324/ppci/lang/c/nodes/types.py#L41-L43
stackimpact/stackimpact-python
4d0a415b790c89e7bee1d70216f948b7fec11540
stackimpact/profilers/block_profiler.py
python
BlockProfiler.start_profiler
(self)
[]
def start_profiler(self): self.agent.log('Activating block profiler.') signal.setitimer(signal.ITIMER_REAL, self.SAMPLING_RATE, self.SAMPLING_RATE)
[ "def", "start_profiler", "(", "self", ")", ":", "self", ".", "agent", ".", "log", "(", "'Activating block profiler.'", ")", "signal", ".", "setitimer", "(", "signal", ".", "ITIMER_REAL", ",", "self", ".", "SAMPLING_RATE", ",", "self", ".", "SAMPLING_RATE", "...
https://github.com/stackimpact/stackimpact-python/blob/4d0a415b790c89e7bee1d70216f948b7fec11540/stackimpact/profilers/block_profiler.py#L79-L82
home-assistant/core
265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1
homeassistant/components/demo/fan.py
python
DemoPercentageFan.percentage
(self)
return self._percentage
Return the current speed.
Return the current speed.
[ "Return", "the", "current", "speed", "." ]
def percentage(self) -> int | None: """Return the current speed.""" return self._percentage
[ "def", "percentage", "(", "self", ")", "->", "int", "|", "None", ":", "return", "self", ".", "_percentage" ]
https://github.com/home-assistant/core/blob/265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1/homeassistant/components/demo/fan.py#L163-L165
pvlib/pvlib-python
1ab0eb20f9cd9fb9f7a0ddf35f81283f2648e34a
pvlib/_version.py
python
git_get_keywords
(versionfile_abs)
return keywords
Extract version information from the given file.
Extract version information from the given file.
[ "Extract", "version", "information", "from", "the", "given", "file", "." ]
def git_get_keywords(versionfile_abs): """Extract version information from the given file.""" # the code embedded in _version.py can just fetch the value of these # keywords. When used from setup.py, we don't want to import _version.py, # so we do it with a regexp instead. This function is not used from # _version.py. keywords = {} try: f = open(versionfile_abs, "r") for line in f.readlines(): if line.strip().startswith("git_refnames ="): mo = re.search(r'=\s*"(.*)"', line) if mo: keywords["refnames"] = mo.group(1) if line.strip().startswith("git_full ="): mo = re.search(r'=\s*"(.*)"', line) if mo: keywords["full"] = mo.group(1) f.close() except EnvironmentError: pass return keywords
[ "def", "git_get_keywords", "(", "versionfile_abs", ")", ":", "# the code embedded in _version.py can just fetch the value of these", "# keywords. When used from setup.py, we don't want to import _version.py,", "# so we do it with a regexp instead. This function is not used from", "# _version.py.",...
https://github.com/pvlib/pvlib-python/blob/1ab0eb20f9cd9fb9f7a0ddf35f81283f2648e34a/pvlib/_version.py#L121-L142
stephenmcd/mezzanine
e38ffc69f732000ce44b7ed5c9d0516d258b8af2
mezzanine/generic/forms.py
python
ThreadedCommentForm.__init__
(self, request, *args, **kwargs)
Set some initial field values from cookies or the logged in user, and apply some HTML5 attributes to the fields if the ``FORMS_USE_HTML5`` setting is ``True``.
Set some initial field values from cookies or the logged in user, and apply some HTML5 attributes to the fields if the ``FORMS_USE_HTML5`` setting is ``True``.
[ "Set", "some", "initial", "field", "values", "from", "cookies", "or", "the", "logged", "in", "user", "and", "apply", "some", "HTML5", "attributes", "to", "the", "fields", "if", "the", "FORMS_USE_HTML5", "setting", "is", "True", "." ]
def __init__(self, request, *args, **kwargs): """ Set some initial field values from cookies or the logged in user, and apply some HTML5 attributes to the fields if the ``FORMS_USE_HTML5`` setting is ``True``. """ kwargs.setdefault("initial", {}) user = request.user for field in ThreadedCommentForm.cookie_fields: cookie_name = ThreadedCommentForm.cookie_prefix + field value = request.COOKIES.get(cookie_name, "") if not value and is_authenticated(user): if field == "name": value = user.get_full_name() if not value and user.username != user.email: value = user.username elif field == "email": value = user.email kwargs["initial"][field] = value super().__init__(*args, **kwargs)
[ "def", "__init__", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "kwargs", ".", "setdefault", "(", "\"initial\"", ",", "{", "}", ")", "user", "=", "request", ".", "user", "for", "field", "in", "ThreadedCommentForm", ...
https://github.com/stephenmcd/mezzanine/blob/e38ffc69f732000ce44b7ed5c9d0516d258b8af2/mezzanine/generic/forms.py#L103-L122
constverum/ProxyBroker
d21aae8575fc3a95493233ecfd2c7cf47b36b069
proxybroker/providers.py
python
My_proxy_com._pipe
(self)
[]
async def _pipe(self): exp = r'''href\s*=\s*['"]([^'"]?free-[^'"]*)['"]''' url = 'https://www.my-proxy.com/free-proxy-list.html' page = await self.get(url) urls = [ 'https://www.my-proxy.com/%s' % path for path in re.findall(exp, page) ] urls.append(url) await self._find_on_pages(urls)
[ "async", "def", "_pipe", "(", "self", ")", ":", "exp", "=", "r'''href\\s*=\\s*['\"]([^'\"]?free-[^'\"]*)['\"]'''", "url", "=", "'https://www.my-proxy.com/free-proxy-list.html'", "page", "=", "await", "self", ".", "get", "(", "url", ")", "urls", "=", "[", "'https://w...
https://github.com/constverum/ProxyBroker/blob/d21aae8575fc3a95493233ecfd2c7cf47b36b069/proxybroker/providers.py#L573-L582
Tencent/GAutomator
0ac9f849d1ca2c59760a91c5c94d3db375a380cd
GAutomatorIos/ga2/device/iOS/wda/__init__.py
python
Session.tap_hold
(self, x, y, duration=1.0)
return self.http.post('/wda/touchAndHold', data=data)
Tap and hold for a moment Args: - x, y(int): position - duration(float): seconds of hold time [[FBRoute POST:@"/wda/touchAndHold"] respondWithTarget:self action:@selector(handleTouchAndHoldCoordinate:)],
Tap and hold for a moment
[ "Tap", "and", "hold", "for", "a", "moment" ]
def tap_hold(self, x, y, duration=1.0): """ Tap and hold for a moment Args: - x, y(int): position - duration(float): seconds of hold time [[FBRoute POST:@"/wda/touchAndHold"] respondWithTarget:self action:@selector(handleTouchAndHoldCoordinate:)], """ self.check_alert() data = {'x': x, 'y': y, 'duration': duration} return self.http.post('/wda/touchAndHold', data=data)
[ "def", "tap_hold", "(", "self", ",", "x", ",", "y", ",", "duration", "=", "1.0", ")", ":", "self", ".", "check_alert", "(", ")", "data", "=", "{", "'x'", ":", "x", ",", "'y'", ":", "y", ",", "'duration'", ":", "duration", "}", "return", "self", ...
https://github.com/Tencent/GAutomator/blob/0ac9f849d1ca2c59760a91c5c94d3db375a380cd/GAutomatorIos/ga2/device/iOS/wda/__init__.py#L443-L455
jbjorne/TEES
caf19a4a1352ac59f5dc13a8684cc42ce4342d9d
Utils/Libraries/pstat.py
python
nonrepeats
(inlist)
return nonrepeats
Returns items that are NOT duplicated in the first dim of the passed list. Usage: nonrepeats (inlist)
Returns items that are NOT duplicated in the first dim of the passed list.
[ "Returns", "items", "that", "are", "NOT", "duplicated", "in", "the", "first", "dim", "of", "the", "passed", "list", "." ]
def nonrepeats(inlist): """ Returns items that are NOT duplicated in the first dim of the passed list. Usage: nonrepeats (inlist) """ nonrepeats = [] for i in range(len(inlist)): if inlist.count(inlist[i]) == 1: nonrepeats.append(inlist[i]) return nonrepeats
[ "def", "nonrepeats", "(", "inlist", ")", ":", "nonrepeats", "=", "[", "]", "for", "i", "in", "range", "(", "len", "(", "inlist", ")", ")", ":", "if", "inlist", ".", "count", "(", "inlist", "[", "i", "]", ")", "==", "1", ":", "nonrepeats", ".", ...
https://github.com/jbjorne/TEES/blob/caf19a4a1352ac59f5dc13a8684cc42ce4342d9d/Utils/Libraries/pstat.py#L686-L696
cmbruns/pyopenvr
ac4847a8a05cda0d4bcf7c4f243008b2a191c7a5
src/openvr/glframework/sdl_app.py
python
SdlApp.__exit__
(self, type_arg, value, traceback)
cleanup for RAII using 'with' keyword
cleanup for RAII using 'with' keyword
[ "cleanup", "for", "RAII", "using", "with", "keyword" ]
def __exit__(self, type_arg, value, traceback): "cleanup for RAII using 'with' keyword" print('SdlApp exiting') self.dispose_gl()
[ "def", "__exit__", "(", "self", ",", "type_arg", ",", "value", ",", "traceback", ")", ":", "print", "(", "'SdlApp exiting'", ")", "self", ".", "dispose_gl", "(", ")" ]
https://github.com/cmbruns/pyopenvr/blob/ac4847a8a05cda0d4bcf7c4f243008b2a191c7a5/src/openvr/glframework/sdl_app.py#L44-L47
tariqdaouda/pyGeno
6311c9cd94443e05b130d8b4babc24c374a77d7c
pyGeno/Transcript.py
python
Transcript.getCodon
(self, i)
return self.getNucleotideCodon(i*3)[0]
returns the ith codon
returns the ith codon
[ "returns", "the", "ith", "codon" ]
def getCodon(self, i) : """returns the ith codon""" return self.getNucleotideCodon(i*3)[0]
[ "def", "getCodon", "(", "self", ",", "i", ")", ":", "return", "self", ".", "getNucleotideCodon", "(", "i", "*", "3", ")", "[", "0", "]" ]
https://github.com/tariqdaouda/pyGeno/blob/6311c9cd94443e05b130d8b4babc24c374a77d7c/pyGeno/Transcript.py#L161-L163
kubernetes-client/python
47b9da9de2d02b2b7a34fbe05afb44afd130d73a
kubernetes/client/models/v1_json_schema_props.py
python
V1JSONSchemaProps.dependencies
(self, dependencies)
Sets the dependencies of this V1JSONSchemaProps. :param dependencies: The dependencies of this V1JSONSchemaProps. # noqa: E501 :type: dict(str, object)
Sets the dependencies of this V1JSONSchemaProps.
[ "Sets", "the", "dependencies", "of", "this", "V1JSONSchemaProps", "." ]
def dependencies(self, dependencies): """Sets the dependencies of this V1JSONSchemaProps. :param dependencies: The dependencies of this V1JSONSchemaProps. # noqa: E501 :type: dict(str, object) """ self._dependencies = dependencies
[ "def", "dependencies", "(", "self", ",", "dependencies", ")", ":", "self", ".", "_dependencies", "=", "dependencies" ]
https://github.com/kubernetes-client/python/blob/47b9da9de2d02b2b7a34fbe05afb44afd130d73a/kubernetes/client/models/v1_json_schema_props.py#L450-L458
linxid/Machine_Learning_Study_Path
558e82d13237114bbb8152483977806fc0c222af
Machine Learning In Action/Chapter8-Regression/venv/Lib/site-packages/pip-9.0.1-py3.6.egg/pip/commands/show.py
python
ShowCommand.__init__
(self, *args, **kw)
[]
def __init__(self, *args, **kw): super(ShowCommand, self).__init__(*args, **kw) self.cmd_opts.add_option( '-f', '--files', dest='files', action='store_true', default=False, help='Show the full list of installed files for each package.') self.parser.insert_option_group(0, self.cmd_opts)
[ "def", "__init__", "(", "self", ",", "*", "args", ",", "*", "*", "kw", ")", ":", "super", "(", "ShowCommand", ",", "self", ")", ".", "__init__", "(", "*", "args", ",", "*", "*", "kw", ")", "self", ".", "cmd_opts", ".", "add_option", "(", "'-f'", ...
https://github.com/linxid/Machine_Learning_Study_Path/blob/558e82d13237114bbb8152483977806fc0c222af/Machine Learning In Action/Chapter8-Regression/venv/Lib/site-packages/pip-9.0.1-py3.6.egg/pip/commands/show.py#L23-L32
holzschu/Carnets
44effb10ddfc6aa5c8b0687582a724ba82c6b547
Library/lib/python3.7/_collections_abc.py
python
MutableSequence.insert
(self, index, value)
S.insert(index, value) -- insert value before index
S.insert(index, value) -- insert value before index
[ "S", ".", "insert", "(", "index", "value", ")", "--", "insert", "value", "before", "index" ]
def insert(self, index, value): 'S.insert(index, value) -- insert value before index' raise IndexError
[ "def", "insert", "(", "self", ",", "index", ",", "value", ")", ":", "raise", "IndexError" ]
https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/_collections_abc.py#L965-L967
prof7bit/goxtool
e307f12df2df37a3a109953e805ad19d6c6e0628
goxtool.py
python
try_get_lock_or_break_open
()
this is an ugly hack to workaround possible deadlock problems. It is used during shutdown to make sure we can properly exit even when some slot is stuck (due to a programming error) and won't release the lock. If we can't acquire it within 2 seconds we just break it open forcefully.
this is an ugly hack to workaround possible deadlock problems. It is used during shutdown to make sure we can properly exit even when some slot is stuck (due to a programming error) and won't release the lock. If we can't acquire it within 2 seconds we just break it open forcefully.
[ "this", "is", "an", "ugly", "hack", "to", "workaround", "possible", "deadlock", "problems", ".", "It", "is", "used", "during", "shutdown", "to", "make", "sure", "we", "can", "properly", "exit", "even", "when", "some", "slot", "is", "stuck", "(", "due", "...
def try_get_lock_or_break_open(): """this is an ugly hack to workaround possible deadlock problems. It is used during shutdown to make sure we can properly exit even when some slot is stuck (due to a programming error) and won't release the lock. If we can't acquire it within 2 seconds we just break it open forcefully.""" #pylint: disable=W0212 time_end = time.time() + 2 while time.time() < time_end: if goxapi.Signal._lock.acquire(False): return time.sleep(0.001) # something keeps holding the lock, apparently some slot is stuck # in an infinite loop. In order to be able to shut down anyways # we just throw away that lock and replace it with a new one lock = threading.RLock() lock.acquire() goxapi.Signal._lock = lock print "### could not acquire signal lock, frozen slot somewhere?" print "### please see the stacktrace log to determine the cause."
[ "def", "try_get_lock_or_break_open", "(", ")", ":", "#pylint: disable=W0212", "time_end", "=", "time", ".", "time", "(", ")", "+", "2", "while", "time", ".", "time", "(", ")", "<", "time_end", ":", "if", "goxapi", ".", "Signal", ".", "_lock", ".", "acqui...
https://github.com/prof7bit/goxtool/blob/e307f12df2df37a3a109953e805ad19d6c6e0628/goxtool.py#L123-L142
FederatedAI/FATE
32540492623568ecd1afcb367360133616e02fa3
python/fate_arch/federation/transfer_variable.py
python
Variable.set_preserve_num
(self, n)
return self
[]
def set_preserve_num(self, n): self._get_gc.set_capacity(n) self._remote_gc.set_capacity(n) return self
[ "def", "set_preserve_num", "(", "self", ",", "n", ")", ":", "self", ".", "_get_gc", ".", "set_capacity", "(", "n", ")", "self", ".", "_remote_gc", ".", "set_capacity", "(", "n", ")", "return", "self" ]
https://github.com/FederatedAI/FATE/blob/32540492623568ecd1afcb367360133616e02fa3/python/fate_arch/federation/transfer_variable.py#L135-L138
riptideio/pymodbus
c5772b35ae3f29d1947f3ab453d8d00df846459f
pymodbus/client/asynchronous/async_io/__init__.py
python
ReconnectingAsyncioModbusTlsClient._create_protocol
(self)
return protocol
Factory function to create initialized protocol instance.
Factory function to create initialized protocol instance.
[ "Factory", "function", "to", "create", "initialized", "protocol", "instance", "." ]
def _create_protocol(self): """ Factory function to create initialized protocol instance. """ protocol = self.protocol_class(framer=self.framer, **self._proto_args) protocol.transaction = FifoTransactionManager(self) protocol.factory = self return protocol
[ "def", "_create_protocol", "(", "self", ")", ":", "protocol", "=", "self", ".", "protocol_class", "(", "framer", "=", "self", ".", "framer", ",", "*", "*", "self", ".", "_proto_args", ")", "protocol", ".", "transaction", "=", "FifoTransactionManager", "(", ...
https://github.com/riptideio/pymodbus/blob/c5772b35ae3f29d1947f3ab453d8d00df846459f/pymodbus/client/asynchronous/async_io/__init__.py#L491-L498
misterch0c/shadowbroker
e3a069bea47a2c1009697941ac214adc6f90aa8d
windows/Resources/Python/Core/Lib/py_compile.py
python
compile
(file, cfile=None, dfile=None, doraise=False)
return
Byte-compile one Python source file to Python bytecode. Arguments: file: source filename cfile: target filename; defaults to source with 'c' or 'o' appended ('c' normally, 'o' in optimizing mode, giving .pyc or .pyo) dfile: purported filename; defaults to source (this is the filename that will show up in error messages) doraise: flag indicating whether or not an exception should be raised when a compile error is found. If an exception occurs and this flag is set to False, a string indicating the nature of the exception will be printed, and the function will return to the caller. If an exception occurs and this flag is set to True, a PyCompileError exception will be raised. Note that it isn't necessary to byte-compile Python modules for execution efficiency -- Python itself byte-compiles a module when it is loaded, and if it can, writes out the bytecode to the corresponding .pyc (or .pyo) file. However, if a Python installation is shared between users, it is a good idea to byte-compile all modules upon installation, since other users may not be able to write in the source directories, and thus they won't be able to write the .pyc/.pyo file, and then they would be byte-compiling every module each time it is loaded. This can slow down program start-up considerably. See compileall.py for a script/module that uses this module to byte-compile all installed files (or all files in selected directories).
Byte-compile one Python source file to Python bytecode. Arguments: file: source filename cfile: target filename; defaults to source with 'c' or 'o' appended ('c' normally, 'o' in optimizing mode, giving .pyc or .pyo) dfile: purported filename; defaults to source (this is the filename that will show up in error messages) doraise: flag indicating whether or not an exception should be raised when a compile error is found. If an exception occurs and this flag is set to False, a string indicating the nature of the exception will be printed, and the function will return to the caller. If an exception occurs and this flag is set to True, a PyCompileError exception will be raised. Note that it isn't necessary to byte-compile Python modules for execution efficiency -- Python itself byte-compiles a module when it is loaded, and if it can, writes out the bytecode to the corresponding .pyc (or .pyo) file. However, if a Python installation is shared between users, it is a good idea to byte-compile all modules upon installation, since other users may not be able to write in the source directories, and thus they won't be able to write the .pyc/.pyo file, and then they would be byte-compiling every module each time it is loaded. This can slow down program start-up considerably. See compileall.py for a script/module that uses this module to byte-compile all installed files (or all files in selected directories).
[ "Byte", "-", "compile", "one", "Python", "source", "file", "to", "Python", "bytecode", ".", "Arguments", ":", "file", ":", "source", "filename", "cfile", ":", "target", "filename", ";", "defaults", "to", "source", "with", "c", "or", "o", "appended", "(", ...
def compile(file, cfile=None, dfile=None, doraise=False): """Byte-compile one Python source file to Python bytecode. Arguments: file: source filename cfile: target filename; defaults to source with 'c' or 'o' appended ('c' normally, 'o' in optimizing mode, giving .pyc or .pyo) dfile: purported filename; defaults to source (this is the filename that will show up in error messages) doraise: flag indicating whether or not an exception should be raised when a compile error is found. If an exception occurs and this flag is set to False, a string indicating the nature of the exception will be printed, and the function will return to the caller. If an exception occurs and this flag is set to True, a PyCompileError exception will be raised. Note that it isn't necessary to byte-compile Python modules for execution efficiency -- Python itself byte-compiles a module when it is loaded, and if it can, writes out the bytecode to the corresponding .pyc (or .pyo) file. However, if a Python installation is shared between users, it is a good idea to byte-compile all modules upon installation, since other users may not be able to write in the source directories, and thus they won't be able to write the .pyc/.pyo file, and then they would be byte-compiling every module each time it is loaded. This can slow down program start-up considerably. See compileall.py for a script/module that uses this module to byte-compile all installed files (or all files in selected directories). """ with open(file, 'U') as f: try: timestamp = long(os.fstat(f.fileno()).st_mtime) except AttributeError: timestamp = long(os.stat(file).st_mtime) codestring = f.read() try: codeobject = __builtin__.compile(codestring, dfile or file, 'exec') except Exception as err: py_exc = PyCompileError(err.__class__, err.args, dfile or file) if doraise: raise py_exc else: sys.stderr.write(py_exc.msg + '\n') return if cfile is None: cfile = file + (__debug__ and 'c' or 'o') with open(cfile, 'wb') as fc: fc.write('\x00\x00\x00\x00') wr_long(fc, timestamp) marshal.dump(codeobject, fc) fc.flush() fc.seek(0, 0) fc.write(MAGIC) return
[ "def", "compile", "(", "file", ",", "cfile", "=", "None", ",", "dfile", "=", "None", ",", "doraise", "=", "False", ")", ":", "with", "open", "(", "file", ",", "'U'", ")", "as", "f", ":", "try", ":", "timestamp", "=", "long", "(", "os", ".", "fs...
https://github.com/misterch0c/shadowbroker/blob/e3a069bea47a2c1009697941ac214adc6f90aa8d/windows/Resources/Python/Core/Lib/py_compile.py#L72-L133
lutris/lutris
66675a4d5537f6b2a2ba2b6df0b3cdf8924c823a
lutris/util/wine/fsync.py
python
_get_futex_waitv_syscall_nr
()
return _get_syscall_nr_from_headers('futex_waitv')
Get the syscall number of the Linux futex_waitv() syscall. Returns: The futex_waitv() syscall number. Raises: RuntimeError: When the syscall number could not be determined.
Get the syscall number of the Linux futex_waitv() syscall.
[ "Get", "the", "syscall", "number", "of", "the", "Linux", "futex_waitv", "()", "syscall", "." ]
def _get_futex_waitv_syscall_nr(): """Get the syscall number of the Linux futex_waitv() syscall. Returns: The futex_waitv() syscall number. Raises: RuntimeError: When the syscall number could not be determined. """ bits = ctypes.sizeof(ctypes.c_void_p) * 8 try: return _NR_FUTEX_WAITV_PER_ARCH[(os.uname()[4], bits)] except KeyError: pass return _get_syscall_nr_from_headers('futex_waitv')
[ "def", "_get_futex_waitv_syscall_nr", "(", ")", ":", "bits", "=", "ctypes", ".", "sizeof", "(", "ctypes", ".", "c_void_p", ")", "*", "8", "try", ":", "return", "_NR_FUTEX_WAITV_PER_ARCH", "[", "(", "os", ".", "uname", "(", ")", "[", "4", "]", ",", "bit...
https://github.com/lutris/lutris/blob/66675a4d5537f6b2a2ba2b6df0b3cdf8924c823a/lutris/util/wine/fsync.py#L302-L318
IJDykeman/wangTiles
7c1ee2095ebdf7f72bce07d94c6484915d5cae8b
experimental_code/tiles_3d/venv_mac/lib/python2.7/site-packages/pkg_resources/_vendor/packaging/specifiers.py
python
BaseSpecifier.__hash__
(self)
Returns a hash value for this Specifier like object.
Returns a hash value for this Specifier like object.
[ "Returns", "a", "hash", "value", "for", "this", "Specifier", "like", "object", "." ]
def __hash__(self): """ Returns a hash value for this Specifier like object. """
[ "def", "__hash__", "(", "self", ")", ":" ]
https://github.com/IJDykeman/wangTiles/blob/7c1ee2095ebdf7f72bce07d94c6484915d5cae8b/experimental_code/tiles_3d/venv_mac/lib/python2.7/site-packages/pkg_resources/_vendor/packaging/specifiers.py#L31-L34
annoviko/pyclustering
bf4f51a472622292627ec8c294eb205585e50f52
pyclustering/cluster/bang.py
python
bang_block.__init__
(self, data, region, level, space_block, cache_points=False)
! @brief Create BANG-block. @param[in] data (list): List of points that are processed. @param[in] region (uint): Region number - unique value on a level. @param[in] level (uint): Level number where block is created. @param[in] space_block (spatial_block): Spatial block description in data space. @param[in] cache_points (bool): if True then points are stored in memory (used for leaf blocks).
! @brief Create BANG-block.
[ "!", "@brief", "Create", "BANG", "-", "block", "." ]
def __init__(self, data, region, level, space_block, cache_points=False): """! @brief Create BANG-block. @param[in] data (list): List of points that are processed. @param[in] region (uint): Region number - unique value on a level. @param[in] level (uint): Level number where block is created. @param[in] space_block (spatial_block): Spatial block description in data space. @param[in] cache_points (bool): if True then points are stored in memory (used for leaf blocks). """ self.__data = data self.__region_number = region self.__level = level self.__spatial_block = space_block self.__cache_points = cache_points self.__cluster = None self.__points = None self.__amount_points = self.__get_amount_points() self.__density = self.__calculate_density(self.__amount_points)
[ "def", "__init__", "(", "self", ",", "data", ",", "region", ",", "level", ",", "space_block", ",", "cache_points", "=", "False", ")", ":", "self", ".", "__data", "=", "data", "self", ".", "__region_number", "=", "region", "self", ".", "__level", "=", "...
https://github.com/annoviko/pyclustering/blob/bf4f51a472622292627ec8c294eb205585e50f52/pyclustering/cluster/bang.py#L746-L766
andresriancho/w3af
cd22e5252243a87aaa6d0ddea47cf58dacfe00a9
w3af/plugins/attack/db/sqlmap/lib/core/dump.py
python
Dump.dbTablesCount
(self, dbTables)
[]
def dbTablesCount(self, dbTables): if isinstance(dbTables, dict) and len(dbTables) > 0: if conf.api: self._write(dbTables, content_type=CONTENT_TYPE.COUNT) return maxlength1 = len("Table") maxlength2 = len("Entries") for ctables in dbTables.values(): for tables in ctables.values(): for table in tables: maxlength1 = max(maxlength1, len(normalizeUnicode(table) or unicode(table))) for db, counts in dbTables.items(): self._write("Database: %s" % unsafeSQLIdentificatorNaming(db) if db else "Current database") lines1 = "-" * (maxlength1 + 2) blank1 = " " * (maxlength1 - len("Table")) lines2 = "-" * (maxlength2 + 2) blank2 = " " * (maxlength2 - len("Entries")) self._write("+%s+%s+" % (lines1, lines2)) self._write("| Table%s | Entries%s |" % (blank1, blank2)) self._write("+%s+%s+" % (lines1, lines2)) sortedCounts = counts.keys() sortedCounts.sort(reverse=True) for count in sortedCounts: tables = counts[count] if count is None: count = "Unknown" tables.sort(key=lambda x: x.lower() if isinstance(x, basestring) else x) for table in tables: blank1 = " " * (maxlength1 - len(normalizeUnicode(table) or unicode(table))) blank2 = " " * (maxlength2 - len(str(count))) self._write("| %s%s | %d%s |" % (table, blank1, count, blank2)) self._write("+%s+%s+\n" % (lines1, lines2)) else: logger.error("unable to retrieve the number of entries for any table")
[ "def", "dbTablesCount", "(", "self", ",", "dbTables", ")", ":", "if", "isinstance", "(", "dbTables", ",", "dict", ")", "and", "len", "(", "dbTables", ")", ">", "0", ":", "if", "conf", ".", "api", ":", "self", ".", "_write", "(", "dbTables", ",", "c...
https://github.com/andresriancho/w3af/blob/cd22e5252243a87aaa6d0ddea47cf58dacfe00a9/w3af/plugins/attack/db/sqlmap/lib/core/dump.py#L345-L389
krintoxi/NoobSec-Toolkit
38738541cbc03cedb9a3b3ed13b629f781ad64f6
NoobSecToolkit /tools/inject/plugins/dbms/maxdb/enumeration.py
python
Enumeration.searchDb
(self)
return []
[]
def searchDb(self): warnMsg = "on SAP MaxDB it is not possible to search databases" logger.warn(warnMsg) return []
[ "def", "searchDb", "(", "self", ")", ":", "warnMsg", "=", "\"on SAP MaxDB it is not possible to search databases\"", "logger", ".", "warn", "(", "warnMsg", ")", "return", "[", "]" ]
https://github.com/krintoxi/NoobSec-Toolkit/blob/38738541cbc03cedb9a3b3ed13b629f781ad64f6/NoobSecToolkit /tools/inject/plugins/dbms/maxdb/enumeration.py#L171-L175
leancloud/satori
701caccbd4fe45765001ca60435c0cb499477c03
satori-rules/plugin/libs/pymysql/connections.py
python
MySQLResult._finish_unbuffered_query
(self)
[]
def _finish_unbuffered_query(self): # After much reading on the MySQL protocol, it appears that there is, # in fact, no way to stop MySQL from sending all the data after # executing a query, so we just spin, and wait for an EOF packet. while self.unbuffered_active: packet = self.connection._read_packet() if self._check_packet_is_eof(packet): self.unbuffered_active = False self.connection = None
[ "def", "_finish_unbuffered_query", "(", "self", ")", ":", "# After much reading on the MySQL protocol, it appears that there is,", "# in fact, no way to stop MySQL from sending all the data after", "# executing a query, so we just spin, and wait for an EOF packet.", "while", "self", ".", "un...
https://github.com/leancloud/satori/blob/701caccbd4fe45765001ca60435c0cb499477c03/satori-rules/plugin/libs/pymysql/connections.py#L1392-L1400
KalleHallden/AutoTimer
2d954216700c4930baa154e28dbddc34609af7ce
env/lib/python2.7/site-packages/pkg_resources/__init__.py
python
WorkingSet.require
(self, *requirements)
return needed
Ensure that distributions matching `requirements` are activated `requirements` must be a string or a (possibly-nested) sequence thereof, specifying the distributions and versions required. The return value is a sequence of the distributions that needed to be activated to fulfill the requirements; all relevant distributions are included, even if they were already activated in this working set.
Ensure that distributions matching `requirements` are activated
[ "Ensure", "that", "distributions", "matching", "requirements", "are", "activated" ]
def require(self, *requirements): """Ensure that distributions matching `requirements` are activated `requirements` must be a string or a (possibly-nested) sequence thereof, specifying the distributions and versions required. The return value is a sequence of the distributions that needed to be activated to fulfill the requirements; all relevant distributions are included, even if they were already activated in this working set. """ needed = self.resolve(parse_requirements(requirements)) for dist in needed: self.add(dist) return needed
[ "def", "require", "(", "self", ",", "*", "requirements", ")", ":", "needed", "=", "self", ".", "resolve", "(", "parse_requirements", "(", "requirements", ")", ")", "for", "dist", "in", "needed", ":", "self", ".", "add", "(", "dist", ")", "return", "nee...
https://github.com/KalleHallden/AutoTimer/blob/2d954216700c4930baa154e28dbddc34609af7ce/env/lib/python2.7/site-packages/pkg_resources/__init__.py#L891-L905
omz/PythonistaAppTemplate
f560f93f8876d82a21d108977f90583df08d55af
PythonistaAppTemplate/PythonistaKit.framework/pylib/site-packages/pycparser/c_parser.py
python
CParser.p_initializer_1
(self, p)
initializer : assignment_expression
initializer : assignment_expression
[ "initializer", ":", "assignment_expression" ]
def p_initializer_1(self, p): """ initializer : assignment_expression """ p[0] = p[1]
[ "def", "p_initializer_1", "(", "self", ",", "p", ")", ":", "p", "[", "0", "]", "=", "p", "[", "1", "]" ]
https://github.com/omz/PythonistaAppTemplate/blob/f560f93f8876d82a21d108977f90583df08d55af/PythonistaAppTemplate/PythonistaKit.framework/pylib/site-packages/pycparser/c_parser.py#L1122-L1125
tensorflow/lingvo
ce10019243d954c3c3ebe739f7589b5eebfdf907
lingvo/core/builder_layers.py
python
ReshapeLayer.FProp
(self, theta, inp)
return tf.nest.map_structure(lambda t: tf.reshape(t, p.shape), inp)
Reshape the inputs. Args: theta: A `.NestedMap` object containing variable values. inp: A tensor or `.NestedMap` object containing inputs to reshape. Returns: A tensor or `.NestedMap` with the same structure as the input.
Reshape the inputs.
[ "Reshape", "the", "inputs", "." ]
def FProp(self, theta, inp): """Reshape the inputs. Args: theta: A `.NestedMap` object containing variable values. inp: A tensor or `.NestedMap` object containing inputs to reshape. Returns: A tensor or `.NestedMap` with the same structure as the input. """ p = self.params return tf.nest.map_structure(lambda t: tf.reshape(t, p.shape), inp)
[ "def", "FProp", "(", "self", ",", "theta", ",", "inp", ")", ":", "p", "=", "self", ".", "params", "return", "tf", ".", "nest", ".", "map_structure", "(", "lambda", "t", ":", "tf", ".", "reshape", "(", "t", ",", "p", ".", "shape", ")", ",", "inp...
https://github.com/tensorflow/lingvo/blob/ce10019243d954c3c3ebe739f7589b5eebfdf907/lingvo/core/builder_layers.py#L1393-L1404
ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework
cb692f527e4e819b6c228187c5702d990a180043
external/Scripting Engine/packages/IronPython.StdLib.2.7.4/content/Lib/profile.py
python
runctx
(statement, globals, locals, filename=None, sort=-1)
Run statement under profiler, supplying your own globals and locals, optionally saving results in filename. statement and filename have the same semantics as profile.run
Run statement under profiler, supplying your own globals and locals, optionally saving results in filename.
[ "Run", "statement", "under", "profiler", "supplying", "your", "own", "globals", "and", "locals", "optionally", "saving", "results", "in", "filename", "." ]
def runctx(statement, globals, locals, filename=None, sort=-1): """Run statement under profiler, supplying your own globals and locals, optionally saving results in filename. statement and filename have the same semantics as profile.run """ prof = Profile() try: prof = prof.runctx(statement, globals, locals) except SystemExit: pass if filename is not None: prof.dump_stats(filename) else: return prof.print_stats(sort)
[ "def", "runctx", "(", "statement", ",", "globals", ",", "locals", ",", "filename", "=", "None", ",", "sort", "=", "-", "1", ")", ":", "prof", "=", "Profile", "(", ")", "try", ":", "prof", "=", "prof", ".", "runctx", "(", "statement", ",", "globals"...
https://github.com/ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework/blob/cb692f527e4e819b6c228187c5702d990a180043/external/Scripting Engine/packages/IronPython.StdLib.2.7.4/content/Lib/profile.py#L78-L93
CvvT/dumpDex
92ab3b7e996194a06bf1dd5538a4954e8a5ee9c1
python/idaapi.py
python
hexwarns_t.insert
(self, *args)
return _idaapi.hexwarns_t_insert(self, *args)
insert(self, it, x) -> hexwarn_t
insert(self, it, x) -> hexwarn_t
[ "insert", "(", "self", "it", "x", ")", "-", ">", "hexwarn_t" ]
def insert(self, *args): """ insert(self, it, x) -> hexwarn_t """ return _idaapi.hexwarns_t_insert(self, *args)
[ "def", "insert", "(", "self", ",", "*", "args", ")", ":", "return", "_idaapi", ".", "hexwarns_t_insert", "(", "self", ",", "*", "args", ")" ]
https://github.com/CvvT/dumpDex/blob/92ab3b7e996194a06bf1dd5538a4954e8a5ee9c1/python/idaapi.py#L33390-L33394
lovelylain/pyctp
fd304de4b50c4ddc31a4190b1caaeb5dec66bc5d
futures2/ctp/ApiStruct.py
python
InputBatchOrderAction.__init__
(self, BrokerID='', InvestorID='', OrderActionRef=0, RequestID=0, FrontID=0, SessionID=0, ExchangeID='', UserID='')
[]
def __init__(self, BrokerID='', InvestorID='', OrderActionRef=0, RequestID=0, FrontID=0, SessionID=0, ExchangeID='', UserID=''): self.BrokerID = '' #经纪公司代码, char[11] self.InvestorID = '' #投资者代码, char[13] self.OrderActionRef = '' #报单操作引用, int self.RequestID = '' #请求编号, int self.FrontID = '' #前置编号, int self.SessionID = '' #会话编号, int self.ExchangeID = '' #交易所代码, char[9] self.UserID = ''
[ "def", "__init__", "(", "self", ",", "BrokerID", "=", "''", ",", "InvestorID", "=", "''", ",", "OrderActionRef", "=", "0", ",", "RequestID", "=", "0", ",", "FrontID", "=", "0", ",", "SessionID", "=", "0", ",", "ExchangeID", "=", "''", ",", "UserID", ...
https://github.com/lovelylain/pyctp/blob/fd304de4b50c4ddc31a4190b1caaeb5dec66bc5d/futures2/ctp/ApiStruct.py#L3814-L3822
Yonsm/.homeassistant
4d9a0070d0fcd8a5ded46e7884da9a4494bbbf26
extras/homeassistant/components/braviatv/media_player.py
python
BraviaTVMediaPlayer.async_set_volume_level
(self, volume)
Set volume level, range 0..1.
Set volume level, range 0..1.
[ "Set", "volume", "level", "range", "0", "..", "1", "." ]
async def async_set_volume_level(self, volume): """Set volume level, range 0..1.""" await self.coordinator.async_set_volume_level(volume)
[ "async", "def", "async_set_volume_level", "(", "self", ",", "volume", ")", ":", "await", "self", ".", "coordinator", ".", "async_set_volume_level", "(", "volume", ")" ]
https://github.com/Yonsm/.homeassistant/blob/4d9a0070d0fcd8a5ded46e7884da9a4494bbbf26/extras/homeassistant/components/braviatv/media_player.py#L119-L121
emesene/emesene
4548a4098310e21b16437bb36223a7f632a4f7bc
emesene/e3/papylib/papyon/papyon/event/conversation.py
python
ConversationEventInterface.on_conversation_error
(self, type, error)
Called when an error occurs in the L{Client<papyon.conversation>}. @param type: the error type @type type: L{ClientErrorType} @param error: the error code @type error: L{NetworkError} or L{AuthenticationError} or L{ProtocolError} or L{ContactInviteError} or L{MessageError}
Called when an error occurs in the L{Client<papyon.conversation>}.
[ "Called", "when", "an", "error", "occurs", "in", "the", "L", "{", "Client<papyon", ".", "conversation", ">", "}", "." ]
def on_conversation_error(self, type, error): """Called when an error occurs in the L{Client<papyon.conversation>}. @param type: the error type @type type: L{ClientErrorType} @param error: the error code @type error: L{NetworkError} or L{AuthenticationError} or L{ProtocolError} or L{ContactInviteError} or L{MessageError}""" pass
[ "def", "on_conversation_error", "(", "self", ",", "type", ",", "error", ")", ":", "pass" ]
https://github.com/emesene/emesene/blob/4548a4098310e21b16437bb36223a7f632a4f7bc/emesene/e3/papylib/papyon/papyon/event/conversation.py#L78-L88
cloudera/hue
23f02102d4547c17c32bd5ea0eb24e9eadd657a4
desktop/core/ext-py/zope.interface-4.5.0/src/zope/interface/interfaces.py
python
IComponentRegistry.registerSubscriptionAdapter
(factory, required=None, provides=None, name=_BLANK, info='')
Register a subscriber factory Parameters: factory The object used to compute the adapter required This is a sequence of specifications for objects to be adapted. If omitted, then the value of the factory's __component_adapts__ attribute will be used. The __component_adapts__ attribute is usually attribute is normally set in class definitions using adapts function, or for callables using the adapter decorator. If the factory doesn't have a __component_adapts__ adapts attribute, then this argument is required. provided This is the interface provided by the adapter and implemented by the factory. If the factory implements a single interface, then this argument is optional and the factory-implemented interface will be used. name The adapter name. Currently, only the empty string is accepted. Other strings will be accepted in the future when support for named subscribers is added. info An object that can be converted to a string to provide information about the registration. A Registered event is generated with an ISubscriptionAdapterRegistration.
Register a subscriber factory
[ "Register", "a", "subscriber", "factory" ]
def registerSubscriptionAdapter(factory, required=None, provides=None, name=_BLANK, info=''): """Register a subscriber factory Parameters: factory The object used to compute the adapter required This is a sequence of specifications for objects to be adapted. If omitted, then the value of the factory's __component_adapts__ attribute will be used. The __component_adapts__ attribute is usually attribute is normally set in class definitions using adapts function, or for callables using the adapter decorator. If the factory doesn't have a __component_adapts__ adapts attribute, then this argument is required. provided This is the interface provided by the adapter and implemented by the factory. If the factory implements a single interface, then this argument is optional and the factory-implemented interface will be used. name The adapter name. Currently, only the empty string is accepted. Other strings will be accepted in the future when support for named subscribers is added. info An object that can be converted to a string to provide information about the registration. A Registered event is generated with an ISubscriptionAdapterRegistration. """
[ "def", "registerSubscriptionAdapter", "(", "factory", ",", "required", "=", "None", ",", "provides", "=", "None", ",", "name", "=", "_BLANK", ",", "info", "=", "''", ")", ":" ]
https://github.com/cloudera/hue/blob/23f02102d4547c17c32bd5ea0eb24e9eadd657a4/desktop/core/ext-py/zope.interface-4.5.0/src/zope/interface/interfaces.py#L1108-L1147
bytefish/facerec
4071e1e79a50dbf1d1f2e061d24448576e5ac37d
py/facerec/validation.py
python
SimpleValidation.__init__
(self, model)
Args: model [PredictableModel] model to perform the validation on
Args: model [PredictableModel] model to perform the validation on
[ "Args", ":", "model", "[", "PredictableModel", "]", "model", "to", "perform", "the", "validation", "on" ]
def __init__(self, model): """ Args: model [PredictableModel] model to perform the validation on """ super(SimpleValidation, self).__init__(model=model) self.logger = logging.getLogger("facerec.validation.SimpleValidation")
[ "def", "__init__", "(", "self", ",", "model", ")", ":", "super", "(", "SimpleValidation", ",", "self", ")", ".", "__init__", "(", "model", "=", "model", ")", "self", ".", "logger", "=", "logging", ".", "getLogger", "(", "\"facerec.validation.SimpleValidation...
https://github.com/bytefish/facerec/blob/4071e1e79a50dbf1d1f2e061d24448576e5ac37d/py/facerec/validation.py#L342-L348
iiau-tracker/SPLT
a196e603798e9be969d9d985c087c11cad1cda43
lib/object_detection/models/faster_rcnn_resnet_v1_feature_extractor.py
python
FasterRCNNResnetV1FeatureExtractor._extract_box_classifier_features
(self, proposal_feature_maps, scope)
return proposal_classifier_features
Extracts second stage box classifier features. Args: proposal_feature_maps: A 4-D float tensor with shape [batch_size * self.max_num_proposals, crop_height, crop_width, depth] representing the feature map cropped to each proposal. scope: A scope name (unused). Returns: proposal_classifier_features: A 4-D float tensor with shape [batch_size * self.max_num_proposals, height, width, depth] representing box classifier features for each proposal.
Extracts second stage box classifier features.
[ "Extracts", "second", "stage", "box", "classifier", "features", "." ]
def _extract_box_classifier_features(self, proposal_feature_maps, scope): """Extracts second stage box classifier features. Args: proposal_feature_maps: A 4-D float tensor with shape [batch_size * self.max_num_proposals, crop_height, crop_width, depth] representing the feature map cropped to each proposal. scope: A scope name (unused). Returns: proposal_classifier_features: A 4-D float tensor with shape [batch_size * self.max_num_proposals, height, width, depth] representing box classifier features for each proposal. """ with tf.variable_scope(self._architecture, reuse=self._reuse_weights): with slim.arg_scope( resnet_utils.resnet_arg_scope( batch_norm_epsilon=1e-5, batch_norm_scale=True, weight_decay=self._weight_decay)): with slim.arg_scope([slim.batch_norm], is_training=False): blocks = [ resnet_utils.Block('block4', resnet_v1.bottleneck, [{ 'depth': 2048, 'depth_bottleneck': 512, 'stride': 1 }] * 3) ] proposal_classifier_features = resnet_utils.stack_blocks_dense( proposal_feature_maps, blocks) return proposal_classifier_features
[ "def", "_extract_box_classifier_features", "(", "self", ",", "proposal_feature_maps", ",", "scope", ")", ":", "with", "tf", ".", "variable_scope", "(", "self", ".", "_architecture", ",", "reuse", "=", "self", ".", "_reuse_weights", ")", ":", "with", "slim", "....
https://github.com/iiau-tracker/SPLT/blob/a196e603798e9be969d9d985c087c11cad1cda43/lib/object_detection/models/faster_rcnn_resnet_v1_feature_extractor.py#L131-L161
rowliny/DiffHelper
ab3a96f58f9579d0023aed9ebd785f4edf26f8af
Tool/SitePackages/nltk/sem/hole.py
python
HoleSemantics._find_top_most_labels
(self)
return self._find_top_nodes(self.labels)
Return the set of labels which are not referenced directly as part of another formula fragment. These will be the top-most labels for the subtree that they are part of.
Return the set of labels which are not referenced directly as part of another formula fragment. These will be the top-most labels for the subtree that they are part of.
[ "Return", "the", "set", "of", "labels", "which", "are", "not", "referenced", "directly", "as", "part", "of", "another", "formula", "fragment", ".", "These", "will", "be", "the", "top", "-", "most", "labels", "for", "the", "subtree", "that", "they", "are", ...
def _find_top_most_labels(self): """ Return the set of labels which are not referenced directly as part of another formula fragment. These will be the top-most labels for the subtree that they are part of. """ return self._find_top_nodes(self.labels)
[ "def", "_find_top_most_labels", "(", "self", ")", ":", "return", "self", ".", "_find_top_nodes", "(", "self", ".", "labels", ")" ]
https://github.com/rowliny/DiffHelper/blob/ab3a96f58f9579d0023aed9ebd785f4edf26f8af/Tool/SitePackages/nltk/sem/hole.py#L148-L154
khalim19/gimp-plugin-export-layers
b37255f2957ad322f4d332689052351cdea6e563
export_layers/gui/placeholders.py
python
GimpObjectPlaceholdersComboBoxPresenter._set_value
(self, value)
[]
def _set_value(self, value): self._element.set_active(self._setting.get_allowed_placeholder_names().index(value))
[ "def", "_set_value", "(", "self", ",", "value", ")", ":", "self", ".", "_element", ".", "set_active", "(", "self", ".", "_setting", ".", "get_allowed_placeholder_names", "(", ")", ".", "index", "(", "value", ")", ")" ]
https://github.com/khalim19/gimp-plugin-export-layers/blob/b37255f2957ad322f4d332689052351cdea6e563/export_layers/gui/placeholders.py#L55-L56
zachwill/flask-engine
7c8ad4bfe36382a8c9286d873ec7b785715832a4
libs/jinja2/compiler.py
python
CodeGenerator.macro_body
(self, node, frame, children=None)
return frame
Dump the function def of a macro or call block.
Dump the function def of a macro or call block.
[ "Dump", "the", "function", "def", "of", "a", "macro", "or", "call", "block", "." ]
def macro_body(self, node, frame, children=None): """Dump the function def of a macro or call block.""" frame = self.function_scoping(node, frame, children) # macros are delayed, they never require output checks frame.require_output_check = False args = frame.arguments # XXX: this is an ugly fix for the loop nesting bug # (tests.test_old_bugs.test_loop_call_bug). This works around # a identifier nesting problem we have in general. It's just more # likely to happen in loops which is why we work around it. The # real solution would be "nonlocal" all the identifiers that are # leaking into a new python frame and might be used both unassigned # and assigned. if 'loop' in frame.identifiers.declared: args = args + ['l_loop=l_loop'] self.writeline('def macro(%s):' % ', '.join(args), node) self.indent() self.buffer(frame) self.pull_locals(frame) self.blockvisit(node.body, frame) self.return_buffer_contents(frame) self.outdent() return frame
[ "def", "macro_body", "(", "self", ",", "node", ",", "frame", ",", "children", "=", "None", ")", ":", "frame", "=", "self", ".", "function_scoping", "(", "node", ",", "frame", ",", "children", ")", "# macros are delayed, they never require output checks", "frame"...
https://github.com/zachwill/flask-engine/blob/7c8ad4bfe36382a8c9286d873ec7b785715832a4/libs/jinja2/compiler.py#L712-L734
pyparallel/pyparallel
11e8c6072d48c8f13641925d17b147bf36ee0ba3
Lib/lib2to3/pgen2/tokenize.py
python
generate_tokens
(readline)
The generate_tokens() generator requires one argument, readline, which must be a callable object which provides the same interface as the readline() method of built-in file objects. Each call to the function should return one line of input as a string. Alternately, readline can be a callable function terminating with StopIteration: readline = open(myfile).next # Example of alternate readline The generator produces 5-tuples with these members: the token type; the token string; a 2-tuple (srow, scol) of ints specifying the row and column where the token begins in the source; a 2-tuple (erow, ecol) of ints specifying the row and column where the token ends in the source; and the line on which the token was found. The line passed is the logical line; continuation lines are included.
The generate_tokens() generator requires one argument, readline, which must be a callable object which provides the same interface as the readline() method of built-in file objects. Each call to the function should return one line of input as a string. Alternately, readline can be a callable function terminating with StopIteration: readline = open(myfile).next # Example of alternate readline
[ "The", "generate_tokens", "()", "generator", "requires", "one", "argument", "readline", "which", "must", "be", "a", "callable", "object", "which", "provides", "the", "same", "interface", "as", "the", "readline", "()", "method", "of", "built", "-", "in", "file"...
def generate_tokens(readline): """ The generate_tokens() generator requires one argument, readline, which must be a callable object which provides the same interface as the readline() method of built-in file objects. Each call to the function should return one line of input as a string. Alternately, readline can be a callable function terminating with StopIteration: readline = open(myfile).next # Example of alternate readline The generator produces 5-tuples with these members: the token type; the token string; a 2-tuple (srow, scol) of ints specifying the row and column where the token begins in the source; a 2-tuple (erow, ecol) of ints specifying the row and column where the token ends in the source; and the line on which the token was found. The line passed is the logical line; continuation lines are included. """ lnum = parenlev = continued = 0 namechars, numchars = string.ascii_letters + '_', '0123456789' contstr, needcont = '', 0 contline = None indents = [0] while 1: # loop over lines in stream try: line = readline() except StopIteration: line = '' lnum = lnum + 1 pos, max = 0, len(line) if contstr: # continued string if not line: raise TokenError("EOF in multi-line string", strstart) endmatch = endprog.match(line) if endmatch: pos = end = endmatch.end(0) yield (STRING, contstr + line[:end], strstart, (lnum, end), contline + line) contstr, needcont = '', 0 contline = None elif needcont and line[-2:] != '\\\n' and line[-3:] != '\\\r\n': yield (ERRORTOKEN, contstr + line, strstart, (lnum, len(line)), contline) contstr = '' contline = None continue else: contstr = contstr + line contline = contline + line continue elif parenlev == 0 and not continued: # new statement if not line: break column = 0 while pos < max: # measure leading whitespace if line[pos] == ' ': column = column + 1 elif line[pos] == '\t': column = (column//tabsize + 1)*tabsize elif line[pos] == '\f': column = 0 else: break pos = pos + 1 if pos == max: break if line[pos] in '#\r\n': # skip comments or blank lines if line[pos] == '#': comment_token = line[pos:].rstrip('\r\n') nl_pos = pos + len(comment_token) yield (COMMENT, comment_token, (lnum, pos), (lnum, pos + len(comment_token)), line) yield (NL, line[nl_pos:], (lnum, nl_pos), (lnum, len(line)), line) else: yield ((NL, COMMENT)[line[pos] == '#'], line[pos:], (lnum, pos), (lnum, len(line)), line) continue if column > indents[-1]: # count indents or dedents indents.append(column) yield (INDENT, line[:pos], (lnum, 0), (lnum, pos), line) while column < indents[-1]: if column not in indents: raise IndentationError( "unindent does not match any outer indentation level", ("<tokenize>", lnum, pos, line)) indents = indents[:-1] yield (DEDENT, '', (lnum, pos), (lnum, pos), line) else: # continued statement if not line: raise TokenError("EOF in multi-line statement", (lnum, 0)) continued = 0 while pos < max: pseudomatch = pseudoprog.match(line, pos) if pseudomatch: # scan for tokens start, end = pseudomatch.span(1) spos, epos, pos = (lnum, start), (lnum, end), end token, initial = line[start:end], line[start] if initial in numchars or \ (initial == '.' and token != '.'): # ordinary number yield (NUMBER, token, spos, epos, line) elif initial in '\r\n': newline = NEWLINE if parenlev > 0: newline = NL yield (newline, token, spos, epos, line) elif initial == '#': assert not token.endswith("\n") yield (COMMENT, token, spos, epos, line) elif token in triple_quoted: endprog = endprogs[token] endmatch = endprog.match(line, pos) if endmatch: # all on one line pos = endmatch.end(0) token = line[start:pos] yield (STRING, token, spos, (lnum, pos), line) else: strstart = (lnum, start) # multiple lines contstr = line[start:] contline = line break elif initial in single_quoted or \ token[:2] in single_quoted or \ token[:3] in single_quoted: if token[-1] == '\n': # continued string strstart = (lnum, start) endprog = (endprogs[initial] or endprogs[token[1]] or endprogs[token[2]]) contstr, needcont = line[start:], 1 contline = line break else: # ordinary string yield (STRING, token, spos, epos, line) elif initial in namechars: # ordinary name yield (NAME, token, spos, epos, line) elif initial == '\\': # continued stmt # This yield is new; needed for better idempotency: yield (NL, token, spos, (lnum, pos), line) continued = 1 else: if initial in '([{': parenlev = parenlev + 1 elif initial in ')]}': parenlev = parenlev - 1 yield (OP, token, spos, epos, line) else: yield (ERRORTOKEN, line[pos], (lnum, pos), (lnum, pos+1), line) pos = pos + 1 for indent in indents[1:]: # pop remaining indent levels yield (DEDENT, '', (lnum, 0), (lnum, 0), '') yield (ENDMARKER, '', (lnum, 0), (lnum, 0), '')
[ "def", "generate_tokens", "(", "readline", ")", ":", "lnum", "=", "parenlev", "=", "continued", "=", "0", "namechars", ",", "numchars", "=", "string", ".", "ascii_letters", "+", "'_'", ",", "'0123456789'", "contstr", ",", "needcont", "=", "''", ",", "0", ...
https://github.com/pyparallel/pyparallel/blob/11e8c6072d48c8f13641925d17b147bf36ee0ba3/Lib/lib2to3/pgen2/tokenize.py#L347-L497
rwightman/efficientdet-pytorch
9cb43186711d28bd41f82f132818c65663b33c1f
effdet/evaluation/detection_evaluator.py
python
DetectionEvaluator.clear
(self)
Clears the state to prepare for a fresh evaluation.
Clears the state to prepare for a fresh evaluation.
[ "Clears", "the", "state", "to", "prepare", "for", "a", "fresh", "evaluation", "." ]
def clear(self): """Clears the state to prepare for a fresh evaluation.""" pass
[ "def", "clear", "(", "self", ")", ":", "pass" ]
https://github.com/rwightman/efficientdet-pytorch/blob/9cb43186711d28bd41f82f132818c65663b33c1f/effdet/evaluation/detection_evaluator.py#L91-L93
pandas-dev/pandas
5ba7d714014ae8feaccc0dd4a98890828cf2832d
pandas/io/html.py
python
_HtmlFrameParser._expand_colspan_rowspan
(self, rows)
return all_texts
Given a list of <tr>s, return a list of text rows. Parameters ---------- rows : list of node-like List of <tr>s Returns ------- list of list Each returned row is a list of str text. Notes ----- Any cell with ``rowspan`` or ``colspan`` will have its contents copied to subsequent cells.
Given a list of <tr>s, return a list of text rows.
[ "Given", "a", "list", "of", "<tr", ">", "s", "return", "a", "list", "of", "text", "rows", "." ]
def _expand_colspan_rowspan(self, rows): """ Given a list of <tr>s, return a list of text rows. Parameters ---------- rows : list of node-like List of <tr>s Returns ------- list of list Each returned row is a list of str text. Notes ----- Any cell with ``rowspan`` or ``colspan`` will have its contents copied to subsequent cells. """ all_texts = [] # list of rows, each a list of str remainder: list[tuple[int, str, int]] = [] # list of (index, text, nrows) for tr in rows: texts = [] # the output for this row next_remainder = [] index = 0 tds = self._parse_td(tr) for td in tds: # Append texts from previous rows with rowspan>1 that come # before this <td> while remainder and remainder[0][0] <= index: prev_i, prev_text, prev_rowspan = remainder.pop(0) texts.append(prev_text) if prev_rowspan > 1: next_remainder.append((prev_i, prev_text, prev_rowspan - 1)) index += 1 # Append the text from this <td>, colspan times text = _remove_whitespace(self._text_getter(td)) rowspan = int(self._attr_getter(td, "rowspan") or 1) colspan = int(self._attr_getter(td, "colspan") or 1) for _ in range(colspan): texts.append(text) if rowspan > 1: next_remainder.append((index, text, rowspan - 1)) index += 1 # Append texts from previous rows at the final position for prev_i, prev_text, prev_rowspan in remainder: texts.append(prev_text) if prev_rowspan > 1: next_remainder.append((prev_i, prev_text, prev_rowspan - 1)) all_texts.append(texts) remainder = next_remainder # Append rows that only appear because the previous row had non-1 # rowspan while remainder: next_remainder = [] texts = [] for prev_i, prev_text, prev_rowspan in remainder: texts.append(prev_text) if prev_rowspan > 1: next_remainder.append((prev_i, prev_text, prev_rowspan - 1)) all_texts.append(texts) remainder = next_remainder return all_texts
[ "def", "_expand_colspan_rowspan", "(", "self", ",", "rows", ")", ":", "all_texts", "=", "[", "]", "# list of rows, each a list of str", "remainder", ":", "list", "[", "tuple", "[", "int", ",", "str", ",", "int", "]", "]", "=", "[", "]", "# list of (index, te...
https://github.com/pandas-dev/pandas/blob/5ba7d714014ae8feaccc0dd4a98890828cf2832d/pandas/io/html.py#L444-L514
triaquae/triaquae
bbabf736b3ba56a0c6498e7f04e16c13b8b8f2b9
TriAquae/models/django/db/models/sql/datastructures.py
python
Date.__init__
(self, col, lookup_type)
[]
def __init__(self, col, lookup_type): self.col = col self.lookup_type = lookup_type
[ "def", "__init__", "(", "self", ",", "col", ",", "lookup_type", ")", ":", "self", ".", "col", "=", "col", "self", ".", "lookup_type", "=", "lookup_type" ]
https://github.com/triaquae/triaquae/blob/bbabf736b3ba56a0c6498e7f04e16c13b8b8f2b9/TriAquae/models/django/db/models/sql/datastructures.py#L29-L31
rwth-i6/returnn
f2d718a197a280b0d5f0fd91a7fcb8658560dddb
returnn/datasets/map.py
python
MapDatasetWrapper._collect_single_seq
(self, seq_idx)
return DatasetSeq( seq_idx, features=self._dataset[corpus_seq_idx], seq_tag=self._dataset.get_seq_tag(corpus_seq_idx))
:param int seq_idx: sorted seq idx :return:
:param int seq_idx: sorted seq idx :return:
[ ":", "param", "int", "seq_idx", ":", "sorted", "seq", "idx", ":", "return", ":" ]
def _collect_single_seq(self, seq_idx): """ :param int seq_idx: sorted seq idx :return: """ corpus_seq_idx = self.get_corpus_seq_idx(seq_idx) return DatasetSeq( seq_idx, features=self._dataset[corpus_seq_idx], seq_tag=self._dataset.get_seq_tag(corpus_seq_idx))
[ "def", "_collect_single_seq", "(", "self", ",", "seq_idx", ")", ":", "corpus_seq_idx", "=", "self", ".", "get_corpus_seq_idx", "(", "seq_idx", ")", "return", "DatasetSeq", "(", "seq_idx", ",", "features", "=", "self", ".", "_dataset", "[", "corpus_seq_idx", "]...
https://github.com/rwth-i6/returnn/blob/f2d718a197a280b0d5f0fd91a7fcb8658560dddb/returnn/datasets/map.py#L122-L129
truenas/middleware
b11ec47d6340324f5a32287ffb4012e5d709b934
src/middlewared/middlewared/plugins/chart_releases_linux/upgrade.py
python
ChartReleaseService.upgrade
(self, job, release_name, options)
return chart_release
Upgrade `release_name` chart release. `upgrade_options.item_version` specifies to which item version chart release should be upgraded to. System will update container images being used by `release_name` chart release as a chart release upgrade is not considered complete until the images in use have also been updated to latest versions. During upgrade, `upgrade_options.values` can be specified to apply configuration changes for configuration changes for the chart release in question. When chart version is upgraded, system will automatically take a snapshot of `ix_volumes` in question which can be used to rollback later on.
Upgrade `release_name` chart release.
[ "Upgrade", "release_name", "chart", "release", "." ]
async def upgrade(self, job, release_name, options): """ Upgrade `release_name` chart release. `upgrade_options.item_version` specifies to which item version chart release should be upgraded to. System will update container images being used by `release_name` chart release as a chart release upgrade is not considered complete until the images in use have also been updated to latest versions. During upgrade, `upgrade_options.values` can be specified to apply configuration changes for configuration changes for the chart release in question. When chart version is upgraded, system will automatically take a snapshot of `ix_volumes` in question which can be used to rollback later on. """ await self.middleware.call('kubernetes.validate_k8s_setup') release = await self.middleware.call('chart.release.get_instance', release_name) if not release['update_available'] and not release['container_images_update_available']: raise CallError('No update is available for chart release') # We need to update container images before upgrading chart version as it's possible that the chart version # in question needs newer image hashes. job.set_progress(10, 'Updating container images') await ( await self.middleware.call('chart.release.pull_container_images', release_name, {'redeploy': False}) ).wait(raise_error=True) job.set_progress(30, 'Updated container images') await self.scale_down_workloads_before_snapshot(job, release) # If a snapshot of the volumes already exist with the same name in case of a failed upgrade, we will remove # it as we want the current point in time being reflected in the snapshot # TODO: Remove volumes/ix_volumes check in next release as we are going to do a recursive snapshot # from parent volumes ds moving on for filesystem in ('volumes', 'volumes/ix_volumes'): volumes_ds = os.path.join(release['dataset'], filesystem) snap_name = f'{volumes_ds}@{release["version"]}' if await self.middleware.call('zfs.snapshot.query', [['id', '=', snap_name]]): await self.middleware.call('zfs.snapshot.delete', snap_name, {'recursive': True}) await self.middleware.call( 'zfs.snapshot.create', { 'dataset': os.path.join(release['dataset'], 'volumes'), 'name': release['version'], 'recursive': True } ) job.set_progress(50, 'Created snapshot for upgrade') if release['update_available']: await self.upgrade_chart_release(job, release, options) else: await (await self.middleware.call('chart.release.redeploy', release_name)).wait(raise_error=True) chart_release = await self.middleware.call('chart.release.get_instance', release_name) self.middleware.send_event('chart.release.query', 'CHANGED', id=release_name, fields=chart_release) await self.chart_releases_update_checks_internal([['id', '=', release_name]]) job.set_progress(100, 'Upgrade complete for chart release') return chart_release
[ "async", "def", "upgrade", "(", "self", ",", "job", ",", "release_name", ",", "options", ")", ":", "await", "self", ".", "middleware", ".", "call", "(", "'kubernetes.validate_k8s_setup'", ")", "release", "=", "await", "self", ".", "middleware", ".", "call", ...
https://github.com/truenas/middleware/blob/b11ec47d6340324f5a32287ffb4012e5d709b934/src/middlewared/middlewared/plugins/chart_releases_linux/upgrade.py#L68-L127
quantopian/zipline
014f1fc339dc8b7671d29be2d85ce57d3daec343
zipline/data/adjustments.py
python
SQLiteAdjustmentWriter.write
(self, splits=None, mergers=None, dividends=None, stock_dividends=None)
Writes data to a SQLite file to be read by SQLiteAdjustmentReader. Parameters ---------- splits : pandas.DataFrame, optional Dataframe containing split data. The format of this dataframe is: effective_date : int The date, represented as seconds since Unix epoch, on which the adjustment should be applied. ratio : float A value to apply to all data earlier than the effective date. For open, high, low, and close those values are multiplied by the ratio. Volume is divided by this value. sid : int The asset id associated with this adjustment. mergers : pandas.DataFrame, optional DataFrame containing merger data. The format of this dataframe is: effective_date : int The date, represented as seconds since Unix epoch, on which the adjustment should be applied. ratio : float A value to apply to all data earlier than the effective date. For open, high, low, and close those values are multiplied by the ratio. Volume is unaffected. sid : int The asset id associated with this adjustment. dividends : pandas.DataFrame, optional DataFrame containing dividend data. The format of the dataframe is: sid : int The asset id associated with this adjustment. ex_date : datetime64 The date on which an equity must be held to be eligible to receive payment. declared_date : datetime64 The date on which the dividend is announced to the public. pay_date : datetime64 The date on which the dividend is distributed. record_date : datetime64 The date on which the stock ownership is checked to determine distribution of dividends. amount : float The cash amount paid for each share. Dividend ratios are calculated as: ``1.0 - (dividend_value / "close on day prior to ex_date")`` stock_dividends : pandas.DataFrame, optional DataFrame containing stock dividend data. The format of the dataframe is: sid : int The asset id associated with this adjustment. ex_date : datetime64 The date on which an equity must be held to be eligible to receive payment. declared_date : datetime64 The date on which the dividend is announced to the public. pay_date : datetime64 The date on which the dividend is distributed. record_date : datetime64 The date on which the stock ownership is checked to determine distribution of dividends. payment_sid : int The asset id of the shares that should be paid instead of cash. ratio : float The ratio of currently held shares in the held sid that should be paid with new shares of the payment_sid. See Also -------- zipline.data.adjustments.SQLiteAdjustmentReader
Writes data to a SQLite file to be read by SQLiteAdjustmentReader.
[ "Writes", "data", "to", "a", "SQLite", "file", "to", "be", "read", "by", "SQLiteAdjustmentReader", "." ]
def write(self, splits=None, mergers=None, dividends=None, stock_dividends=None): """ Writes data to a SQLite file to be read by SQLiteAdjustmentReader. Parameters ---------- splits : pandas.DataFrame, optional Dataframe containing split data. The format of this dataframe is: effective_date : int The date, represented as seconds since Unix epoch, on which the adjustment should be applied. ratio : float A value to apply to all data earlier than the effective date. For open, high, low, and close those values are multiplied by the ratio. Volume is divided by this value. sid : int The asset id associated with this adjustment. mergers : pandas.DataFrame, optional DataFrame containing merger data. The format of this dataframe is: effective_date : int The date, represented as seconds since Unix epoch, on which the adjustment should be applied. ratio : float A value to apply to all data earlier than the effective date. For open, high, low, and close those values are multiplied by the ratio. Volume is unaffected. sid : int The asset id associated with this adjustment. dividends : pandas.DataFrame, optional DataFrame containing dividend data. The format of the dataframe is: sid : int The asset id associated with this adjustment. ex_date : datetime64 The date on which an equity must be held to be eligible to receive payment. declared_date : datetime64 The date on which the dividend is announced to the public. pay_date : datetime64 The date on which the dividend is distributed. record_date : datetime64 The date on which the stock ownership is checked to determine distribution of dividends. amount : float The cash amount paid for each share. Dividend ratios are calculated as: ``1.0 - (dividend_value / "close on day prior to ex_date")`` stock_dividends : pandas.DataFrame, optional DataFrame containing stock dividend data. The format of the dataframe is: sid : int The asset id associated with this adjustment. ex_date : datetime64 The date on which an equity must be held to be eligible to receive payment. declared_date : datetime64 The date on which the dividend is announced to the public. pay_date : datetime64 The date on which the dividend is distributed. record_date : datetime64 The date on which the stock ownership is checked to determine distribution of dividends. payment_sid : int The asset id of the shares that should be paid instead of cash. ratio : float The ratio of currently held shares in the held sid that should be paid with new shares of the payment_sid. See Also -------- zipline.data.adjustments.SQLiteAdjustmentReader """ self.write_frame('splits', splits) self.write_frame('mergers', mergers) self.write_dividend_data(dividends, stock_dividends) # Use IF NOT EXISTS here to allow multiple writes if desired. self.conn.execute( "CREATE INDEX IF NOT EXISTS splits_sids " "ON splits(sid)" ) self.conn.execute( "CREATE INDEX IF NOT EXISTS splits_effective_date " "ON splits(effective_date)" ) self.conn.execute( "CREATE INDEX IF NOT EXISTS mergers_sids " "ON mergers(sid)" ) self.conn.execute( "CREATE INDEX IF NOT EXISTS mergers_effective_date " "ON mergers(effective_date)" ) self.conn.execute( "CREATE INDEX IF NOT EXISTS dividends_sid " "ON dividends(sid)" ) self.conn.execute( "CREATE INDEX IF NOT EXISTS dividends_effective_date " "ON dividends(effective_date)" ) self.conn.execute( "CREATE INDEX IF NOT EXISTS dividend_payouts_sid " "ON dividend_payouts(sid)" ) self.conn.execute( "CREATE INDEX IF NOT EXISTS dividends_payouts_ex_date " "ON dividend_payouts(ex_date)" ) self.conn.execute( "CREATE INDEX IF NOT EXISTS stock_dividend_payouts_sid " "ON stock_dividend_payouts(sid)" ) self.conn.execute( "CREATE INDEX IF NOT EXISTS stock_dividends_payouts_ex_date " "ON stock_dividend_payouts(ex_date)" )
[ "def", "write", "(", "self", ",", "splits", "=", "None", ",", "mergers", "=", "None", ",", "dividends", "=", "None", ",", "stock_dividends", "=", "None", ")", ":", "self", ".", "write_frame", "(", "'splits'", ",", "splits", ")", "self", ".", "write_fra...
https://github.com/quantopian/zipline/blob/014f1fc339dc8b7671d29be2d85ce57d3daec343/zipline/data/adjustments.py#L583-L703
compas-dev/compas
0b33f8786481f710115fb1ae5fe79abc2a9a5175
src/compas/files/stl.py
python
STL.write
(self, mesh, **kwargs)
Write a mesh to the file. Parameters ---------- mesh : :class:`compas.datastructures.Mesh` The mesh. binary : bool, optional Flag indicating that the file should be written in binary format. solid_name : str, optional The name of the solid. Defaults to the name of the mesh. precision : str, optional COMPAS precision specification for parsing geometric data. Returns ------- None
Write a mesh to the file.
[ "Write", "a", "mesh", "to", "the", "file", "." ]
def write(self, mesh, **kwargs): """Write a mesh to the file. Parameters ---------- mesh : :class:`compas.datastructures.Mesh` The mesh. binary : bool, optional Flag indicating that the file should be written in binary format. solid_name : str, optional The name of the solid. Defaults to the name of the mesh. precision : str, optional COMPAS precision specification for parsing geometric data. Returns ------- None """ self._writer = STLWriter(self.filepath, mesh, **kwargs) self._writer.write()
[ "def", "write", "(", "self", ",", "mesh", ",", "*", "*", "kwargs", ")", ":", "self", ".", "_writer", "=", "STLWriter", "(", "self", ".", "filepath", ",", "mesh", ",", "*", "*", "kwargs", ")", "self", ".", "_writer", ".", "write", "(", ")" ]
https://github.com/compas-dev/compas/blob/0b33f8786481f710115fb1ae5fe79abc2a9a5175/src/compas/files/stl.py#L63-L84
PaddlePaddle/PaddleHub
107ee7e1a49d15e9c94da3956475d88a53fc165f
modules/image/object_detection/yolov3_mobilenet_v1_coco2017/yolo_head.py
python
YOLOv3Head.get_prediction
(self, outputs, im_size)
return pred
Get prediction result of YOLOv3 network Args: outputs (list): list of Variables, return from _get_outputs im_size (Variable): Variable of size([h, w]) of each image Returns: pred (Variable): The prediction result after non-max suppress.
Get prediction result of YOLOv3 network
[ "Get", "prediction", "result", "of", "YOLOv3", "network" ]
def get_prediction(self, outputs, im_size): """ Get prediction result of YOLOv3 network Args: outputs (list): list of Variables, return from _get_outputs im_size (Variable): Variable of size([h, w]) of each image Returns: pred (Variable): The prediction result after non-max suppress. """ boxes = [] scores = [] downsample = 32 for i, output in enumerate(outputs): box, score = fluid.layers.yolo_box( x=output, img_size=im_size, anchors=self.mask_anchors[i], class_num=self.num_classes, conf_thresh=self.nms.score_threshold, downsample_ratio=downsample, name=self.prefix_name + "yolo_box" + str(i)) boxes.append(box) scores.append(fluid.layers.transpose(score, perm=[0, 2, 1])) downsample //= 2 yolo_boxes = fluid.layers.concat(boxes, axis=1) yolo_scores = fluid.layers.concat(scores, axis=2) pred = fluid.layers.multiclass_nms( bboxes=yolo_boxes, scores=yolo_scores, score_threshold=self.nms.score_threshold, nms_top_k=self.nms.nms_top_k, keep_top_k=self.nms.keep_top_k, nms_threshold=self.nms.nms_threshold, background_label=self.nms.background_label, normalized=self.nms.normalized, name="multiclass_nms") return pred
[ "def", "get_prediction", "(", "self", ",", "outputs", ",", "im_size", ")", ":", "boxes", "=", "[", "]", "scores", "=", "[", "]", "downsample", "=", "32", "for", "i", ",", "output", "in", "enumerate", "(", "outputs", ")", ":", "box", ",", "score", "...
https://github.com/PaddlePaddle/PaddleHub/blob/107ee7e1a49d15e9c94da3956475d88a53fc165f/modules/image/object_detection/yolov3_mobilenet_v1_coco2017/yolo_head.py#L232-L273
AppScale/gts
46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9
AppServer/lib/django-1.5/django/core/files/storage.py
python
Storage.created_time
(self, name)
Returns the creation time (as datetime object) of the file specified by name.
Returns the creation time (as datetime object) of the file specified by name.
[ "Returns", "the", "creation", "time", "(", "as", "datetime", "object", ")", "of", "the", "file", "specified", "by", "name", "." ]
def created_time(self, name): """ Returns the creation time (as datetime object) of the file specified by name. """ raise NotImplementedError()
[ "def", "created_time", "(", "self", ",", "name", ")", ":", "raise", "NotImplementedError", "(", ")" ]
https://github.com/AppScale/gts/blob/46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9/AppServer/lib/django-1.5/django/core/files/storage.py#L130-L135
OUCMachineLearning/OUCML
5b54337d7c0316084cb1a74befda2bba96137d4a
AutoML/darts-master/cnn/utils.py
python
load
(model, model_path)
[]
def load(model, model_path): model.load_state_dict(torch.load(model_path))
[ "def", "load", "(", "model", ",", "model_path", ")", ":", "model", ".", "load_state_dict", "(", "torch", ".", "load", "(", "model_path", ")", ")" ]
https://github.com/OUCMachineLearning/OUCML/blob/5b54337d7c0316084cb1a74befda2bba96137d4a/AutoML/darts-master/cnn/utils.py#L98-L99
IronLanguages/ironpython3
7a7bb2a872eeab0d1009fc8a6e24dca43f65b693
Src/StdLib/Lib/tarfile.py
python
TarFile.close
(self)
Close the TarFile. In write-mode, two finishing zero blocks are appended to the archive.
Close the TarFile. In write-mode, two finishing zero blocks are appended to the archive.
[ "Close", "the", "TarFile", ".", "In", "write", "-", "mode", "two", "finishing", "zero", "blocks", "are", "appended", "to", "the", "archive", "." ]
def close(self): """Close the TarFile. In write-mode, two finishing zero blocks are appended to the archive. """ if self.closed: return self.closed = True try: if self.mode in "aw": self.fileobj.write(NUL * (BLOCKSIZE * 2)) self.offset += (BLOCKSIZE * 2) # fill up the end with zero-blocks # (like option -b20 for tar does) blocks, remainder = divmod(self.offset, RECORDSIZE) if remainder > 0: self.fileobj.write(NUL * (RECORDSIZE - remainder)) finally: if not self._extfileobj: self.fileobj.close()
[ "def", "close", "(", "self", ")", ":", "if", "self", ".", "closed", ":", "return", "self", ".", "closed", "=", "True", "try", ":", "if", "self", ".", "mode", "in", "\"aw\"", ":", "self", ".", "fileobj", ".", "write", "(", "NUL", "*", "(", "BLOCKS...
https://github.com/IronLanguages/ironpython3/blob/7a7bb2a872eeab0d1009fc8a6e24dca43f65b693/Src/StdLib/Lib/tarfile.py#L1705-L1724
tcgoetz/GarminDB
55796eb621df9f6ecd92f16b3a53393d23c0b4dc
scripts/garmindb_cli.py
python
backup_dbs
()
Backup GarminDb database files.
Backup GarminDb database files.
[ "Backup", "GarminDb", "database", "files", "." ]
def backup_dbs(): """Backup GarminDb database files.""" dbs = glob.glob(ConfigManager.get_db_dir() + os.sep + '*.db') backupfile = ConfigManager.get_or_create_backup_dir() + os.sep + str(int(datetime.datetime.now().timestamp())) + '_dbs.zip' logger.info("Backiping up dbs %s to %s", dbs, backupfile) with zipfile.ZipFile(backupfile, 'w') as backupzip: for db in dbs: backupzip.write(db)
[ "def", "backup_dbs", "(", ")", ":", "dbs", "=", "glob", ".", "glob", "(", "ConfigManager", ".", "get_db_dir", "(", ")", "+", "os", ".", "sep", "+", "'*.db'", ")", "backupfile", "=", "ConfigManager", ".", "get_or_create_backup_dir", "(", ")", "+", "os", ...
https://github.com/tcgoetz/GarminDB/blob/55796eb621df9f6ecd92f16b3a53393d23c0b4dc/scripts/garmindb_cli.py#L237-L244
idanr1986/cuckoo-droid
1350274639473d3d2b0ac740cae133ca53ab7444
analyzer/android_on_linux/lib/api/androguard/dvm.py
python
SparseSwitch.add_note
(self, msg)
Add a note to this instruction :param msg: the message :type msg: objects (string)
Add a note to this instruction
[ "Add", "a", "note", "to", "this", "instruction" ]
def add_note(self, msg) : """ Add a note to this instruction :param msg: the message :type msg: objects (string) """ self.notes.append( msg )
[ "def", "add_note", "(", "self", ",", "msg", ")", ":", "self", ".", "notes", ".", "append", "(", "msg", ")" ]
https://github.com/idanr1986/cuckoo-droid/blob/1350274639473d3d2b0ac740cae133ca53ab7444/analyzer/android_on_linux/lib/api/androguard/dvm.py#L3951-L3958
rwth-i6/returnn
f2d718a197a280b0d5f0fd91a7fcb8658560dddb
returnn/theano/activation_functions.py
python
clipped01lu
(z)
return relu(z) - relu(z - numpy.float32(1))
0 for x <= 0 x for 0 <= x <= 1 1 for 1 <= x
0 for x <= 0 x for 0 <= x <= 1 1 for 1 <= x
[ "0", "for", "x", "<", "=", "0", "x", "for", "0", "<", "=", "x", "<", "=", "1", "1", "for", "1", "<", "=", "x" ]
def clipped01lu(z): """ 0 for x <= 0 x for 0 <= x <= 1 1 for 1 <= x """ # Not sure about the fastest implementation... return relu(z) - relu(z - numpy.float32(1))
[ "def", "clipped01lu", "(", "z", ")", ":", "# Not sure about the fastest implementation...", "return", "relu", "(", "z", ")", "-", "relu", "(", "z", "-", "numpy", ".", "float32", "(", "1", ")", ")" ]
https://github.com/rwth-i6/returnn/blob/f2d718a197a280b0d5f0fd91a7fcb8658560dddb/returnn/theano/activation_functions.py#L13-L20
braincorp/PVM
3de2683634f372d2ac5aaa8b19e8ff23420d94d1
PVM_tools/labeled_movie.py
python
LabeledMovieFrame.create_channel
(self, channel)
:param channel: Name of the channel to create :type channel: str Creates a new channel. A channel is a container which can take an image and other attributes. :Example: :: cap0 = cv2.VideoCapture(0) cap1 = cv2.VideoCapture(1) ret, img_left = cap0.read() ret, img_right = cap1.read() F = LabeledMovieFrame(internal_storage_method="jpg") F.create_channel("left_image") F.set_image(img_left, channel="left_image") F.create_channel("right_image") F.set_image(img_right, channel="right_image") F.set_default_channel("left_image") assert(np.allclose(F.get_image(), img_left))
:param channel: Name of the channel to create :type channel: str
[ ":", "param", "channel", ":", "Name", "of", "the", "channel", "to", "create", ":", "type", "channel", ":", "str" ]
def create_channel(self, channel): """ :param channel: Name of the channel to create :type channel: str Creates a new channel. A channel is a container which can take an image and other attributes. :Example: :: cap0 = cv2.VideoCapture(0) cap1 = cv2.VideoCapture(1) ret, img_left = cap0.read() ret, img_right = cap1.read() F = LabeledMovieFrame(internal_storage_method="jpg") F.create_channel("left_image") F.set_image(img_left, channel="left_image") F.create_channel("right_image") F.set_image(img_right, channel="right_image") F.set_default_channel("left_image") assert(np.allclose(F.get_image(), img_left)) """ self._channel[channel] = channel self._per_channel_storage_method[channel] = self._internal_storage_method
[ "def", "create_channel", "(", "self", ",", "channel", ")", ":", "self", ".", "_channel", "[", "channel", "]", "=", "channel", "self", ".", "_per_channel_storage_method", "[", "channel", "]", "=", "self", ".", "_internal_storage_method" ]
https://github.com/braincorp/PVM/blob/3de2683634f372d2ac5aaa8b19e8ff23420d94d1/PVM_tools/labeled_movie.py#L118-L142
keon/algorithms
23d4e85a506eaeaff315e855be12f8dbe47a7ec3
algorithms/matrix/crout_matrix_decomposition.py
python
crout_matrix_decomposition
(A)
return (L,U)
[]
def crout_matrix_decomposition(A): n = len(A) L = [[0.0] * n for i in range(n)] U = [[0.0] * n for i in range(n)] for j in range(n): U[j][j] = 1.0 for i in range(j, n): alpha = float(A[i][j]) for k in range(j): alpha -= L[i][k]*U[k][j] L[i][j] = float(alpha) for i in range(j+1, n): tempU = float(A[j][i]) for k in range(j): tempU -= float(L[j][k]*U[k][i]) if int(L[j][j]) == 0: L[j][j] = float(0.1**40) U[j][i] = float(tempU/L[j][j]) return (L,U)
[ "def", "crout_matrix_decomposition", "(", "A", ")", ":", "n", "=", "len", "(", "A", ")", "L", "=", "[", "[", "0.0", "]", "*", "n", "for", "i", "in", "range", "(", "n", ")", "]", "U", "=", "[", "[", "0.0", "]", "*", "n", "for", "i", "in", ...
https://github.com/keon/algorithms/blob/23d4e85a506eaeaff315e855be12f8dbe47a7ec3/algorithms/matrix/crout_matrix_decomposition.py#L29-L47
TencentCloud/tencentcloud-sdk-python
3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2
tencentcloud/cpdp/v20190820/cpdp_client.py
python
CpdpClient.CreateAgentTaxPaymentInfos
(self, request)
直播平台-代理商完税信息录入 :param request: Request instance for CreateAgentTaxPaymentInfos. :type request: :class:`tencentcloud.cpdp.v20190820.models.CreateAgentTaxPaymentInfosRequest` :rtype: :class:`tencentcloud.cpdp.v20190820.models.CreateAgentTaxPaymentInfosResponse`
直播平台-代理商完税信息录入
[ "直播平台", "-", "代理商完税信息录入" ]
def CreateAgentTaxPaymentInfos(self, request): """直播平台-代理商完税信息录入 :param request: Request instance for CreateAgentTaxPaymentInfos. :type request: :class:`tencentcloud.cpdp.v20190820.models.CreateAgentTaxPaymentInfosRequest` :rtype: :class:`tencentcloud.cpdp.v20190820.models.CreateAgentTaxPaymentInfosResponse` """ try: params = request._serialize() body = self.call("CreateAgentTaxPaymentInfos", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.CreateAgentTaxPaymentInfosResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message)
[ "def", "CreateAgentTaxPaymentInfos", "(", "self", ",", "request", ")", ":", "try", ":", "params", "=", "request", ".", "_serialize", "(", ")", "body", "=", "self", ".", "call", "(", "\"CreateAgentTaxPaymentInfos\"", ",", "params", ")", "response", "=", "json...
https://github.com/TencentCloud/tencentcloud-sdk-python/blob/3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2/tencentcloud/cpdp/v20190820/cpdp_client.py#L596-L621
pawamoy/aria2p
2855c6a9a38e36278671258439f6caf59c39cfc3
src/aria2p/downloads.py
python
File.is_metadata
(self)
return str(self.path).startswith("[METADATA]")
Return True if this file is aria2 metadata and not an actual file. Returns: If the file is metadata.
Return True if this file is aria2 metadata and not an actual file.
[ "Return", "True", "if", "this", "file", "is", "aria2", "metadata", "and", "not", "an", "actual", "file", "." ]
def is_metadata(self) -> bool: """ Return True if this file is aria2 metadata and not an actual file. Returns: If the file is metadata. """ return str(self.path).startswith("[METADATA]")
[ "def", "is_metadata", "(", "self", ")", "->", "bool", ":", "return", "str", "(", "self", ".", "path", ")", ".", "startswith", "(", "\"[METADATA]\"", ")" ]
https://github.com/pawamoy/aria2p/blob/2855c6a9a38e36278671258439f6caf59c39cfc3/src/aria2p/downloads.py#L136-L143
GoogleCloudPlatform/professional-services
0c707aa97437f3d154035ef8548109b7882f71da
tools/ml-auto-eda/ml_eda/reporting/recommendation.py
python
check_p_value
(analysis: Analysis)
return None
Check whether the p-value of statistical tests exceed the predefined threshold Args: analysis: (analysis_entity_pb2.Analysis), analysis that contain the result of statistical test Returns: Union[None, string]
Check whether the p-value of statistical tests exceed the predefined threshold
[ "Check", "whether", "the", "p", "-", "value", "of", "statistical", "tests", "exceed", "the", "predefined", "threshold" ]
def check_p_value(analysis: Analysis) -> Union[None, Text]: """Check whether the p-value of statistical tests exceed the predefined threshold Args: analysis: (analysis_entity_pb2.Analysis), analysis that contain the result of statistical test Returns: Union[None, string] """ metric = analysis.smetrics[0] name_list = [att.name for att in analysis.features] p_value = metric.value if p_value < P_VALUE_THRESHOLD: return template.LOW_P_VALUE.format( name_one=name_list[0], name_two=name_list[1], metric='p-value', value=formatting.numeric_formatting(p_value) ) return None
[ "def", "check_p_value", "(", "analysis", ":", "Analysis", ")", "->", "Union", "[", "None", ",", "Text", "]", ":", "metric", "=", "analysis", ".", "smetrics", "[", "0", "]", "name_list", "=", "[", "att", ".", "name", "for", "att", "in", "analysis", "....
https://github.com/GoogleCloudPlatform/professional-services/blob/0c707aa97437f3d154035ef8548109b7882f71da/tools/ml-auto-eda/ml_eda/reporting/recommendation.py#L131-L154
pwnieexpress/pwn_plug_sources
1a23324f5dc2c3de20f9c810269b6a29b2758cad
src/metagoofil/hachoir_core/text_handler.py
python
textHandler
(field, handler)
return field
[]
def textHandler(field, handler): assert isinstance(handler, (FunctionType, MethodType)) assert issubclass(field.__class__, Field) field.createDisplay = lambda: handler(field) return field
[ "def", "textHandler", "(", "field", ",", "handler", ")", ":", "assert", "isinstance", "(", "handler", ",", "(", "FunctionType", ",", "MethodType", ")", ")", "assert", "issubclass", "(", "field", ".", "__class__", ",", "Field", ")", "field", ".", "createDis...
https://github.com/pwnieexpress/pwn_plug_sources/blob/1a23324f5dc2c3de20f9c810269b6a29b2758cad/src/metagoofil/hachoir_core/text_handler.py#L13-L17
mila-iqia/myia
56774a39579b4ec4123f44843ad4ca688acc859b
myia/utils/unify.py
python
RestrictedVar.intersection
(self, v)
Return the intersection of two RestrictedVars. The resulting variable's legal values are the intersection of self and v's legal values.
Return the intersection of two RestrictedVars.
[ "Return", "the", "intersection", "of", "two", "RestrictedVars", "." ]
def intersection(self, v): """Return the intersection of two RestrictedVars. The resulting variable's legal values are the intersection of self and v's legal values. """ if isinstance(v, RestrictedVar): lv = set(self.legal_values) lv2 = set(v.legal_values) common = lv & lv2 if common == lv: return self elif common == lv2: return v elif common: return RestrictedVar(common) else: return False else: return NotImplemented
[ "def", "intersection", "(", "self", ",", "v", ")", ":", "if", "isinstance", "(", "v", ",", "RestrictedVar", ")", ":", "lv", "=", "set", "(", "self", ".", "legal_values", ")", "lv2", "=", "set", "(", "v", ".", "legal_values", ")", "common", "=", "lv...
https://github.com/mila-iqia/myia/blob/56774a39579b4ec4123f44843ad4ca688acc859b/myia/utils/unify.py#L141-L160
hydroshare/hydroshare
7ba563b55412f283047fb3ef6da367d41dec58c6
hs_core/management/utils.py
python
__ingest_irods_directory
(resource, dir, logger, stop_on_error=False, log_errors=True, echo_errors=False, return_errors=False)
return errors, ecount
list a directory and ingest files there for conformance with django ResourceFiles :param stop_on_error: whether to raise a ValidationError exception on first error :param log_errors: whether to log errors to Django log :param echo_errors: whether to print errors on stdout :param return_errors: whether to collect errors in an array and return them.
list a directory and ingest files there for conformance with django ResourceFiles
[ "list", "a", "directory", "and", "ingest", "files", "there", "for", "conformance", "with", "django", "ResourceFiles" ]
def __ingest_irods_directory(resource, dir, logger, stop_on_error=False, log_errors=True, echo_errors=False, return_errors=False): """ list a directory and ingest files there for conformance with django ResourceFiles :param stop_on_error: whether to raise a ValidationError exception on first error :param log_errors: whether to log errors to Django log :param echo_errors: whether to print errors on stdout :param return_errors: whether to collect errors in an array and return them. """ errors = [] ecount = 0 istorage = resource.get_irods_storage() try: listing = istorage.listdir(dir) for fname in listing[1]: # files # do not use os.path.join because fname might contain unicode characters fullpath = dir + '/' + fname found = False for res_file in resource.files.all(): if res_file.storage_path == fullpath: found = True if not found and not resource.is_aggregation_xml_file(fullpath): ecount += 1 msg = "ingest_irods_files: file {} in iRODs does not exist in Django (INGESTING)"\ .format(fullpath) if echo_errors: print(msg) if log_errors: logger.error(msg) if return_errors: errors.append(msg) if stop_on_error: raise ValidationError(msg) # TODO: does not ingest logical file structure for composite resources link_irods_file_to_django(resource, fullpath) # Create required logical files as necessary if resource.resource_type == "CompositeResource": file_type = get_logical_file_type(res=resource, file_id=res_file.pk, fail_feedback=False) if not res_file.has_logical_file and file_type is not None: msg = "ingest_irods_files: setting required logical file for {}"\ .format(fullpath) if echo_errors: print(msg) if log_errors: logger.error(msg) if return_errors: errors.append(msg) if stop_on_error: raise ValidationError(msg) set_logical_file_type(res=resource, user=None, file_id=res_file.pk, fail_feedback=False) elif res_file.has_logical_file and file_type is not None and \ not isinstance(res_file.logical_file, file_type): msg = "ingest_irods_files: logical file for {} has type {}, should be {}"\ .format(res_file.storage_path, type(res_file.logical_file).__name__, file_type.__name__) if echo_errors: print(msg) if log_errors: logger.error(msg) if return_errors: errors.append(msg) if stop_on_error: raise ValidationError(msg) elif res_file.has_logical_file and file_type is None: msg = "ingest_irods_files: logical file for {} has type {}, not needed"\ .format(res_file.storage_path, type(res_file.logical_file).__name__, file_type.__name__) if echo_errors: print(msg) if log_errors: logger.error(msg) if return_errors: errors.append(msg) if stop_on_error: raise ValidationError(msg) for dname in listing[0]: # directories # do not use os.path.join because fname might contain unicode characters error2, ecount2 = __ingest_irods_directory(resource, dir + '/' + dname, logger, stop_on_error=stop_on_error, echo_errors=echo_errors, log_errors=log_errors, return_errors=return_errors) errors.extend(error2) ecount += ecount2 except SessionException as se: print("iRODs error: {}".format(se.stderr)) logger.error("iRODs error: {}".format(se.stderr)) return errors, ecount
[ "def", "__ingest_irods_directory", "(", "resource", ",", "dir", ",", "logger", ",", "stop_on_error", "=", "False", ",", "log_errors", "=", "True", ",", "echo_errors", "=", "False", ",", "return_errors", "=", "False", ")", ":", "errors", "=", "[", "]", "eco...
https://github.com/hydroshare/hydroshare/blob/7ba563b55412f283047fb3ef6da367d41dec58c6/hs_core/management/utils.py#L354-L458
hyperledger/aries-cloudagent-python
2f36776e99f6053ae92eed8123b5b1b2e891c02a
aries_cloudagent/utils/task_queue.py
python
PendingTask.task
(self, task: asyncio.Task)
Setter for the task.
Setter for the task.
[ "Setter", "for", "the", "task", "." ]
def task(self, task: asyncio.Task): """Setter for the task.""" if self.task_future.cancelled(): return elif self.task_future.done(): raise ValueError("Cannot set pending task future, already done") self.task_future.set_result(task)
[ "def", "task", "(", "self", ",", "task", ":", "asyncio", ".", "Task", ")", ":", "if", "self", ".", "task_future", ".", "cancelled", "(", ")", ":", "return", "elif", "self", ".", "task_future", ".", "done", "(", ")", ":", "raise", "ValueError", "(", ...
https://github.com/hyperledger/aries-cloudagent-python/blob/2f36776e99f6053ae92eed8123b5b1b2e891c02a/aries_cloudagent/utils/task_queue.py#L107-L113