repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
alexa/alexa-skills-kit-sdk-for-python | ask-sdk-core/ask_sdk_core/api_client.py | DefaultApiClient._convert_list_tuples_to_dict | def _convert_list_tuples_to_dict(self, headers_list):
# type: (List[Tuple[str, str]]) -> Dict[str, str]
"""Convert list of tuples from headers of request object to
dictionary format.
:param headers_list: List of tuples made up of two element
strings from `ApiClientRequest` headers variable
:type headers_list: List[Tuple[str, str]]
:return: Dictionary of headers in keys as strings and values
as comma separated strings
:rtype: Dict[str, str]
"""
headers_dict = {} # type: Dict
if headers_list is not None:
for header_tuple in headers_list:
key, value = header_tuple[0], header_tuple[1]
if key in headers_dict:
headers_dict[key] = "{}, {}".format(
headers_dict[key], value)
else:
headers_dict[header_tuple[0]] = value
return headers_dict | python | def _convert_list_tuples_to_dict(self, headers_list):
# type: (List[Tuple[str, str]]) -> Dict[str, str]
"""Convert list of tuples from headers of request object to
dictionary format.
:param headers_list: List of tuples made up of two element
strings from `ApiClientRequest` headers variable
:type headers_list: List[Tuple[str, str]]
:return: Dictionary of headers in keys as strings and values
as comma separated strings
:rtype: Dict[str, str]
"""
headers_dict = {} # type: Dict
if headers_list is not None:
for header_tuple in headers_list:
key, value = header_tuple[0], header_tuple[1]
if key in headers_dict:
headers_dict[key] = "{}, {}".format(
headers_dict[key], value)
else:
headers_dict[header_tuple[0]] = value
return headers_dict | [
"def",
"_convert_list_tuples_to_dict",
"(",
"self",
",",
"headers_list",
")",
":",
"# type: (List[Tuple[str, str]]) -> Dict[str, str]",
"headers_dict",
"=",
"{",
"}",
"# type: Dict",
"if",
"headers_list",
"is",
"not",
"None",
":",
"for",
"header_tuple",
"in",
"headers_l... | Convert list of tuples from headers of request object to
dictionary format.
:param headers_list: List of tuples made up of two element
strings from `ApiClientRequest` headers variable
:type headers_list: List[Tuple[str, str]]
:return: Dictionary of headers in keys as strings and values
as comma separated strings
:rtype: Dict[str, str] | [
"Convert",
"list",
"of",
"tuples",
"from",
"headers",
"of",
"request",
"object",
"to",
"dictionary",
"format",
"."
] | 097b6406aa12d5ca0b825b00c936861b530cbf39 | https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/ask-sdk-core/ask_sdk_core/api_client.py#L109-L130 | train | 215,400 |
alexa/alexa-skills-kit-sdk-for-python | ask-sdk-core/ask_sdk_core/api_client.py | DefaultApiClient._convert_dict_to_list_tuples | def _convert_dict_to_list_tuples(self, headers_dict):
# type: (Dict[str, str]) -> List[Tuple[str, str]]
"""Convert headers dict to list of string tuples format for
`ApiClientResponse` headers variable.
:param headers_dict: Dictionary of headers in keys as strings
and values as comma separated strings
:type headers_dict: Dict[str, str]
:return: List of tuples made up of two element strings from
headers of client response
:rtype: List[Tuple[str, str]]
"""
headers_list = []
if headers_dict is not None:
for key, values in six.iteritems(headers_dict):
for value in values.split(","):
value = value.strip()
if value is not None and value is not '':
headers_list.append((key, value.strip()))
return headers_list | python | def _convert_dict_to_list_tuples(self, headers_dict):
# type: (Dict[str, str]) -> List[Tuple[str, str]]
"""Convert headers dict to list of string tuples format for
`ApiClientResponse` headers variable.
:param headers_dict: Dictionary of headers in keys as strings
and values as comma separated strings
:type headers_dict: Dict[str, str]
:return: List of tuples made up of two element strings from
headers of client response
:rtype: List[Tuple[str, str]]
"""
headers_list = []
if headers_dict is not None:
for key, values in six.iteritems(headers_dict):
for value in values.split(","):
value = value.strip()
if value is not None and value is not '':
headers_list.append((key, value.strip()))
return headers_list | [
"def",
"_convert_dict_to_list_tuples",
"(",
"self",
",",
"headers_dict",
")",
":",
"# type: (Dict[str, str]) -> List[Tuple[str, str]]",
"headers_list",
"=",
"[",
"]",
"if",
"headers_dict",
"is",
"not",
"None",
":",
"for",
"key",
",",
"values",
"in",
"six",
".",
"i... | Convert headers dict to list of string tuples format for
`ApiClientResponse` headers variable.
:param headers_dict: Dictionary of headers in keys as strings
and values as comma separated strings
:type headers_dict: Dict[str, str]
:return: List of tuples made up of two element strings from
headers of client response
:rtype: List[Tuple[str, str]] | [
"Convert",
"headers",
"dict",
"to",
"list",
"of",
"string",
"tuples",
"format",
"for",
"ApiClientResponse",
"headers",
"variable",
"."
] | 097b6406aa12d5ca0b825b00c936861b530cbf39 | https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/ask-sdk-core/ask_sdk_core/api_client.py#L132-L151 | train | 215,401 |
alexa/alexa-skills-kit-sdk-for-python | ask-sdk-runtime/ask_sdk_runtime/dispatch_components/request_components.py | GenericRequestMapper.add_request_handler_chain | def add_request_handler_chain(self, request_handler_chain):
# type: (GenericRequestHandlerChain) -> None
"""Checks the type before adding it to the
request_handler_chains instance variable.
:param request_handler_chain: Request Handler Chain instance.
:type request_handler_chain: RequestHandlerChain
:raises: :py:class:`ask_sdk_runtime.exceptions.DispatchException`
if a null input is provided or if the input is of invalid type
"""
if request_handler_chain is None or not isinstance(
request_handler_chain, GenericRequestHandlerChain):
raise DispatchException(
"Request Handler Chain is not a GenericRequestHandlerChain "
"instance")
self._request_handler_chains.append(request_handler_chain) | python | def add_request_handler_chain(self, request_handler_chain):
# type: (GenericRequestHandlerChain) -> None
"""Checks the type before adding it to the
request_handler_chains instance variable.
:param request_handler_chain: Request Handler Chain instance.
:type request_handler_chain: RequestHandlerChain
:raises: :py:class:`ask_sdk_runtime.exceptions.DispatchException`
if a null input is provided or if the input is of invalid type
"""
if request_handler_chain is None or not isinstance(
request_handler_chain, GenericRequestHandlerChain):
raise DispatchException(
"Request Handler Chain is not a GenericRequestHandlerChain "
"instance")
self._request_handler_chains.append(request_handler_chain) | [
"def",
"add_request_handler_chain",
"(",
"self",
",",
"request_handler_chain",
")",
":",
"# type: (GenericRequestHandlerChain) -> None",
"if",
"request_handler_chain",
"is",
"None",
"or",
"not",
"isinstance",
"(",
"request_handler_chain",
",",
"GenericRequestHandlerChain",
")... | Checks the type before adding it to the
request_handler_chains instance variable.
:param request_handler_chain: Request Handler Chain instance.
:type request_handler_chain: RequestHandlerChain
:raises: :py:class:`ask_sdk_runtime.exceptions.DispatchException`
if a null input is provided or if the input is of invalid type | [
"Checks",
"the",
"type",
"before",
"adding",
"it",
"to",
"the",
"request_handler_chains",
"instance",
"variable",
"."
] | 097b6406aa12d5ca0b825b00c936861b530cbf39 | https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/ask-sdk-runtime/ask_sdk_runtime/dispatch_components/request_components.py#L331-L346 | train | 215,402 |
alexa/alexa-skills-kit-sdk-for-python | ask-sdk-runtime/ask_sdk_runtime/dispatch_components/request_components.py | GenericRequestMapper.get_request_handler_chain | def get_request_handler_chain(self, handler_input):
# type: (Input) -> Union[GenericRequestHandlerChain, None]
"""Get the request handler chain that can handle the dispatch
input.
:param handler_input: Generic input passed to the
dispatcher.
:type handler_input: Input
:return: Handler Chain that can handle the input.
:rtype: Union[None, GenericRequestHandlerChain]
"""
for chain in self.request_handler_chains:
handler = chain.request_handler # type: AbstractRequestHandler
if handler.can_handle(handler_input=handler_input):
return chain
return None | python | def get_request_handler_chain(self, handler_input):
# type: (Input) -> Union[GenericRequestHandlerChain, None]
"""Get the request handler chain that can handle the dispatch
input.
:param handler_input: Generic input passed to the
dispatcher.
:type handler_input: Input
:return: Handler Chain that can handle the input.
:rtype: Union[None, GenericRequestHandlerChain]
"""
for chain in self.request_handler_chains:
handler = chain.request_handler # type: AbstractRequestHandler
if handler.can_handle(handler_input=handler_input):
return chain
return None | [
"def",
"get_request_handler_chain",
"(",
"self",
",",
"handler_input",
")",
":",
"# type: (Input) -> Union[GenericRequestHandlerChain, None]",
"for",
"chain",
"in",
"self",
".",
"request_handler_chains",
":",
"handler",
"=",
"chain",
".",
"request_handler",
"# type: Abstrac... | Get the request handler chain that can handle the dispatch
input.
:param handler_input: Generic input passed to the
dispatcher.
:type handler_input: Input
:return: Handler Chain that can handle the input.
:rtype: Union[None, GenericRequestHandlerChain] | [
"Get",
"the",
"request",
"handler",
"chain",
"that",
"can",
"handle",
"the",
"dispatch",
"input",
"."
] | 097b6406aa12d5ca0b825b00c936861b530cbf39 | https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/ask-sdk-runtime/ask_sdk_runtime/dispatch_components/request_components.py#L348-L363 | train | 215,403 |
alexa/alexa-skills-kit-sdk-for-python | ask-sdk-runtime/ask_sdk_runtime/dispatch_components/exception_components.py | GenericExceptionMapper.add_exception_handler | def add_exception_handler(self, exception_handler):
# type: (AbstractExceptionHandler) -> None
"""Checks the type before adding it to the exception_handlers
instance variable.
:param exception_handler: Exception Handler instance.
:type exception_handler: ask_sdk_runtime.dispatch_components.exception_components.AbstractExceptionHandler
:raises: :py:class:`ask_sdk_runtime.exceptions.DispatchException` if a
null input is provided or if the input is of invalid type
"""
if exception_handler is None or not isinstance(
exception_handler, AbstractExceptionHandler):
raise DispatchException(
"Input is not an AbstractExceptionHandler instance")
self._exception_handlers.append(exception_handler) | python | def add_exception_handler(self, exception_handler):
# type: (AbstractExceptionHandler) -> None
"""Checks the type before adding it to the exception_handlers
instance variable.
:param exception_handler: Exception Handler instance.
:type exception_handler: ask_sdk_runtime.dispatch_components.exception_components.AbstractExceptionHandler
:raises: :py:class:`ask_sdk_runtime.exceptions.DispatchException` if a
null input is provided or if the input is of invalid type
"""
if exception_handler is None or not isinstance(
exception_handler, AbstractExceptionHandler):
raise DispatchException(
"Input is not an AbstractExceptionHandler instance")
self._exception_handlers.append(exception_handler) | [
"def",
"add_exception_handler",
"(",
"self",
",",
"exception_handler",
")",
":",
"# type: (AbstractExceptionHandler) -> None",
"if",
"exception_handler",
"is",
"None",
"or",
"not",
"isinstance",
"(",
"exception_handler",
",",
"AbstractExceptionHandler",
")",
":",
"raise",... | Checks the type before adding it to the exception_handlers
instance variable.
:param exception_handler: Exception Handler instance.
:type exception_handler: ask_sdk_runtime.dispatch_components.exception_components.AbstractExceptionHandler
:raises: :py:class:`ask_sdk_runtime.exceptions.DispatchException` if a
null input is provided or if the input is of invalid type | [
"Checks",
"the",
"type",
"before",
"adding",
"it",
"to",
"the",
"exception_handlers",
"instance",
"variable",
"."
] | 097b6406aa12d5ca0b825b00c936861b530cbf39 | https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/ask-sdk-runtime/ask_sdk_runtime/dispatch_components/exception_components.py#L165-L179 | train | 215,404 |
alexa/alexa-skills-kit-sdk-for-python | ask-sdk-runtime/ask_sdk_runtime/dispatch_components/exception_components.py | GenericExceptionMapper.get_handler | def get_handler(self, handler_input, exception):
# type: (Input, Exception) -> Union[AbstractExceptionHandler, None]
"""Get the exception handler that can handle the input and
exception.
:param handler_input: Generic input passed to the
dispatcher.
:type handler_input: Input
:param exception: Exception thrown by
:py:class:`ask_sdk_runtime.dispatch.GenericRequestDispatcher`
dispatch method.
:type exception: Exception
:return: Exception Handler that can handle the input or None.
:rtype: Union[None, ask_sdk_runtime.dispatch_components.exception_components.AbstractExceptionHandler]
"""
for handler in self.exception_handlers:
if handler.can_handle(
handler_input=handler_input, exception=exception):
return handler
return None | python | def get_handler(self, handler_input, exception):
# type: (Input, Exception) -> Union[AbstractExceptionHandler, None]
"""Get the exception handler that can handle the input and
exception.
:param handler_input: Generic input passed to the
dispatcher.
:type handler_input: Input
:param exception: Exception thrown by
:py:class:`ask_sdk_runtime.dispatch.GenericRequestDispatcher`
dispatch method.
:type exception: Exception
:return: Exception Handler that can handle the input or None.
:rtype: Union[None, ask_sdk_runtime.dispatch_components.exception_components.AbstractExceptionHandler]
"""
for handler in self.exception_handlers:
if handler.can_handle(
handler_input=handler_input, exception=exception):
return handler
return None | [
"def",
"get_handler",
"(",
"self",
",",
"handler_input",
",",
"exception",
")",
":",
"# type: (Input, Exception) -> Union[AbstractExceptionHandler, None]",
"for",
"handler",
"in",
"self",
".",
"exception_handlers",
":",
"if",
"handler",
".",
"can_handle",
"(",
"handler_... | Get the exception handler that can handle the input and
exception.
:param handler_input: Generic input passed to the
dispatcher.
:type handler_input: Input
:param exception: Exception thrown by
:py:class:`ask_sdk_runtime.dispatch.GenericRequestDispatcher`
dispatch method.
:type exception: Exception
:return: Exception Handler that can handle the input or None.
:rtype: Union[None, ask_sdk_runtime.dispatch_components.exception_components.AbstractExceptionHandler] | [
"Get",
"the",
"exception",
"handler",
"that",
"can",
"handle",
"the",
"input",
"and",
"exception",
"."
] | 097b6406aa12d5ca0b825b00c936861b530cbf39 | https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/ask-sdk-runtime/ask_sdk_runtime/dispatch_components/exception_components.py#L181-L200 | train | 215,405 |
alexa/alexa-skills-kit-sdk-for-python | ask-sdk-webservice-support/ask_sdk_webservice_support/verifier.py | RequestVerifier.verify | def verify(
self, headers, serialized_request_env, deserialized_request_env):
# type: (Dict[str, Any], str, RequestEnvelope) -> None
"""Verify if the input request signature and the body matches.
The verify method retrieves the Signature Certificate Chain URL,
validates the URL, retrieves the chain from the URL, validates
the signing certificate, extract the public key, base64 decode
the Signature and verifies if the hash value of the request body
matches with the decrypted signature.
:param headers: headers of the input POST request
:type headers: Dict[str, Any]
:param serialized_request_env: raw request envelope in the
input POST request
:type serialized_request_env: str
:param deserialized_request_env: deserialized request envelope
instance of the input POST request
:type deserialized_request_env:
:py:class:`ask_sdk_model.request_envelope.RequestEnvelope`
:raises: :py:class:`VerificationException` if headers doesn't
exist or verification fails
"""
cert_url = headers.get(self._signature_cert_chain_url_key)
signature = headers.get(self._signature_key)
if cert_url is None or signature is None:
raise VerificationException(
"Missing Signature/Certificate for the skill request")
cert_chain = self._retrieve_and_validate_certificate_chain(cert_url)
self._valid_request_body(
cert_chain, signature, serialized_request_env) | python | def verify(
self, headers, serialized_request_env, deserialized_request_env):
# type: (Dict[str, Any], str, RequestEnvelope) -> None
"""Verify if the input request signature and the body matches.
The verify method retrieves the Signature Certificate Chain URL,
validates the URL, retrieves the chain from the URL, validates
the signing certificate, extract the public key, base64 decode
the Signature and verifies if the hash value of the request body
matches with the decrypted signature.
:param headers: headers of the input POST request
:type headers: Dict[str, Any]
:param serialized_request_env: raw request envelope in the
input POST request
:type serialized_request_env: str
:param deserialized_request_env: deserialized request envelope
instance of the input POST request
:type deserialized_request_env:
:py:class:`ask_sdk_model.request_envelope.RequestEnvelope`
:raises: :py:class:`VerificationException` if headers doesn't
exist or verification fails
"""
cert_url = headers.get(self._signature_cert_chain_url_key)
signature = headers.get(self._signature_key)
if cert_url is None or signature is None:
raise VerificationException(
"Missing Signature/Certificate for the skill request")
cert_chain = self._retrieve_and_validate_certificate_chain(cert_url)
self._valid_request_body(
cert_chain, signature, serialized_request_env) | [
"def",
"verify",
"(",
"self",
",",
"headers",
",",
"serialized_request_env",
",",
"deserialized_request_env",
")",
":",
"# type: (Dict[str, Any], str, RequestEnvelope) -> None",
"cert_url",
"=",
"headers",
".",
"get",
"(",
"self",
".",
"_signature_cert_chain_url_key",
")"... | Verify if the input request signature and the body matches.
The verify method retrieves the Signature Certificate Chain URL,
validates the URL, retrieves the chain from the URL, validates
the signing certificate, extract the public key, base64 decode
the Signature and verifies if the hash value of the request body
matches with the decrypted signature.
:param headers: headers of the input POST request
:type headers: Dict[str, Any]
:param serialized_request_env: raw request envelope in the
input POST request
:type serialized_request_env: str
:param deserialized_request_env: deserialized request envelope
instance of the input POST request
:type deserialized_request_env:
:py:class:`ask_sdk_model.request_envelope.RequestEnvelope`
:raises: :py:class:`VerificationException` if headers doesn't
exist or verification fails | [
"Verify",
"if",
"the",
"input",
"request",
"signature",
"and",
"the",
"body",
"matches",
"."
] | 097b6406aa12d5ca0b825b00c936861b530cbf39 | https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/ask-sdk-webservice-support/ask_sdk_webservice_support/verifier.py#L165-L198 | train | 215,406 |
alexa/alexa-skills-kit-sdk-for-python | ask-sdk-webservice-support/ask_sdk_webservice_support/verifier.py | RequestVerifier._retrieve_and_validate_certificate_chain | def _retrieve_and_validate_certificate_chain(self, cert_url):
# type: (str) -> Certificate
"""Retrieve and validate certificate chain.
This method validates if the URL is valid and loads and
validates the certificate chain, before returning it.
:param cert_url: URL for retrieving certificate chain
:type cert_url: str
:return The certificate chain loaded from the URL
:rtype cryptography.x509.Certificate
:raises: :py:class:`VerificationException` if the URL is invalid,
if the loaded certificate chain is invalid
"""
self._validate_certificate_url(cert_url)
cert_chain = self._load_cert_chain(cert_url)
self._validate_cert_chain(cert_chain)
return cert_chain | python | def _retrieve_and_validate_certificate_chain(self, cert_url):
# type: (str) -> Certificate
"""Retrieve and validate certificate chain.
This method validates if the URL is valid and loads and
validates the certificate chain, before returning it.
:param cert_url: URL for retrieving certificate chain
:type cert_url: str
:return The certificate chain loaded from the URL
:rtype cryptography.x509.Certificate
:raises: :py:class:`VerificationException` if the URL is invalid,
if the loaded certificate chain is invalid
"""
self._validate_certificate_url(cert_url)
cert_chain = self._load_cert_chain(cert_url)
self._validate_cert_chain(cert_chain)
return cert_chain | [
"def",
"_retrieve_and_validate_certificate_chain",
"(",
"self",
",",
"cert_url",
")",
":",
"# type: (str) -> Certificate",
"self",
".",
"_validate_certificate_url",
"(",
"cert_url",
")",
"cert_chain",
"=",
"self",
".",
"_load_cert_chain",
"(",
"cert_url",
")",
"self",
... | Retrieve and validate certificate chain.
This method validates if the URL is valid and loads and
validates the certificate chain, before returning it.
:param cert_url: URL for retrieving certificate chain
:type cert_url: str
:return The certificate chain loaded from the URL
:rtype cryptography.x509.Certificate
:raises: :py:class:`VerificationException` if the URL is invalid,
if the loaded certificate chain is invalid | [
"Retrieve",
"and",
"validate",
"certificate",
"chain",
"."
] | 097b6406aa12d5ca0b825b00c936861b530cbf39 | https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/ask-sdk-webservice-support/ask_sdk_webservice_support/verifier.py#L200-L218 | train | 215,407 |
alexa/alexa-skills-kit-sdk-for-python | ask-sdk-webservice-support/ask_sdk_webservice_support/verifier.py | RequestVerifier._validate_certificate_url | def _validate_certificate_url(self, cert_url):
# type: (str) -> None
"""Validate the URL containing the certificate chain.
This method validates if the URL provided adheres to the format
mentioned here :
https://developer.amazon.com/docs/custom-skills/host-a-custom-skill-as-a-web-service.html#cert-verify-signature-certificate-url
:param cert_url: URL for retrieving certificate chain
:type cert_url: str
:raises: :py:class:`VerificationException` if the URL is invalid
"""
parsed_url = urlparse(cert_url)
protocol = parsed_url.scheme
if protocol.lower() != CERT_CHAIN_URL_PROTOCOL.lower():
raise VerificationException(
"Signature Certificate URL has invalid protocol: {}. "
"Expecting {}".format(protocol, CERT_CHAIN_URL_PROTOCOL))
hostname = parsed_url.hostname
if (hostname is None or
hostname.lower() != CERT_CHAIN_URL_HOSTNAME.lower()):
raise VerificationException(
"Signature Certificate URL has invalid hostname: {}. "
"Expecting {}".format(hostname, CERT_CHAIN_URL_HOSTNAME))
normalized_path = os.path.normpath(parsed_url.path)
if not normalized_path.startswith(CERT_CHAIN_URL_STARTPATH):
raise VerificationException(
"Signature Certificate URL has invalid path: {}. "
"Expecting the path to start with {}".format(
normalized_path, CERT_CHAIN_URL_STARTPATH))
port = parsed_url.port
if port is not None and port != CERT_CHAIN_URL_PORT:
raise VerificationException(
"Signature Certificate URL has invalid port: {}. "
"Expecting {}".format(str(port), str(CERT_CHAIN_URL_PORT))) | python | def _validate_certificate_url(self, cert_url):
# type: (str) -> None
"""Validate the URL containing the certificate chain.
This method validates if the URL provided adheres to the format
mentioned here :
https://developer.amazon.com/docs/custom-skills/host-a-custom-skill-as-a-web-service.html#cert-verify-signature-certificate-url
:param cert_url: URL for retrieving certificate chain
:type cert_url: str
:raises: :py:class:`VerificationException` if the URL is invalid
"""
parsed_url = urlparse(cert_url)
protocol = parsed_url.scheme
if protocol.lower() != CERT_CHAIN_URL_PROTOCOL.lower():
raise VerificationException(
"Signature Certificate URL has invalid protocol: {}. "
"Expecting {}".format(protocol, CERT_CHAIN_URL_PROTOCOL))
hostname = parsed_url.hostname
if (hostname is None or
hostname.lower() != CERT_CHAIN_URL_HOSTNAME.lower()):
raise VerificationException(
"Signature Certificate URL has invalid hostname: {}. "
"Expecting {}".format(hostname, CERT_CHAIN_URL_HOSTNAME))
normalized_path = os.path.normpath(parsed_url.path)
if not normalized_path.startswith(CERT_CHAIN_URL_STARTPATH):
raise VerificationException(
"Signature Certificate URL has invalid path: {}. "
"Expecting the path to start with {}".format(
normalized_path, CERT_CHAIN_URL_STARTPATH))
port = parsed_url.port
if port is not None and port != CERT_CHAIN_URL_PORT:
raise VerificationException(
"Signature Certificate URL has invalid port: {}. "
"Expecting {}".format(str(port), str(CERT_CHAIN_URL_PORT))) | [
"def",
"_validate_certificate_url",
"(",
"self",
",",
"cert_url",
")",
":",
"# type: (str) -> None",
"parsed_url",
"=",
"urlparse",
"(",
"cert_url",
")",
"protocol",
"=",
"parsed_url",
".",
"scheme",
"if",
"protocol",
".",
"lower",
"(",
")",
"!=",
"CERT_CHAIN_UR... | Validate the URL containing the certificate chain.
This method validates if the URL provided adheres to the format
mentioned here :
https://developer.amazon.com/docs/custom-skills/host-a-custom-skill-as-a-web-service.html#cert-verify-signature-certificate-url
:param cert_url: URL for retrieving certificate chain
:type cert_url: str
:raises: :py:class:`VerificationException` if the URL is invalid | [
"Validate",
"the",
"URL",
"containing",
"the",
"certificate",
"chain",
"."
] | 097b6406aa12d5ca0b825b00c936861b530cbf39 | https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/ask-sdk-webservice-support/ask_sdk_webservice_support/verifier.py#L220-L258 | train | 215,408 |
alexa/alexa-skills-kit-sdk-for-python | ask-sdk-webservice-support/ask_sdk_webservice_support/verifier.py | RequestVerifier._load_cert_chain | def _load_cert_chain(self, cert_url, x509_backend=default_backend()):
# type: (str, X509Backend) -> Certificate
"""Loads the certificate chain from the URL.
This method loads the certificate chain from the certificate
cache. If there is a cache miss, the certificate chain is
loaded from the certificate URL using the
:py:func:`cryptography.x509.load_pem_x509_certificate` method.
The x509 backend is set as default to the
:py:class:`cryptography.hazmat.backends.default_backend`
instance. A :py:class:`VerificationException` is raised if the
certificate cannot be loaded.
:param cert_url: URL for retrieving certificate chain
:type cert_url: str
:param x509_backend: Backend to be used, for loading pem x509
certificate
:type x509_backend:
cryptography.hazmat.backends.interfaces.X509Backend
:return: Certificate chain loaded from cache or URL
:rtype cryptography.x509.Certificate
:raises: :py:class:`VerificationException` if unable to load the
certificate
"""
try:
if cert_url in self._cert_cache:
return self._cert_cache.get(cert_url)
else:
with urlopen(cert_url) as cert_response:
cert_data = cert_response.read()
x509_certificate = load_pem_x509_certificate(
cert_data, x509_backend)
self._cert_cache[cert_url] = x509_certificate
return x509_certificate
except ValueError as e:
raise VerificationException(
"Unable to load certificate from URL", e) | python | def _load_cert_chain(self, cert_url, x509_backend=default_backend()):
# type: (str, X509Backend) -> Certificate
"""Loads the certificate chain from the URL.
This method loads the certificate chain from the certificate
cache. If there is a cache miss, the certificate chain is
loaded from the certificate URL using the
:py:func:`cryptography.x509.load_pem_x509_certificate` method.
The x509 backend is set as default to the
:py:class:`cryptography.hazmat.backends.default_backend`
instance. A :py:class:`VerificationException` is raised if the
certificate cannot be loaded.
:param cert_url: URL for retrieving certificate chain
:type cert_url: str
:param x509_backend: Backend to be used, for loading pem x509
certificate
:type x509_backend:
cryptography.hazmat.backends.interfaces.X509Backend
:return: Certificate chain loaded from cache or URL
:rtype cryptography.x509.Certificate
:raises: :py:class:`VerificationException` if unable to load the
certificate
"""
try:
if cert_url in self._cert_cache:
return self._cert_cache.get(cert_url)
else:
with urlopen(cert_url) as cert_response:
cert_data = cert_response.read()
x509_certificate = load_pem_x509_certificate(
cert_data, x509_backend)
self._cert_cache[cert_url] = x509_certificate
return x509_certificate
except ValueError as e:
raise VerificationException(
"Unable to load certificate from URL", e) | [
"def",
"_load_cert_chain",
"(",
"self",
",",
"cert_url",
",",
"x509_backend",
"=",
"default_backend",
"(",
")",
")",
":",
"# type: (str, X509Backend) -> Certificate",
"try",
":",
"if",
"cert_url",
"in",
"self",
".",
"_cert_cache",
":",
"return",
"self",
".",
"_c... | Loads the certificate chain from the URL.
This method loads the certificate chain from the certificate
cache. If there is a cache miss, the certificate chain is
loaded from the certificate URL using the
:py:func:`cryptography.x509.load_pem_x509_certificate` method.
The x509 backend is set as default to the
:py:class:`cryptography.hazmat.backends.default_backend`
instance. A :py:class:`VerificationException` is raised if the
certificate cannot be loaded.
:param cert_url: URL for retrieving certificate chain
:type cert_url: str
:param x509_backend: Backend to be used, for loading pem x509
certificate
:type x509_backend:
cryptography.hazmat.backends.interfaces.X509Backend
:return: Certificate chain loaded from cache or URL
:rtype cryptography.x509.Certificate
:raises: :py:class:`VerificationException` if unable to load the
certificate | [
"Loads",
"the",
"certificate",
"chain",
"from",
"the",
"URL",
"."
] | 097b6406aa12d5ca0b825b00c936861b530cbf39 | https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/ask-sdk-webservice-support/ask_sdk_webservice_support/verifier.py#L260-L296 | train | 215,409 |
alexa/alexa-skills-kit-sdk-for-python | ask-sdk-webservice-support/ask_sdk_webservice_support/verifier.py | RequestVerifier._validate_cert_chain | def _validate_cert_chain(self, cert_chain):
# type: (Certificate) -> None
"""Validate the certificate chain.
This method checks if the passed in certificate chain is valid,
i.e it is not expired and the Alexa domain is present in the
SAN extensions of the certificate chain. A
:py:class:`VerificationException` is raised if the certificate
chain is not valid.
:param cert_chain: Certificate chain to be validated
:type cert_chain: cryptography.x509.Certificate
:return: None
:raises: :py:class:`VerificationException` if certificated is
not valid
"""
now = datetime.utcnow()
if not (cert_chain.not_valid_before <= now <=
cert_chain.not_valid_after):
raise VerificationException("Signing Certificate expired")
ext = cert_chain.extensions.get_extension_for_oid(
ExtensionOID.SUBJECT_ALTERNATIVE_NAME)
if CERT_CHAIN_DOMAIN not in ext.value.get_values_for_type(
DNSName):
raise VerificationException(
"{} domain missing in Signature Certificate Chain".format(
CERT_CHAIN_DOMAIN)) | python | def _validate_cert_chain(self, cert_chain):
# type: (Certificate) -> None
"""Validate the certificate chain.
This method checks if the passed in certificate chain is valid,
i.e it is not expired and the Alexa domain is present in the
SAN extensions of the certificate chain. A
:py:class:`VerificationException` is raised if the certificate
chain is not valid.
:param cert_chain: Certificate chain to be validated
:type cert_chain: cryptography.x509.Certificate
:return: None
:raises: :py:class:`VerificationException` if certificated is
not valid
"""
now = datetime.utcnow()
if not (cert_chain.not_valid_before <= now <=
cert_chain.not_valid_after):
raise VerificationException("Signing Certificate expired")
ext = cert_chain.extensions.get_extension_for_oid(
ExtensionOID.SUBJECT_ALTERNATIVE_NAME)
if CERT_CHAIN_DOMAIN not in ext.value.get_values_for_type(
DNSName):
raise VerificationException(
"{} domain missing in Signature Certificate Chain".format(
CERT_CHAIN_DOMAIN)) | [
"def",
"_validate_cert_chain",
"(",
"self",
",",
"cert_chain",
")",
":",
"# type: (Certificate) -> None",
"now",
"=",
"datetime",
".",
"utcnow",
"(",
")",
"if",
"not",
"(",
"cert_chain",
".",
"not_valid_before",
"<=",
"now",
"<=",
"cert_chain",
".",
"not_valid_a... | Validate the certificate chain.
This method checks if the passed in certificate chain is valid,
i.e it is not expired and the Alexa domain is present in the
SAN extensions of the certificate chain. A
:py:class:`VerificationException` is raised if the certificate
chain is not valid.
:param cert_chain: Certificate chain to be validated
:type cert_chain: cryptography.x509.Certificate
:return: None
:raises: :py:class:`VerificationException` if certificated is
not valid | [
"Validate",
"the",
"certificate",
"chain",
"."
] | 097b6406aa12d5ca0b825b00c936861b530cbf39 | https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/ask-sdk-webservice-support/ask_sdk_webservice_support/verifier.py#L298-L325 | train | 215,410 |
alexa/alexa-skills-kit-sdk-for-python | ask-sdk-webservice-support/ask_sdk_webservice_support/verifier.py | RequestVerifier._valid_request_body | def _valid_request_body(
self, cert_chain, signature, serialized_request_env):
# type: (Certificate, str, str) -> None
"""Validate the request body hash with signature.
This method checks if the hash value of the request body
matches with the hash value of the signature, decrypted using
certificate chain. A
:py:class:`VerificationException` is raised if there is a
mismatch.
:param cert_chain: Certificate chain to be validated
:type cert_chain: cryptography.x509.Certificate
:param signature: Encrypted signature of the request
:type: str
:param serialized_request_env: Raw request body
:type: str
:raises: :py:class:`VerificationException` if certificate is
not valid
"""
decoded_signature = base64.b64decode(signature)
public_key = cert_chain.public_key()
request_env_bytes = serialized_request_env.encode(CHARACTER_ENCODING)
try:
public_key.verify(
decoded_signature, request_env_bytes,
self._padding, self._hash_algorithm)
except InvalidSignature as e:
raise VerificationException("Request body is not valid", e) | python | def _valid_request_body(
self, cert_chain, signature, serialized_request_env):
# type: (Certificate, str, str) -> None
"""Validate the request body hash with signature.
This method checks if the hash value of the request body
matches with the hash value of the signature, decrypted using
certificate chain. A
:py:class:`VerificationException` is raised if there is a
mismatch.
:param cert_chain: Certificate chain to be validated
:type cert_chain: cryptography.x509.Certificate
:param signature: Encrypted signature of the request
:type: str
:param serialized_request_env: Raw request body
:type: str
:raises: :py:class:`VerificationException` if certificate is
not valid
"""
decoded_signature = base64.b64decode(signature)
public_key = cert_chain.public_key()
request_env_bytes = serialized_request_env.encode(CHARACTER_ENCODING)
try:
public_key.verify(
decoded_signature, request_env_bytes,
self._padding, self._hash_algorithm)
except InvalidSignature as e:
raise VerificationException("Request body is not valid", e) | [
"def",
"_valid_request_body",
"(",
"self",
",",
"cert_chain",
",",
"signature",
",",
"serialized_request_env",
")",
":",
"# type: (Certificate, str, str) -> None",
"decoded_signature",
"=",
"base64",
".",
"b64decode",
"(",
"signature",
")",
"public_key",
"=",
"cert_chai... | Validate the request body hash with signature.
This method checks if the hash value of the request body
matches with the hash value of the signature, decrypted using
certificate chain. A
:py:class:`VerificationException` is raised if there is a
mismatch.
:param cert_chain: Certificate chain to be validated
:type cert_chain: cryptography.x509.Certificate
:param signature: Encrypted signature of the request
:type: str
:param serialized_request_env: Raw request body
:type: str
:raises: :py:class:`VerificationException` if certificate is
not valid | [
"Validate",
"the",
"request",
"body",
"hash",
"with",
"signature",
"."
] | 097b6406aa12d5ca0b825b00c936861b530cbf39 | https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/ask-sdk-webservice-support/ask_sdk_webservice_support/verifier.py#L327-L356 | train | 215,411 |
alexa/alexa-skills-kit-sdk-for-python | ask-sdk-webservice-support/ask_sdk_webservice_support/verifier.py | TimestampVerifier.verify | def verify(
self, headers, serialized_request_env, deserialized_request_env):
# type: (Dict[str, Any], str, RequestEnvelope) -> None
"""Verify if the input request timestamp is in tolerated limits.
The verify method retrieves the request timestamp and check if
it falls in the limit set by the tolerance, by checking with
the current timestamp in UTC.
:param headers: headers of the input POST request
:type headers: Dict[str, Any]
:param serialized_request_env: raw request envelope in the
input POST request
:type serialized_request_env: str
:param deserialized_request_env: deserialized request envelope
instance of the input POST request
:type deserialized_request_env:
:py:class:`ask_sdk_model.request_envelope.RequestEnvelope`
:raises: :py:class:`VerificationException` if difference between
local timestamp and input request timestamp is more than
specific tolerance limit
"""
local_now = datetime.now(tz.tzutc())
request_timestamp = deserialized_request_env.request.timestamp
if (abs((local_now - request_timestamp).seconds) >
(self._tolerance_in_millis / 1000)):
raise VerificationException("Timestamp verification failed") | python | def verify(
self, headers, serialized_request_env, deserialized_request_env):
# type: (Dict[str, Any], str, RequestEnvelope) -> None
"""Verify if the input request timestamp is in tolerated limits.
The verify method retrieves the request timestamp and check if
it falls in the limit set by the tolerance, by checking with
the current timestamp in UTC.
:param headers: headers of the input POST request
:type headers: Dict[str, Any]
:param serialized_request_env: raw request envelope in the
input POST request
:type serialized_request_env: str
:param deserialized_request_env: deserialized request envelope
instance of the input POST request
:type deserialized_request_env:
:py:class:`ask_sdk_model.request_envelope.RequestEnvelope`
:raises: :py:class:`VerificationException` if difference between
local timestamp and input request timestamp is more than
specific tolerance limit
"""
local_now = datetime.now(tz.tzutc())
request_timestamp = deserialized_request_env.request.timestamp
if (abs((local_now - request_timestamp).seconds) >
(self._tolerance_in_millis / 1000)):
raise VerificationException("Timestamp verification failed") | [
"def",
"verify",
"(",
"self",
",",
"headers",
",",
"serialized_request_env",
",",
"deserialized_request_env",
")",
":",
"# type: (Dict[str, Any], str, RequestEnvelope) -> None",
"local_now",
"=",
"datetime",
".",
"now",
"(",
"tz",
".",
"tzutc",
"(",
")",
")",
"reque... | Verify if the input request timestamp is in tolerated limits.
The verify method retrieves the request timestamp and check if
it falls in the limit set by the tolerance, by checking with
the current timestamp in UTC.
:param headers: headers of the input POST request
:type headers: Dict[str, Any]
:param serialized_request_env: raw request envelope in the
input POST request
:type serialized_request_env: str
:param deserialized_request_env: deserialized request envelope
instance of the input POST request
:type deserialized_request_env:
:py:class:`ask_sdk_model.request_envelope.RequestEnvelope`
:raises: :py:class:`VerificationException` if difference between
local timestamp and input request timestamp is more than
specific tolerance limit | [
"Verify",
"if",
"the",
"input",
"request",
"timestamp",
"is",
"in",
"tolerated",
"limits",
"."
] | 097b6406aa12d5ca0b825b00c936861b530cbf39 | https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/ask-sdk-webservice-support/ask_sdk_webservice_support/verifier.py#L411-L437 | train | 215,412 |
mozilla/moz-sql-parser | moz_sql_parser/formatting.py | escape | def escape(identifier, ansi_quotes, should_quote):
"""
Escape identifiers.
ANSI uses single quotes, but many databases use back quotes.
"""
if not should_quote(identifier):
return identifier
quote = '"' if ansi_quotes else '`'
identifier = identifier.replace(quote, 2*quote)
return '{0}{1}{2}'.format(quote, identifier, quote) | python | def escape(identifier, ansi_quotes, should_quote):
"""
Escape identifiers.
ANSI uses single quotes, but many databases use back quotes.
"""
if not should_quote(identifier):
return identifier
quote = '"' if ansi_quotes else '`'
identifier = identifier.replace(quote, 2*quote)
return '{0}{1}{2}'.format(quote, identifier, quote) | [
"def",
"escape",
"(",
"identifier",
",",
"ansi_quotes",
",",
"should_quote",
")",
":",
"if",
"not",
"should_quote",
"(",
"identifier",
")",
":",
"return",
"identifier",
"quote",
"=",
"'\"'",
"if",
"ansi_quotes",
"else",
"'`'",
"identifier",
"=",
"identifier",
... | Escape identifiers.
ANSI uses single quotes, but many databases use back quotes. | [
"Escape",
"identifiers",
"."
] | 35fcc69b8f73b48e1fd48025cae1e174d57c3921 | https://github.com/mozilla/moz-sql-parser/blob/35fcc69b8f73b48e1fd48025cae1e174d57c3921/moz_sql_parser/formatting.py#L39-L51 | train | 215,413 |
mlouielu/twstock | twstock/analytics.py | Analytics.ma_bias_ratio | def ma_bias_ratio(self, day1, day2):
"""Calculate moving average bias ratio"""
data1 = self.moving_average(self.price, day1)
data2 = self.moving_average(self.price, day2)
result = [data1[-i] - data2[-i] for i in range(1, min(len(data1), len(data2)) + 1)]
return result[::-1] | python | def ma_bias_ratio(self, day1, day2):
"""Calculate moving average bias ratio"""
data1 = self.moving_average(self.price, day1)
data2 = self.moving_average(self.price, day2)
result = [data1[-i] - data2[-i] for i in range(1, min(len(data1), len(data2)) + 1)]
return result[::-1] | [
"def",
"ma_bias_ratio",
"(",
"self",
",",
"day1",
",",
"day2",
")",
":",
"data1",
"=",
"self",
".",
"moving_average",
"(",
"self",
".",
"price",
",",
"day1",
")",
"data2",
"=",
"self",
".",
"moving_average",
"(",
"self",
".",
"price",
",",
"day2",
")... | Calculate moving average bias ratio | [
"Calculate",
"moving",
"average",
"bias",
"ratio"
] | cddddcc084d2d00497d591ab3059e3205b755825 | https://github.com/mlouielu/twstock/blob/cddddcc084d2d00497d591ab3059e3205b755825/twstock/analytics.py#L24-L30 | train | 215,414 |
mlouielu/twstock | twstock/analytics.py | Analytics.ma_bias_ratio_pivot | def ma_bias_ratio_pivot(self, data, sample_size=5, position=False):
"""Calculate pivot point"""
sample = data[-sample_size:]
if position is True:
check_value = max(sample)
pre_check_value = max(sample) > 0
elif position is False:
check_value = min(sample)
pre_check_value = max(sample) < 0
return ((sample_size - sample.index(check_value) < 4 and
sample.index(check_value) != sample_size - 1 and pre_check_value),
sample_size - sample.index(check_value) - 1,
check_value) | python | def ma_bias_ratio_pivot(self, data, sample_size=5, position=False):
"""Calculate pivot point"""
sample = data[-sample_size:]
if position is True:
check_value = max(sample)
pre_check_value = max(sample) > 0
elif position is False:
check_value = min(sample)
pre_check_value = max(sample) < 0
return ((sample_size - sample.index(check_value) < 4 and
sample.index(check_value) != sample_size - 1 and pre_check_value),
sample_size - sample.index(check_value) - 1,
check_value) | [
"def",
"ma_bias_ratio_pivot",
"(",
"self",
",",
"data",
",",
"sample_size",
"=",
"5",
",",
"position",
"=",
"False",
")",
":",
"sample",
"=",
"data",
"[",
"-",
"sample_size",
":",
"]",
"if",
"position",
"is",
"True",
":",
"check_value",
"=",
"max",
"("... | Calculate pivot point | [
"Calculate",
"pivot",
"point"
] | cddddcc084d2d00497d591ab3059e3205b755825 | https://github.com/mlouielu/twstock/blob/cddddcc084d2d00497d591ab3059e3205b755825/twstock/analytics.py#L32-L46 | train | 215,415 |
mlouielu/twstock | twstock/stock.py | Stock.fetch | def fetch(self, year: int, month: int):
"""Fetch year month data"""
self.raw_data = [self.fetcher.fetch(year, month, self.sid)]
self.data = self.raw_data[0]['data']
return self.data | python | def fetch(self, year: int, month: int):
"""Fetch year month data"""
self.raw_data = [self.fetcher.fetch(year, month, self.sid)]
self.data = self.raw_data[0]['data']
return self.data | [
"def",
"fetch",
"(",
"self",
",",
"year",
":",
"int",
",",
"month",
":",
"int",
")",
":",
"self",
".",
"raw_data",
"=",
"[",
"self",
".",
"fetcher",
".",
"fetch",
"(",
"year",
",",
"month",
",",
"self",
".",
"sid",
")",
"]",
"self",
".",
"data"... | Fetch year month data | [
"Fetch",
"year",
"month",
"data"
] | cddddcc084d2d00497d591ab3059e3205b755825 | https://github.com/mlouielu/twstock/blob/cddddcc084d2d00497d591ab3059e3205b755825/twstock/stock.py#L151-L155 | train | 215,416 |
mlouielu/twstock | twstock/stock.py | Stock.fetch_from | def fetch_from(self, year: int, month: int):
"""Fetch data from year, month to current year month data"""
self.raw_data = []
self.data = []
today = datetime.datetime.today()
for year, month in self._month_year_iter(month, year, today.month, today.year):
self.raw_data.append(self.fetcher.fetch(year, month, self.sid))
self.data.extend(self.raw_data[-1]['data'])
return self.data | python | def fetch_from(self, year: int, month: int):
"""Fetch data from year, month to current year month data"""
self.raw_data = []
self.data = []
today = datetime.datetime.today()
for year, month in self._month_year_iter(month, year, today.month, today.year):
self.raw_data.append(self.fetcher.fetch(year, month, self.sid))
self.data.extend(self.raw_data[-1]['data'])
return self.data | [
"def",
"fetch_from",
"(",
"self",
",",
"year",
":",
"int",
",",
"month",
":",
"int",
")",
":",
"self",
".",
"raw_data",
"=",
"[",
"]",
"self",
".",
"data",
"=",
"[",
"]",
"today",
"=",
"datetime",
".",
"datetime",
".",
"today",
"(",
")",
"for",
... | Fetch data from year, month to current year month data | [
"Fetch",
"data",
"from",
"year",
"month",
"to",
"current",
"year",
"month",
"data"
] | cddddcc084d2d00497d591ab3059e3205b755825 | https://github.com/mlouielu/twstock/blob/cddddcc084d2d00497d591ab3059e3205b755825/twstock/stock.py#L157-L165 | train | 215,417 |
mlouielu/twstock | twstock/stock.py | Stock.fetch_31 | def fetch_31(self):
"""Fetch 31 days data"""
today = datetime.datetime.today()
before = today - datetime.timedelta(days=60)
self.fetch_from(before.year, before.month)
self.data = self.data[-31:]
return self.data | python | def fetch_31(self):
"""Fetch 31 days data"""
today = datetime.datetime.today()
before = today - datetime.timedelta(days=60)
self.fetch_from(before.year, before.month)
self.data = self.data[-31:]
return self.data | [
"def",
"fetch_31",
"(",
"self",
")",
":",
"today",
"=",
"datetime",
".",
"datetime",
".",
"today",
"(",
")",
"before",
"=",
"today",
"-",
"datetime",
".",
"timedelta",
"(",
"days",
"=",
"60",
")",
"self",
".",
"fetch_from",
"(",
"before",
".",
"year"... | Fetch 31 days data | [
"Fetch",
"31",
"days",
"data"
] | cddddcc084d2d00497d591ab3059e3205b755825 | https://github.com/mlouielu/twstock/blob/cddddcc084d2d00497d591ab3059e3205b755825/twstock/stock.py#L167-L173 | train | 215,418 |
hellock/icrawler | icrawler/utils/proxy_pool.py | Proxy.to_dict | def to_dict(self):
"""convert detailed proxy info into a dict
Returns:
dict: A dict with four keys: ``addr``, ``protocol``,
``weight`` and ``last_checked``
"""
return dict(
addr=self.addr,
protocol=self.protocol,
weight=self.weight,
last_checked=self.last_checked) | python | def to_dict(self):
"""convert detailed proxy info into a dict
Returns:
dict: A dict with four keys: ``addr``, ``protocol``,
``weight`` and ``last_checked``
"""
return dict(
addr=self.addr,
protocol=self.protocol,
weight=self.weight,
last_checked=self.last_checked) | [
"def",
"to_dict",
"(",
"self",
")",
":",
"return",
"dict",
"(",
"addr",
"=",
"self",
".",
"addr",
",",
"protocol",
"=",
"self",
".",
"protocol",
",",
"weight",
"=",
"self",
".",
"weight",
",",
"last_checked",
"=",
"self",
".",
"last_checked",
")"
] | convert detailed proxy info into a dict
Returns:
dict: A dict with four keys: ``addr``, ``protocol``,
``weight`` and ``last_checked`` | [
"convert",
"detailed",
"proxy",
"info",
"into",
"a",
"dict"
] | 38c925758fd3d3e568d3ecc993f77bc0acfa4788 | https://github.com/hellock/icrawler/blob/38c925758fd3d3e568d3ecc993f77bc0acfa4788/icrawler/utils/proxy_pool.py#L47-L58 | train | 215,419 |
hellock/icrawler | icrawler/utils/proxy_pool.py | ProxyPool.proxy_num | def proxy_num(self, protocol=None):
"""Get the number of proxies in the pool
Args:
protocol (str, optional): 'http' or 'https' or None. (default None)
Returns:
If protocol is None, return the total number of proxies, otherwise,
return the number of proxies of corresponding protocol.
"""
http_num = len(self.proxies['http'])
https_num = len(self.proxies['https'])
if protocol == 'http':
return http_num
elif protocol == 'https':
return https_num
else:
return http_num + https_num | python | def proxy_num(self, protocol=None):
"""Get the number of proxies in the pool
Args:
protocol (str, optional): 'http' or 'https' or None. (default None)
Returns:
If protocol is None, return the total number of proxies, otherwise,
return the number of proxies of corresponding protocol.
"""
http_num = len(self.proxies['http'])
https_num = len(self.proxies['https'])
if protocol == 'http':
return http_num
elif protocol == 'https':
return https_num
else:
return http_num + https_num | [
"def",
"proxy_num",
"(",
"self",
",",
"protocol",
"=",
"None",
")",
":",
"http_num",
"=",
"len",
"(",
"self",
".",
"proxies",
"[",
"'http'",
"]",
")",
"https_num",
"=",
"len",
"(",
"self",
".",
"proxies",
"[",
"'https'",
"]",
")",
"if",
"protocol",
... | Get the number of proxies in the pool
Args:
protocol (str, optional): 'http' or 'https' or None. (default None)
Returns:
If protocol is None, return the total number of proxies, otherwise,
return the number of proxies of corresponding protocol. | [
"Get",
"the",
"number",
"of",
"proxies",
"in",
"the",
"pool"
] | 38c925758fd3d3e568d3ecc993f77bc0acfa4788 | https://github.com/hellock/icrawler/blob/38c925758fd3d3e568d3ecc993f77bc0acfa4788/icrawler/utils/proxy_pool.py#L104-L121 | train | 215,420 |
hellock/icrawler | icrawler/utils/proxy_pool.py | ProxyPool.get_next | def get_next(self, protocol='http', format=False, policy='loop'):
"""Get the next proxy
Args:
protocol (str): 'http' or 'https'. (default 'http')
format (bool): Whether to format the proxy. (default False)
policy (str): Either 'loop' or 'random', indicating the policy of
getting the next proxy. If set to 'loop', will return proxies
in turn, otherwise will return a proxy randomly.
Returns:
Proxy or dict: If format is true, then return the formatted proxy
which is compatible with requests.Session parameters,
otherwise a Proxy object.
"""
if not self.proxies[protocol]:
return None
if policy == 'loop':
idx = self.idx[protocol]
self.idx[protocol] = (idx + 1) % len(self.proxies[protocol])
elif policy == 'random':
idx = random.randint(0, self.proxy_num(protocol) - 1)
else:
self.logger.error('Unsupported get_next policy: {}'.format(policy))
exit()
proxy = self.proxies[protocol][self.addr_list[protocol][idx]]
if proxy.weight < random.random():
return self.get_next(protocol, format, policy)
if format:
return proxy.format()
else:
return proxy | python | def get_next(self, protocol='http', format=False, policy='loop'):
"""Get the next proxy
Args:
protocol (str): 'http' or 'https'. (default 'http')
format (bool): Whether to format the proxy. (default False)
policy (str): Either 'loop' or 'random', indicating the policy of
getting the next proxy. If set to 'loop', will return proxies
in turn, otherwise will return a proxy randomly.
Returns:
Proxy or dict: If format is true, then return the formatted proxy
which is compatible with requests.Session parameters,
otherwise a Proxy object.
"""
if not self.proxies[protocol]:
return None
if policy == 'loop':
idx = self.idx[protocol]
self.idx[protocol] = (idx + 1) % len(self.proxies[protocol])
elif policy == 'random':
idx = random.randint(0, self.proxy_num(protocol) - 1)
else:
self.logger.error('Unsupported get_next policy: {}'.format(policy))
exit()
proxy = self.proxies[protocol][self.addr_list[protocol][idx]]
if proxy.weight < random.random():
return self.get_next(protocol, format, policy)
if format:
return proxy.format()
else:
return proxy | [
"def",
"get_next",
"(",
"self",
",",
"protocol",
"=",
"'http'",
",",
"format",
"=",
"False",
",",
"policy",
"=",
"'loop'",
")",
":",
"if",
"not",
"self",
".",
"proxies",
"[",
"protocol",
"]",
":",
"return",
"None",
"if",
"policy",
"==",
"'loop'",
":"... | Get the next proxy
Args:
protocol (str): 'http' or 'https'. (default 'http')
format (bool): Whether to format the proxy. (default False)
policy (str): Either 'loop' or 'random', indicating the policy of
getting the next proxy. If set to 'loop', will return proxies
in turn, otherwise will return a proxy randomly.
Returns:
Proxy or dict: If format is true, then return the formatted proxy
which is compatible with requests.Session parameters,
otherwise a Proxy object. | [
"Get",
"the",
"next",
"proxy"
] | 38c925758fd3d3e568d3ecc993f77bc0acfa4788 | https://github.com/hellock/icrawler/blob/38c925758fd3d3e568d3ecc993f77bc0acfa4788/icrawler/utils/proxy_pool.py#L123-L154 | train | 215,421 |
hellock/icrawler | icrawler/utils/proxy_pool.py | ProxyPool.save | def save(self, filename):
"""Save proxies to file"""
proxies = {'http': [], 'https': []}
for protocol in ['http', 'https']:
for proxy in self.proxies[protocol]:
serializable_proxy = self.proxies[protocol][proxy].to_dict()
proxies[protocol].append(serializable_proxy)
with open(filename, 'w') as fout:
json.dump(proxies, fout) | python | def save(self, filename):
"""Save proxies to file"""
proxies = {'http': [], 'https': []}
for protocol in ['http', 'https']:
for proxy in self.proxies[protocol]:
serializable_proxy = self.proxies[protocol][proxy].to_dict()
proxies[protocol].append(serializable_proxy)
with open(filename, 'w') as fout:
json.dump(proxies, fout) | [
"def",
"save",
"(",
"self",
",",
"filename",
")",
":",
"proxies",
"=",
"{",
"'http'",
":",
"[",
"]",
",",
"'https'",
":",
"[",
"]",
"}",
"for",
"protocol",
"in",
"[",
"'http'",
",",
"'https'",
"]",
":",
"for",
"proxy",
"in",
"self",
".",
"proxies... | Save proxies to file | [
"Save",
"proxies",
"to",
"file"
] | 38c925758fd3d3e568d3ecc993f77bc0acfa4788 | https://github.com/hellock/icrawler/blob/38c925758fd3d3e568d3ecc993f77bc0acfa4788/icrawler/utils/proxy_pool.py#L156-L164 | train | 215,422 |
hellock/icrawler | icrawler/utils/proxy_pool.py | ProxyPool.load | def load(self, filename):
"""Load proxies from file"""
with open(filename, 'r') as fin:
proxies = json.load(fin)
for protocol in proxies:
for proxy in proxies[protocol]:
self.proxies[protocol][proxy['addr']] = Proxy(
proxy['addr'], proxy['protocol'], proxy['weight'],
proxy['last_checked'])
self.addr_list[protocol].append(proxy['addr']) | python | def load(self, filename):
"""Load proxies from file"""
with open(filename, 'r') as fin:
proxies = json.load(fin)
for protocol in proxies:
for proxy in proxies[protocol]:
self.proxies[protocol][proxy['addr']] = Proxy(
proxy['addr'], proxy['protocol'], proxy['weight'],
proxy['last_checked'])
self.addr_list[protocol].append(proxy['addr']) | [
"def",
"load",
"(",
"self",
",",
"filename",
")",
":",
"with",
"open",
"(",
"filename",
",",
"'r'",
")",
"as",
"fin",
":",
"proxies",
"=",
"json",
".",
"load",
"(",
"fin",
")",
"for",
"protocol",
"in",
"proxies",
":",
"for",
"proxy",
"in",
"proxies... | Load proxies from file | [
"Load",
"proxies",
"from",
"file"
] | 38c925758fd3d3e568d3ecc993f77bc0acfa4788 | https://github.com/hellock/icrawler/blob/38c925758fd3d3e568d3ecc993f77bc0acfa4788/icrawler/utils/proxy_pool.py#L166-L175 | train | 215,423 |
hellock/icrawler | icrawler/utils/proxy_pool.py | ProxyPool.add_proxy | def add_proxy(self, proxy):
"""Add a valid proxy into pool
You must call `add_proxy` method to add a proxy into pool instead of
directly operate the `proxies` variable.
"""
protocol = proxy.protocol
addr = proxy.addr
if addr in self.proxies:
self.proxies[protocol][addr].last_checked = proxy.last_checked
else:
self.proxies[protocol][addr] = proxy
self.addr_list[protocol].append(addr) | python | def add_proxy(self, proxy):
"""Add a valid proxy into pool
You must call `add_proxy` method to add a proxy into pool instead of
directly operate the `proxies` variable.
"""
protocol = proxy.protocol
addr = proxy.addr
if addr in self.proxies:
self.proxies[protocol][addr].last_checked = proxy.last_checked
else:
self.proxies[protocol][addr] = proxy
self.addr_list[protocol].append(addr) | [
"def",
"add_proxy",
"(",
"self",
",",
"proxy",
")",
":",
"protocol",
"=",
"proxy",
".",
"protocol",
"addr",
"=",
"proxy",
".",
"addr",
"if",
"addr",
"in",
"self",
".",
"proxies",
":",
"self",
".",
"proxies",
"[",
"protocol",
"]",
"[",
"addr",
"]",
... | Add a valid proxy into pool
You must call `add_proxy` method to add a proxy into pool instead of
directly operate the `proxies` variable. | [
"Add",
"a",
"valid",
"proxy",
"into",
"pool"
] | 38c925758fd3d3e568d3ecc993f77bc0acfa4788 | https://github.com/hellock/icrawler/blob/38c925758fd3d3e568d3ecc993f77bc0acfa4788/icrawler/utils/proxy_pool.py#L177-L189 | train | 215,424 |
hellock/icrawler | icrawler/utils/proxy_pool.py | ProxyPool.remove_proxy | def remove_proxy(self, proxy):
"""Remove a proxy out of the pool"""
del self.search_flag[proxy.protocol][proxy.addr]
del self.addr_list[proxy.protocol][proxy.addr] | python | def remove_proxy(self, proxy):
"""Remove a proxy out of the pool"""
del self.search_flag[proxy.protocol][proxy.addr]
del self.addr_list[proxy.protocol][proxy.addr] | [
"def",
"remove_proxy",
"(",
"self",
",",
"proxy",
")",
":",
"del",
"self",
".",
"search_flag",
"[",
"proxy",
".",
"protocol",
"]",
"[",
"proxy",
".",
"addr",
"]",
"del",
"self",
".",
"addr_list",
"[",
"proxy",
".",
"protocol",
"]",
"[",
"proxy",
".",... | Remove a proxy out of the pool | [
"Remove",
"a",
"proxy",
"out",
"of",
"the",
"pool"
] | 38c925758fd3d3e568d3ecc993f77bc0acfa4788 | https://github.com/hellock/icrawler/blob/38c925758fd3d3e568d3ecc993f77bc0acfa4788/icrawler/utils/proxy_pool.py#L191-L194 | train | 215,425 |
hellock/icrawler | icrawler/utils/proxy_pool.py | ProxyPool.increase_weight | def increase_weight(self, proxy):
"""Increase the weight of a proxy by multiplying inc_ratio"""
new_weight = proxy.weight * self.inc_ratio
if new_weight < 1.0:
proxy.weight = new_weight
else:
proxy.weight = 1.0 | python | def increase_weight(self, proxy):
"""Increase the weight of a proxy by multiplying inc_ratio"""
new_weight = proxy.weight * self.inc_ratio
if new_weight < 1.0:
proxy.weight = new_weight
else:
proxy.weight = 1.0 | [
"def",
"increase_weight",
"(",
"self",
",",
"proxy",
")",
":",
"new_weight",
"=",
"proxy",
".",
"weight",
"*",
"self",
".",
"inc_ratio",
"if",
"new_weight",
"<",
"1.0",
":",
"proxy",
".",
"weight",
"=",
"new_weight",
"else",
":",
"proxy",
".",
"weight",
... | Increase the weight of a proxy by multiplying inc_ratio | [
"Increase",
"the",
"weight",
"of",
"a",
"proxy",
"by",
"multiplying",
"inc_ratio"
] | 38c925758fd3d3e568d3ecc993f77bc0acfa4788 | https://github.com/hellock/icrawler/blob/38c925758fd3d3e568d3ecc993f77bc0acfa4788/icrawler/utils/proxy_pool.py#L196-L202 | train | 215,426 |
hellock/icrawler | icrawler/utils/proxy_pool.py | ProxyPool.decrease_weight | def decrease_weight(self, proxy):
"""Decreasing the weight of a proxy by multiplying dec_ratio"""
new_weight = proxy.weight * self.dec_ratio
if new_weight < self.weight_thr:
self.remove_proxy(proxy)
else:
proxy.weight = new_weight | python | def decrease_weight(self, proxy):
"""Decreasing the weight of a proxy by multiplying dec_ratio"""
new_weight = proxy.weight * self.dec_ratio
if new_weight < self.weight_thr:
self.remove_proxy(proxy)
else:
proxy.weight = new_weight | [
"def",
"decrease_weight",
"(",
"self",
",",
"proxy",
")",
":",
"new_weight",
"=",
"proxy",
".",
"weight",
"*",
"self",
".",
"dec_ratio",
"if",
"new_weight",
"<",
"self",
".",
"weight_thr",
":",
"self",
".",
"remove_proxy",
"(",
"proxy",
")",
"else",
":",... | Decreasing the weight of a proxy by multiplying dec_ratio | [
"Decreasing",
"the",
"weight",
"of",
"a",
"proxy",
"by",
"multiplying",
"dec_ratio"
] | 38c925758fd3d3e568d3ecc993f77bc0acfa4788 | https://github.com/hellock/icrawler/blob/38c925758fd3d3e568d3ecc993f77bc0acfa4788/icrawler/utils/proxy_pool.py#L204-L210 | train | 215,427 |
hellock/icrawler | icrawler/utils/proxy_pool.py | ProxyPool.is_valid | def is_valid(self, addr, protocol='http', timeout=5):
"""Check if a proxy is valid
Args:
addr: A string in the form of 'ip:port'
protocol: Either 'http' or 'https', different test urls will be used
according to protocol.
timeout: A integer indicating the timeout of connecting the test url.
Returns:
dict: If the proxy is valid, returns {'valid': True, 'response_time': xx}
otherwise returns {'valid': False, 'msg': 'xxxxxx'}.
"""
start = time.time()
try:
r = requests.get(self.test_url[protocol],
timeout=timeout,
proxies={protocol: 'http://' + addr})
except KeyboardInterrupt:
raise
except requests.exceptions.Timeout:
return {'valid': False, 'msg': 'timeout'}
except:
return {'valid': False, 'msg': 'exception'}
else:
if r.status_code == 200:
response_time = time.time() - start
return {'valid': True, 'response_time': response_time}
else:
return {
'valid': False,
'msg': 'status code: {}'.format(r.status_code)
} | python | def is_valid(self, addr, protocol='http', timeout=5):
"""Check if a proxy is valid
Args:
addr: A string in the form of 'ip:port'
protocol: Either 'http' or 'https', different test urls will be used
according to protocol.
timeout: A integer indicating the timeout of connecting the test url.
Returns:
dict: If the proxy is valid, returns {'valid': True, 'response_time': xx}
otherwise returns {'valid': False, 'msg': 'xxxxxx'}.
"""
start = time.time()
try:
r = requests.get(self.test_url[protocol],
timeout=timeout,
proxies={protocol: 'http://' + addr})
except KeyboardInterrupt:
raise
except requests.exceptions.Timeout:
return {'valid': False, 'msg': 'timeout'}
except:
return {'valid': False, 'msg': 'exception'}
else:
if r.status_code == 200:
response_time = time.time() - start
return {'valid': True, 'response_time': response_time}
else:
return {
'valid': False,
'msg': 'status code: {}'.format(r.status_code)
} | [
"def",
"is_valid",
"(",
"self",
",",
"addr",
",",
"protocol",
"=",
"'http'",
",",
"timeout",
"=",
"5",
")",
":",
"start",
"=",
"time",
".",
"time",
"(",
")",
"try",
":",
"r",
"=",
"requests",
".",
"get",
"(",
"self",
".",
"test_url",
"[",
"protoc... | Check if a proxy is valid
Args:
addr: A string in the form of 'ip:port'
protocol: Either 'http' or 'https', different test urls will be used
according to protocol.
timeout: A integer indicating the timeout of connecting the test url.
Returns:
dict: If the proxy is valid, returns {'valid': True, 'response_time': xx}
otherwise returns {'valid': False, 'msg': 'xxxxxx'}. | [
"Check",
"if",
"a",
"proxy",
"is",
"valid"
] | 38c925758fd3d3e568d3ecc993f77bc0acfa4788 | https://github.com/hellock/icrawler/blob/38c925758fd3d3e568d3ecc993f77bc0acfa4788/icrawler/utils/proxy_pool.py#L212-L244 | train | 215,428 |
hellock/icrawler | icrawler/utils/proxy_pool.py | ProxyPool.validate | def validate(self,
proxy_scanner,
expected_num=20,
queue_timeout=3,
val_timeout=5):
"""Target function of validation threads
Args:
proxy_scanner: A ProxyScanner object.
expected_num: Max number of valid proxies to be scanned.
queue_timeout: Timeout for getting a proxy from the queue.
val_timeout: An integer passed to `is_valid` as argument `timeout`.
"""
while self.proxy_num() < expected_num:
try:
candidate_proxy = proxy_scanner.proxy_queue.get(
timeout=queue_timeout)
except queue.Empty:
if proxy_scanner.is_scanning():
continue
else:
break
addr = candidate_proxy['addr']
protocol = candidate_proxy['protocol']
ret = self.is_valid(addr, protocol, val_timeout)
if self.proxy_num() >= expected_num:
self.logger.info('Enough valid proxies, thread {} exit.'
.format(threading.current_thread().name))
break
if ret['valid']:
self.add_proxy(Proxy(addr, protocol))
self.logger.info('{} ok, {:.2f}s'.format(addr, ret[
'response_time']))
else:
self.logger.info('{} invalid, {}'.format(addr, ret['msg'])) | python | def validate(self,
proxy_scanner,
expected_num=20,
queue_timeout=3,
val_timeout=5):
"""Target function of validation threads
Args:
proxy_scanner: A ProxyScanner object.
expected_num: Max number of valid proxies to be scanned.
queue_timeout: Timeout for getting a proxy from the queue.
val_timeout: An integer passed to `is_valid` as argument `timeout`.
"""
while self.proxy_num() < expected_num:
try:
candidate_proxy = proxy_scanner.proxy_queue.get(
timeout=queue_timeout)
except queue.Empty:
if proxy_scanner.is_scanning():
continue
else:
break
addr = candidate_proxy['addr']
protocol = candidate_proxy['protocol']
ret = self.is_valid(addr, protocol, val_timeout)
if self.proxy_num() >= expected_num:
self.logger.info('Enough valid proxies, thread {} exit.'
.format(threading.current_thread().name))
break
if ret['valid']:
self.add_proxy(Proxy(addr, protocol))
self.logger.info('{} ok, {:.2f}s'.format(addr, ret[
'response_time']))
else:
self.logger.info('{} invalid, {}'.format(addr, ret['msg'])) | [
"def",
"validate",
"(",
"self",
",",
"proxy_scanner",
",",
"expected_num",
"=",
"20",
",",
"queue_timeout",
"=",
"3",
",",
"val_timeout",
"=",
"5",
")",
":",
"while",
"self",
".",
"proxy_num",
"(",
")",
"<",
"expected_num",
":",
"try",
":",
"candidate_pr... | Target function of validation threads
Args:
proxy_scanner: A ProxyScanner object.
expected_num: Max number of valid proxies to be scanned.
queue_timeout: Timeout for getting a proxy from the queue.
val_timeout: An integer passed to `is_valid` as argument `timeout`. | [
"Target",
"function",
"of",
"validation",
"threads"
] | 38c925758fd3d3e568d3ecc993f77bc0acfa4788 | https://github.com/hellock/icrawler/blob/38c925758fd3d3e568d3ecc993f77bc0acfa4788/icrawler/utils/proxy_pool.py#L246-L280 | train | 215,429 |
hellock/icrawler | icrawler/utils/proxy_pool.py | ProxyPool.scan | def scan(self,
proxy_scanner,
expected_num=20,
val_thr_num=4,
queue_timeout=3,
val_timeout=5,
out_file='proxies.json'):
"""Scan and validate proxies
Firstly, call the `scan` method of `proxy_scanner`, then using multiple
threads to validate them.
Args:
proxy_scanner: A ProxyScanner object.
expected_num: Max number of valid proxies to be scanned.
val_thr_num: Number of threads used for validating proxies.
queue_timeout: Timeout for getting a proxy from the queue.
val_timeout: An integer passed to `is_valid` as argument `timeout`.
out_file: A string or None. If not None, the proxies will be saved
into `out_file`.
"""
try:
proxy_scanner.scan()
self.logger.info('starting {} threads to validating proxies...'
.format(val_thr_num))
val_threads = []
for i in range(val_thr_num):
t = threading.Thread(
name='val-{:0>2d}'.format(i + 1),
target=self.validate,
kwargs=dict(
proxy_scanner=proxy_scanner,
expected_num=expected_num,
queue_timeout=queue_timeout,
val_timeout=val_timeout))
t.daemon = True
val_threads.append(t)
t.start()
for t in val_threads:
t.join()
self.logger.info('Proxy scanning done!')
except:
raise
finally:
if out_file is not None:
self.save(out_file) | python | def scan(self,
proxy_scanner,
expected_num=20,
val_thr_num=4,
queue_timeout=3,
val_timeout=5,
out_file='proxies.json'):
"""Scan and validate proxies
Firstly, call the `scan` method of `proxy_scanner`, then using multiple
threads to validate them.
Args:
proxy_scanner: A ProxyScanner object.
expected_num: Max number of valid proxies to be scanned.
val_thr_num: Number of threads used for validating proxies.
queue_timeout: Timeout for getting a proxy from the queue.
val_timeout: An integer passed to `is_valid` as argument `timeout`.
out_file: A string or None. If not None, the proxies will be saved
into `out_file`.
"""
try:
proxy_scanner.scan()
self.logger.info('starting {} threads to validating proxies...'
.format(val_thr_num))
val_threads = []
for i in range(val_thr_num):
t = threading.Thread(
name='val-{:0>2d}'.format(i + 1),
target=self.validate,
kwargs=dict(
proxy_scanner=proxy_scanner,
expected_num=expected_num,
queue_timeout=queue_timeout,
val_timeout=val_timeout))
t.daemon = True
val_threads.append(t)
t.start()
for t in val_threads:
t.join()
self.logger.info('Proxy scanning done!')
except:
raise
finally:
if out_file is not None:
self.save(out_file) | [
"def",
"scan",
"(",
"self",
",",
"proxy_scanner",
",",
"expected_num",
"=",
"20",
",",
"val_thr_num",
"=",
"4",
",",
"queue_timeout",
"=",
"3",
",",
"val_timeout",
"=",
"5",
",",
"out_file",
"=",
"'proxies.json'",
")",
":",
"try",
":",
"proxy_scanner",
"... | Scan and validate proxies
Firstly, call the `scan` method of `proxy_scanner`, then using multiple
threads to validate them.
Args:
proxy_scanner: A ProxyScanner object.
expected_num: Max number of valid proxies to be scanned.
val_thr_num: Number of threads used for validating proxies.
queue_timeout: Timeout for getting a proxy from the queue.
val_timeout: An integer passed to `is_valid` as argument `timeout`.
out_file: A string or None. If not None, the proxies will be saved
into `out_file`. | [
"Scan",
"and",
"validate",
"proxies"
] | 38c925758fd3d3e568d3ecc993f77bc0acfa4788 | https://github.com/hellock/icrawler/blob/38c925758fd3d3e568d3ecc993f77bc0acfa4788/icrawler/utils/proxy_pool.py#L282-L327 | train | 215,430 |
hellock/icrawler | icrawler/utils/proxy_pool.py | ProxyPool.default_scan | def default_scan(self,
region='mainland',
expected_num=20,
val_thr_num=4,
queue_timeout=3,
val_timeout=5,
out_file='proxies.json',
src_files=None):
"""Default scan method, to simplify the usage of `scan` method.
It will register following scan functions:
1. scan_file
2. scan_cnproxy (if region is mainland)
3. scan_free_proxy_list (if region is overseas)
4. scan_ip84
5. scan_mimiip
After scanning, all the proxy info will be saved in out_file.
Args:
region: Either 'mainland' or 'overseas'
expected_num: An integer indicating the expected number of proxies,
if this argument is set too great, it may take long to
finish scanning process.
val_thr_num: Number of threads used for validating proxies.
queue_timeout: An integer indicating the timeout for getting a
candidate proxy from the queue.
val_timeout: An integer indicating the timeout when connecting the
test url using a candidate proxy.
out_file: the file name of the output file saving all the proxy info
src_files: A list of file names to scan
"""
if expected_num > 30:
self.logger.warn('The more proxy you expect, the more time it '
'will take. It is highly recommended to limit the'
' expected num under 30.')
proxy_scanner = ProxyScanner()
if src_files is None:
src_files = []
elif isinstance(src_files, str):
src_files = [src_files]
for filename in src_files:
proxy_scanner.register_func(proxy_scanner.scan_file,
{'src_file': filename})
if region == 'mainland':
proxy_scanner.register_func(proxy_scanner.scan_cnproxy, {})
elif region == 'overseas':
proxy_scanner.register_func(proxy_scanner.scan_free_proxy_list, {})
proxy_scanner.register_func(proxy_scanner.scan_ip84,
{'region': region,
'page': 5})
proxy_scanner.register_func(proxy_scanner.scan_mimiip,
{'region': region,
'page': 5})
self.scan(proxy_scanner, expected_num, val_thr_num, queue_timeout,
val_timeout, out_file) | python | def default_scan(self,
region='mainland',
expected_num=20,
val_thr_num=4,
queue_timeout=3,
val_timeout=5,
out_file='proxies.json',
src_files=None):
"""Default scan method, to simplify the usage of `scan` method.
It will register following scan functions:
1. scan_file
2. scan_cnproxy (if region is mainland)
3. scan_free_proxy_list (if region is overseas)
4. scan_ip84
5. scan_mimiip
After scanning, all the proxy info will be saved in out_file.
Args:
region: Either 'mainland' or 'overseas'
expected_num: An integer indicating the expected number of proxies,
if this argument is set too great, it may take long to
finish scanning process.
val_thr_num: Number of threads used for validating proxies.
queue_timeout: An integer indicating the timeout for getting a
candidate proxy from the queue.
val_timeout: An integer indicating the timeout when connecting the
test url using a candidate proxy.
out_file: the file name of the output file saving all the proxy info
src_files: A list of file names to scan
"""
if expected_num > 30:
self.logger.warn('The more proxy you expect, the more time it '
'will take. It is highly recommended to limit the'
' expected num under 30.')
proxy_scanner = ProxyScanner()
if src_files is None:
src_files = []
elif isinstance(src_files, str):
src_files = [src_files]
for filename in src_files:
proxy_scanner.register_func(proxy_scanner.scan_file,
{'src_file': filename})
if region == 'mainland':
proxy_scanner.register_func(proxy_scanner.scan_cnproxy, {})
elif region == 'overseas':
proxy_scanner.register_func(proxy_scanner.scan_free_proxy_list, {})
proxy_scanner.register_func(proxy_scanner.scan_ip84,
{'region': region,
'page': 5})
proxy_scanner.register_func(proxy_scanner.scan_mimiip,
{'region': region,
'page': 5})
self.scan(proxy_scanner, expected_num, val_thr_num, queue_timeout,
val_timeout, out_file) | [
"def",
"default_scan",
"(",
"self",
",",
"region",
"=",
"'mainland'",
",",
"expected_num",
"=",
"20",
",",
"val_thr_num",
"=",
"4",
",",
"queue_timeout",
"=",
"3",
",",
"val_timeout",
"=",
"5",
",",
"out_file",
"=",
"'proxies.json'",
",",
"src_files",
"=",... | Default scan method, to simplify the usage of `scan` method.
It will register following scan functions:
1. scan_file
2. scan_cnproxy (if region is mainland)
3. scan_free_proxy_list (if region is overseas)
4. scan_ip84
5. scan_mimiip
After scanning, all the proxy info will be saved in out_file.
Args:
region: Either 'mainland' or 'overseas'
expected_num: An integer indicating the expected number of proxies,
if this argument is set too great, it may take long to
finish scanning process.
val_thr_num: Number of threads used for validating proxies.
queue_timeout: An integer indicating the timeout for getting a
candidate proxy from the queue.
val_timeout: An integer indicating the timeout when connecting the
test url using a candidate proxy.
out_file: the file name of the output file saving all the proxy info
src_files: A list of file names to scan | [
"Default",
"scan",
"method",
"to",
"simplify",
"the",
"usage",
"of",
"scan",
"method",
"."
] | 38c925758fd3d3e568d3ecc993f77bc0acfa4788 | https://github.com/hellock/icrawler/blob/38c925758fd3d3e568d3ecc993f77bc0acfa4788/icrawler/utils/proxy_pool.py#L329-L383 | train | 215,431 |
hellock/icrawler | icrawler/utils/proxy_pool.py | ProxyScanner.register_func | def register_func(self, func_name, func_kwargs):
"""Register a scan function
Args:
func_name: The function name of a scan function.
func_kwargs: A dict containing arguments of the scan function.
"""
self.scan_funcs.append(func_name)
self.scan_kwargs.append(func_kwargs) | python | def register_func(self, func_name, func_kwargs):
"""Register a scan function
Args:
func_name: The function name of a scan function.
func_kwargs: A dict containing arguments of the scan function.
"""
self.scan_funcs.append(func_name)
self.scan_kwargs.append(func_kwargs) | [
"def",
"register_func",
"(",
"self",
",",
"func_name",
",",
"func_kwargs",
")",
":",
"self",
".",
"scan_funcs",
".",
"append",
"(",
"func_name",
")",
"self",
".",
"scan_kwargs",
".",
"append",
"(",
"func_kwargs",
")"
] | Register a scan function
Args:
func_name: The function name of a scan function.
func_kwargs: A dict containing arguments of the scan function. | [
"Register",
"a",
"scan",
"function"
] | 38c925758fd3d3e568d3ecc993f77bc0acfa4788 | https://github.com/hellock/icrawler/blob/38c925758fd3d3e568d3ecc993f77bc0acfa4788/icrawler/utils/proxy_pool.py#L406-L414 | train | 215,432 |
hellock/icrawler | icrawler/utils/proxy_pool.py | ProxyScanner.scan_file | def scan_file(self, src_file):
"""Scan candidate proxies from an existing file"""
self.logger.info('start scanning file {} for proxy list...'
.format(src_file))
with open(src_file, 'r') as fin:
proxies = json.load(fin)
for protocol in proxies.keys():
for proxy in proxies[protocol]:
self.proxy_queue.put({
'addr': proxy['addr'],
'protocol': protocol
}) | python | def scan_file(self, src_file):
"""Scan candidate proxies from an existing file"""
self.logger.info('start scanning file {} for proxy list...'
.format(src_file))
with open(src_file, 'r') as fin:
proxies = json.load(fin)
for protocol in proxies.keys():
for proxy in proxies[protocol]:
self.proxy_queue.put({
'addr': proxy['addr'],
'protocol': protocol
}) | [
"def",
"scan_file",
"(",
"self",
",",
"src_file",
")",
":",
"self",
".",
"logger",
".",
"info",
"(",
"'start scanning file {} for proxy list...'",
".",
"format",
"(",
"src_file",
")",
")",
"with",
"open",
"(",
"src_file",
",",
"'r'",
")",
"as",
"fin",
":",... | Scan candidate proxies from an existing file | [
"Scan",
"candidate",
"proxies",
"from",
"an",
"existing",
"file"
] | 38c925758fd3d3e568d3ecc993f77bc0acfa4788 | https://github.com/hellock/icrawler/blob/38c925758fd3d3e568d3ecc993f77bc0acfa4788/icrawler/utils/proxy_pool.py#L499-L510 | train | 215,433 |
hellock/icrawler | icrawler/utils/proxy_pool.py | ProxyScanner.scan | def scan(self):
"""Start a thread for each registered scan function to scan proxy lists"""
self.logger.info('{0} registered scan functions, starting {0} threads '
'to scan candidate proxy lists...'
.format(len(self.scan_funcs)))
for i in range(len(self.scan_funcs)):
t = threading.Thread(
name=self.scan_funcs[i].__name__,
target=self.scan_funcs[i],
kwargs=self.scan_kwargs[i])
t.daemon = True
self.scan_threads.append(t)
t.start() | python | def scan(self):
"""Start a thread for each registered scan function to scan proxy lists"""
self.logger.info('{0} registered scan functions, starting {0} threads '
'to scan candidate proxy lists...'
.format(len(self.scan_funcs)))
for i in range(len(self.scan_funcs)):
t = threading.Thread(
name=self.scan_funcs[i].__name__,
target=self.scan_funcs[i],
kwargs=self.scan_kwargs[i])
t.daemon = True
self.scan_threads.append(t)
t.start() | [
"def",
"scan",
"(",
"self",
")",
":",
"self",
".",
"logger",
".",
"info",
"(",
"'{0} registered scan functions, starting {0} threads '",
"'to scan candidate proxy lists...'",
".",
"format",
"(",
"len",
"(",
"self",
".",
"scan_funcs",
")",
")",
")",
"for",
"i",
"... | Start a thread for each registered scan function to scan proxy lists | [
"Start",
"a",
"thread",
"for",
"each",
"registered",
"scan",
"function",
"to",
"scan",
"proxy",
"lists"
] | 38c925758fd3d3e568d3ecc993f77bc0acfa4788 | https://github.com/hellock/icrawler/blob/38c925758fd3d3e568d3ecc993f77bc0acfa4788/icrawler/utils/proxy_pool.py#L519-L531 | train | 215,434 |
hellock/icrawler | icrawler/utils/cached_queue.py | CachedQueue.is_duplicated | def is_duplicated(self, item):
"""Check whether the item has been in the cache
If the item has not been seen before, then hash it and put it into
the cache, otherwise indicates the item is duplicated. When the cache
size exceeds capacity, discard the earliest items in the cache.
Args:
item (object): The item to be checked and stored in cache. It must
be immutable or a list/dict.
Returns:
bool: Whether the item has been in cache.
"""
if isinstance(item, dict):
hashable_item = json.dumps(item, sort_keys=True)
elif isinstance(item, list):
hashable_item = frozenset(item)
else:
hashable_item = item
if hashable_item in self._cache:
return True
else:
if self.cache_capacity > 0 and len(
self._cache) >= self.cache_capacity:
self._cache.popitem(False)
self._cache[hashable_item] = 1
return False | python | def is_duplicated(self, item):
"""Check whether the item has been in the cache
If the item has not been seen before, then hash it and put it into
the cache, otherwise indicates the item is duplicated. When the cache
size exceeds capacity, discard the earliest items in the cache.
Args:
item (object): The item to be checked and stored in cache. It must
be immutable or a list/dict.
Returns:
bool: Whether the item has been in cache.
"""
if isinstance(item, dict):
hashable_item = json.dumps(item, sort_keys=True)
elif isinstance(item, list):
hashable_item = frozenset(item)
else:
hashable_item = item
if hashable_item in self._cache:
return True
else:
if self.cache_capacity > 0 and len(
self._cache) >= self.cache_capacity:
self._cache.popitem(False)
self._cache[hashable_item] = 1
return False | [
"def",
"is_duplicated",
"(",
"self",
",",
"item",
")",
":",
"if",
"isinstance",
"(",
"item",
",",
"dict",
")",
":",
"hashable_item",
"=",
"json",
".",
"dumps",
"(",
"item",
",",
"sort_keys",
"=",
"True",
")",
"elif",
"isinstance",
"(",
"item",
",",
"... | Check whether the item has been in the cache
If the item has not been seen before, then hash it and put it into
the cache, otherwise indicates the item is duplicated. When the cache
size exceeds capacity, discard the earliest items in the cache.
Args:
item (object): The item to be checked and stored in cache. It must
be immutable or a list/dict.
Returns:
bool: Whether the item has been in cache. | [
"Check",
"whether",
"the",
"item",
"has",
"been",
"in",
"the",
"cache"
] | 38c925758fd3d3e568d3ecc993f77bc0acfa4788 | https://github.com/hellock/icrawler/blob/38c925758fd3d3e568d3ecc993f77bc0acfa4788/icrawler/utils/cached_queue.py#L27-L53 | train | 215,435 |
hellock/icrawler | icrawler/utils/cached_queue.py | CachedQueue.put | def put(self, item, block=True, timeout=None, dup_callback=None):
"""Put an item to queue if it is not duplicated.
"""
if not self.is_duplicated(item):
super(CachedQueue, self).put(item, block, timeout)
else:
if dup_callback:
dup_callback(item) | python | def put(self, item, block=True, timeout=None, dup_callback=None):
"""Put an item to queue if it is not duplicated.
"""
if not self.is_duplicated(item):
super(CachedQueue, self).put(item, block, timeout)
else:
if dup_callback:
dup_callback(item) | [
"def",
"put",
"(",
"self",
",",
"item",
",",
"block",
"=",
"True",
",",
"timeout",
"=",
"None",
",",
"dup_callback",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"is_duplicated",
"(",
"item",
")",
":",
"super",
"(",
"CachedQueue",
",",
"self",
... | Put an item to queue if it is not duplicated. | [
"Put",
"an",
"item",
"to",
"queue",
"if",
"it",
"is",
"not",
"duplicated",
"."
] | 38c925758fd3d3e568d3ecc993f77bc0acfa4788 | https://github.com/hellock/icrawler/blob/38c925758fd3d3e568d3ecc993f77bc0acfa4788/icrawler/utils/cached_queue.py#L55-L62 | train | 215,436 |
hellock/icrawler | icrawler/utils/signal.py | Signal.set | def set(self, **signals):
"""Set signals.
Args:
signals: A dict(key-value pairs) of all signals. For example
{'signal1': True, 'signal2': 10}
"""
for name in signals:
if name not in self._signals:
self._init_status[name] = signals[name]
self._signals[name] = signals[name] | python | def set(self, **signals):
"""Set signals.
Args:
signals: A dict(key-value pairs) of all signals. For example
{'signal1': True, 'signal2': 10}
"""
for name in signals:
if name not in self._signals:
self._init_status[name] = signals[name]
self._signals[name] = signals[name] | [
"def",
"set",
"(",
"self",
",",
"*",
"*",
"signals",
")",
":",
"for",
"name",
"in",
"signals",
":",
"if",
"name",
"not",
"in",
"self",
".",
"_signals",
":",
"self",
".",
"_init_status",
"[",
"name",
"]",
"=",
"signals",
"[",
"name",
"]",
"self",
... | Set signals.
Args:
signals: A dict(key-value pairs) of all signals. For example
{'signal1': True, 'signal2': 10} | [
"Set",
"signals",
"."
] | 38c925758fd3d3e568d3ecc993f77bc0acfa4788 | https://github.com/hellock/icrawler/blob/38c925758fd3d3e568d3ecc993f77bc0acfa4788/icrawler/utils/signal.py#L19-L29 | train | 215,437 |
hellock/icrawler | icrawler/feeder.py | Feeder.worker_exec | def worker_exec(self, **kwargs):
"""Target function of workers"""
self.feed(**kwargs)
self.logger.info('thread {} exit'.format(current_thread().name)) | python | def worker_exec(self, **kwargs):
"""Target function of workers"""
self.feed(**kwargs)
self.logger.info('thread {} exit'.format(current_thread().name)) | [
"def",
"worker_exec",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"feed",
"(",
"*",
"*",
"kwargs",
")",
"self",
".",
"logger",
".",
"info",
"(",
"'thread {} exit'",
".",
"format",
"(",
"current_thread",
"(",
")",
".",
"name",
")",
... | Target function of workers | [
"Target",
"function",
"of",
"workers"
] | 38c925758fd3d3e568d3ecc993f77bc0acfa4788 | https://github.com/hellock/icrawler/blob/38c925758fd3d3e568d3ecc993f77bc0acfa4788/icrawler/feeder.py#L41-L44 | train | 215,438 |
hellock/icrawler | icrawler/feeder.py | SimpleSEFeeder.feed | def feed(self, url_template, keyword, offset, max_num, page_step):
"""Feed urls once
Args:
url_template: A string with parameters replaced with "{}".
keyword: A string indicating the searching keyword.
offset: An integer indicating the starting index.
max_num: An integer indicating the max number of images to be crawled.
page_step: An integer added to offset after each iteration.
"""
for i in range(offset, offset + max_num, page_step):
url = url_template.format(keyword, i)
self.out_queue.put(url)
self.logger.debug('put url to url_queue: {}'.format(url)) | python | def feed(self, url_template, keyword, offset, max_num, page_step):
"""Feed urls once
Args:
url_template: A string with parameters replaced with "{}".
keyword: A string indicating the searching keyword.
offset: An integer indicating the starting index.
max_num: An integer indicating the max number of images to be crawled.
page_step: An integer added to offset after each iteration.
"""
for i in range(offset, offset + max_num, page_step):
url = url_template.format(keyword, i)
self.out_queue.put(url)
self.logger.debug('put url to url_queue: {}'.format(url)) | [
"def",
"feed",
"(",
"self",
",",
"url_template",
",",
"keyword",
",",
"offset",
",",
"max_num",
",",
"page_step",
")",
":",
"for",
"i",
"in",
"range",
"(",
"offset",
",",
"offset",
"+",
"max_num",
",",
"page_step",
")",
":",
"url",
"=",
"url_template",... | Feed urls once
Args:
url_template: A string with parameters replaced with "{}".
keyword: A string indicating the searching keyword.
offset: An integer indicating the starting index.
max_num: An integer indicating the max number of images to be crawled.
page_step: An integer added to offset after each iteration. | [
"Feed",
"urls",
"once"
] | 38c925758fd3d3e568d3ecc993f77bc0acfa4788 | https://github.com/hellock/icrawler/blob/38c925758fd3d3e568d3ecc993f77bc0acfa4788/icrawler/feeder.py#L79-L92 | train | 215,439 |
hellock/icrawler | icrawler/utils/thread_pool.py | ThreadPool.connect | def connect(self, component):
"""Connect two ThreadPools.
The ``in_queue`` of the second pool will be set as the ``out_queue`` of
the current pool, thus all the output will be input to the second pool.
Args:
component (ThreadPool): the ThreadPool to be connected.
Returns:
ThreadPool: the modified second ThreadPool.
"""
if not isinstance(component, ThreadPool):
raise TypeError('"component" must be a ThreadPool object')
component.in_queue = self.out_queue
return component | python | def connect(self, component):
"""Connect two ThreadPools.
The ``in_queue`` of the second pool will be set as the ``out_queue`` of
the current pool, thus all the output will be input to the second pool.
Args:
component (ThreadPool): the ThreadPool to be connected.
Returns:
ThreadPool: the modified second ThreadPool.
"""
if not isinstance(component, ThreadPool):
raise TypeError('"component" must be a ThreadPool object')
component.in_queue = self.out_queue
return component | [
"def",
"connect",
"(",
"self",
",",
"component",
")",
":",
"if",
"not",
"isinstance",
"(",
"component",
",",
"ThreadPool",
")",
":",
"raise",
"TypeError",
"(",
"'\"component\" must be a ThreadPool object'",
")",
"component",
".",
"in_queue",
"=",
"self",
".",
... | Connect two ThreadPools.
The ``in_queue`` of the second pool will be set as the ``out_queue`` of
the current pool, thus all the output will be input to the second pool.
Args:
component (ThreadPool): the ThreadPool to be connected.
Returns:
ThreadPool: the modified second ThreadPool. | [
"Connect",
"two",
"ThreadPools",
"."
] | 38c925758fd3d3e568d3ecc993f77bc0acfa4788 | https://github.com/hellock/icrawler/blob/38c925758fd3d3e568d3ecc993f77bc0acfa4788/icrawler/utils/thread_pool.py#L85-L99 | train | 215,440 |
hellock/icrawler | icrawler/downloader.py | Downloader.set_file_idx_offset | def set_file_idx_offset(self, file_idx_offset=0):
"""Set offset of file index.
Args:
file_idx_offset: It can be either an integer or 'auto'. If set
to an integer, the filename will start from
``file_idx_offset`` + 1. If set to ``'auto'``, the filename
will start from existing max file index plus 1.
"""
if isinstance(file_idx_offset, int):
self.file_idx_offset = file_idx_offset
elif file_idx_offset == 'auto':
self.file_idx_offset = self.storage.max_file_idx()
else:
raise ValueError('"file_idx_offset" must be an integer or `auto`') | python | def set_file_idx_offset(self, file_idx_offset=0):
"""Set offset of file index.
Args:
file_idx_offset: It can be either an integer or 'auto'. If set
to an integer, the filename will start from
``file_idx_offset`` + 1. If set to ``'auto'``, the filename
will start from existing max file index plus 1.
"""
if isinstance(file_idx_offset, int):
self.file_idx_offset = file_idx_offset
elif file_idx_offset == 'auto':
self.file_idx_offset = self.storage.max_file_idx()
else:
raise ValueError('"file_idx_offset" must be an integer or `auto`') | [
"def",
"set_file_idx_offset",
"(",
"self",
",",
"file_idx_offset",
"=",
"0",
")",
":",
"if",
"isinstance",
"(",
"file_idx_offset",
",",
"int",
")",
":",
"self",
".",
"file_idx_offset",
"=",
"file_idx_offset",
"elif",
"file_idx_offset",
"==",
"'auto'",
":",
"se... | Set offset of file index.
Args:
file_idx_offset: It can be either an integer or 'auto'. If set
to an integer, the filename will start from
``file_idx_offset`` + 1. If set to ``'auto'``, the filename
will start from existing max file index plus 1. | [
"Set",
"offset",
"of",
"file",
"index",
"."
] | 38c925758fd3d3e568d3ecc993f77bc0acfa4788 | https://github.com/hellock/icrawler/blob/38c925758fd3d3e568d3ecc993f77bc0acfa4788/icrawler/downloader.py#L45-L59 | train | 215,441 |
hellock/icrawler | icrawler/downloader.py | Downloader.get_filename | def get_filename(self, task, default_ext):
"""Set the path where the image will be saved.
The default strategy is to use an increasing 6-digit number as
the filename. You can override this method if you want to set custom
naming rules. The file extension is kept if it can be obtained from
the url, otherwise ``default_ext`` is used as extension.
Args:
task (dict): The task dict got from ``task_queue``.
Output:
Filename with extension.
"""
url_path = urlparse(task['file_url'])[2]
extension = url_path.split('.')[-1] if '.' in url_path else default_ext
file_idx = self.fetched_num + self.file_idx_offset
return '{:06d}.{}'.format(file_idx, extension) | python | def get_filename(self, task, default_ext):
"""Set the path where the image will be saved.
The default strategy is to use an increasing 6-digit number as
the filename. You can override this method if you want to set custom
naming rules. The file extension is kept if it can be obtained from
the url, otherwise ``default_ext`` is used as extension.
Args:
task (dict): The task dict got from ``task_queue``.
Output:
Filename with extension.
"""
url_path = urlparse(task['file_url'])[2]
extension = url_path.split('.')[-1] if '.' in url_path else default_ext
file_idx = self.fetched_num + self.file_idx_offset
return '{:06d}.{}'.format(file_idx, extension) | [
"def",
"get_filename",
"(",
"self",
",",
"task",
",",
"default_ext",
")",
":",
"url_path",
"=",
"urlparse",
"(",
"task",
"[",
"'file_url'",
"]",
")",
"[",
"2",
"]",
"extension",
"=",
"url_path",
".",
"split",
"(",
"'.'",
")",
"[",
"-",
"1",
"]",
"i... | Set the path where the image will be saved.
The default strategy is to use an increasing 6-digit number as
the filename. You can override this method if you want to set custom
naming rules. The file extension is kept if it can be obtained from
the url, otherwise ``default_ext`` is used as extension.
Args:
task (dict): The task dict got from ``task_queue``.
Output:
Filename with extension. | [
"Set",
"the",
"path",
"where",
"the",
"image",
"will",
"be",
"saved",
"."
] | 38c925758fd3d3e568d3ecc993f77bc0acfa4788 | https://github.com/hellock/icrawler/blob/38c925758fd3d3e568d3ecc993f77bc0acfa4788/icrawler/downloader.py#L61-L78 | train | 215,442 |
hellock/icrawler | icrawler/downloader.py | Downloader.reach_max_num | def reach_max_num(self):
"""Check if downloaded images reached max num.
Returns:
bool: if downloaded images reached max num.
"""
if self.signal.get('reach_max_num'):
return True
if self.max_num > 0 and self.fetched_num >= self.max_num:
return True
else:
return False | python | def reach_max_num(self):
"""Check if downloaded images reached max num.
Returns:
bool: if downloaded images reached max num.
"""
if self.signal.get('reach_max_num'):
return True
if self.max_num > 0 and self.fetched_num >= self.max_num:
return True
else:
return False | [
"def",
"reach_max_num",
"(",
"self",
")",
":",
"if",
"self",
".",
"signal",
".",
"get",
"(",
"'reach_max_num'",
")",
":",
"return",
"True",
"if",
"self",
".",
"max_num",
">",
"0",
"and",
"self",
".",
"fetched_num",
">=",
"self",
".",
"max_num",
":",
... | Check if downloaded images reached max num.
Returns:
bool: if downloaded images reached max num. | [
"Check",
"if",
"downloaded",
"images",
"reached",
"max",
"num",
"."
] | 38c925758fd3d3e568d3ecc993f77bc0acfa4788 | https://github.com/hellock/icrawler/blob/38c925758fd3d3e568d3ecc993f77bc0acfa4788/icrawler/downloader.py#L80-L91 | train | 215,443 |
hellock/icrawler | icrawler/downloader.py | Downloader.download | def download(self,
task,
default_ext,
timeout=5,
max_retry=3,
overwrite=False,
**kwargs):
"""Download the image and save it to the corresponding path.
Args:
task (dict): The task dict got from ``task_queue``.
timeout (int): Timeout of making requests for downloading images.
max_retry (int): the max retry times if the request fails.
**kwargs: reserved arguments for overriding.
"""
file_url = task['file_url']
task['success'] = False
task['filename'] = None
retry = max_retry
if not overwrite:
with self.lock:
self.fetched_num += 1
filename = self.get_filename(task, default_ext)
if self.storage.exists(filename):
self.logger.info('skip downloading file %s', filename)
return
self.fetched_num -= 1
while retry > 0 and not self.signal.get('reach_max_num'):
try:
response = self.session.get(file_url, timeout=timeout)
except Exception as e:
self.logger.error('Exception caught when downloading file %s, '
'error: %s, remaining retry times: %d',
file_url, e, retry - 1)
else:
if self.reach_max_num():
self.signal.set(reach_max_num=True)
break
elif response.status_code != 200:
self.logger.error('Response status code %d, file %s',
response.status_code, file_url)
break
elif not self.keep_file(task, response, **kwargs):
break
with self.lock:
self.fetched_num += 1
filename = self.get_filename(task, default_ext)
self.logger.info('image #%s\t%s', self.fetched_num, file_url)
self.storage.write(filename, response.content)
task['success'] = True
task['filename'] = filename
break
finally:
retry -= 1 | python | def download(self,
task,
default_ext,
timeout=5,
max_retry=3,
overwrite=False,
**kwargs):
"""Download the image and save it to the corresponding path.
Args:
task (dict): The task dict got from ``task_queue``.
timeout (int): Timeout of making requests for downloading images.
max_retry (int): the max retry times if the request fails.
**kwargs: reserved arguments for overriding.
"""
file_url = task['file_url']
task['success'] = False
task['filename'] = None
retry = max_retry
if not overwrite:
with self.lock:
self.fetched_num += 1
filename = self.get_filename(task, default_ext)
if self.storage.exists(filename):
self.logger.info('skip downloading file %s', filename)
return
self.fetched_num -= 1
while retry > 0 and not self.signal.get('reach_max_num'):
try:
response = self.session.get(file_url, timeout=timeout)
except Exception as e:
self.logger.error('Exception caught when downloading file %s, '
'error: %s, remaining retry times: %d',
file_url, e, retry - 1)
else:
if self.reach_max_num():
self.signal.set(reach_max_num=True)
break
elif response.status_code != 200:
self.logger.error('Response status code %d, file %s',
response.status_code, file_url)
break
elif not self.keep_file(task, response, **kwargs):
break
with self.lock:
self.fetched_num += 1
filename = self.get_filename(task, default_ext)
self.logger.info('image #%s\t%s', self.fetched_num, file_url)
self.storage.write(filename, response.content)
task['success'] = True
task['filename'] = filename
break
finally:
retry -= 1 | [
"def",
"download",
"(",
"self",
",",
"task",
",",
"default_ext",
",",
"timeout",
"=",
"5",
",",
"max_retry",
"=",
"3",
",",
"overwrite",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"file_url",
"=",
"task",
"[",
"'file_url'",
"]",
"task",
"[",
... | Download the image and save it to the corresponding path.
Args:
task (dict): The task dict got from ``task_queue``.
timeout (int): Timeout of making requests for downloading images.
max_retry (int): the max retry times if the request fails.
**kwargs: reserved arguments for overriding. | [
"Download",
"the",
"image",
"and",
"save",
"it",
"to",
"the",
"corresponding",
"path",
"."
] | 38c925758fd3d3e568d3ecc993f77bc0acfa4788 | https://github.com/hellock/icrawler/blob/38c925758fd3d3e568d3ecc993f77bc0acfa4788/icrawler/downloader.py#L96-L151 | train | 215,444 |
hellock/icrawler | icrawler/downloader.py | ImageDownloader.keep_file | def keep_file(self, task, response, min_size=None, max_size=None):
"""Decide whether to keep the image
Compare image size with ``min_size`` and ``max_size`` to decide.
Args:
response (Response): response of requests.
min_size (tuple or None): minimum size of required images.
max_size (tuple or None): maximum size of required images.
Returns:
bool: whether to keep the image.
"""
try:
img = Image.open(BytesIO(response.content))
except (IOError, OSError):
return False
task['img_size'] = img.size
if min_size and not self._size_gt(img.size, min_size):
return False
if max_size and not self._size_lt(img.size, max_size):
return False
return True | python | def keep_file(self, task, response, min_size=None, max_size=None):
"""Decide whether to keep the image
Compare image size with ``min_size`` and ``max_size`` to decide.
Args:
response (Response): response of requests.
min_size (tuple or None): minimum size of required images.
max_size (tuple or None): maximum size of required images.
Returns:
bool: whether to keep the image.
"""
try:
img = Image.open(BytesIO(response.content))
except (IOError, OSError):
return False
task['img_size'] = img.size
if min_size and not self._size_gt(img.size, min_size):
return False
if max_size and not self._size_lt(img.size, max_size):
return False
return True | [
"def",
"keep_file",
"(",
"self",
",",
"task",
",",
"response",
",",
"min_size",
"=",
"None",
",",
"max_size",
"=",
"None",
")",
":",
"try",
":",
"img",
"=",
"Image",
".",
"open",
"(",
"BytesIO",
"(",
"response",
".",
"content",
")",
")",
"except",
... | Decide whether to keep the image
Compare image size with ``min_size`` and ``max_size`` to decide.
Args:
response (Response): response of requests.
min_size (tuple or None): minimum size of required images.
max_size (tuple or None): maximum size of required images.
Returns:
bool: whether to keep the image. | [
"Decide",
"whether",
"to",
"keep",
"the",
"image"
] | 38c925758fd3d3e568d3ecc993f77bc0acfa4788 | https://github.com/hellock/icrawler/blob/38c925758fd3d3e568d3ecc993f77bc0acfa4788/icrawler/downloader.py#L232-L253 | train | 215,445 |
hellock/icrawler | icrawler/crawler.py | Crawler.set_logger | def set_logger(self, log_level=logging.INFO):
"""Configure the logger with log_level."""
logging.basicConfig(
format='%(asctime)s - %(levelname)s - %(name)s - %(message)s',
level=log_level,
stream=sys.stderr)
self.logger = logging.getLogger(__name__)
logging.getLogger('requests').setLevel(logging.WARNING) | python | def set_logger(self, log_level=logging.INFO):
"""Configure the logger with log_level."""
logging.basicConfig(
format='%(asctime)s - %(levelname)s - %(name)s - %(message)s',
level=log_level,
stream=sys.stderr)
self.logger = logging.getLogger(__name__)
logging.getLogger('requests').setLevel(logging.WARNING) | [
"def",
"set_logger",
"(",
"self",
",",
"log_level",
"=",
"logging",
".",
"INFO",
")",
":",
"logging",
".",
"basicConfig",
"(",
"format",
"=",
"'%(asctime)s - %(levelname)s - %(name)s - %(message)s'",
",",
"level",
"=",
"log_level",
",",
"stream",
"=",
"sys",
"."... | Configure the logger with log_level. | [
"Configure",
"the",
"logger",
"with",
"log_level",
"."
] | 38c925758fd3d3e568d3ecc993f77bc0acfa4788 | https://github.com/hellock/icrawler/blob/38c925758fd3d3e568d3ecc993f77bc0acfa4788/icrawler/crawler.py#L76-L83 | train | 215,446 |
hellock/icrawler | icrawler/crawler.py | Crawler.set_storage | def set_storage(self, storage):
"""Set storage backend for downloader
For full list of storage backend supported, please see :mod:`storage`.
Args:
storage (dict or BaseStorage): storage backend configuration or instance
"""
if isinstance(storage, BaseStorage):
self.storage = storage
elif isinstance(storage, dict):
if 'backend' not in storage and 'root_dir' in storage:
storage['backend'] = 'FileSystem'
try:
backend_cls = getattr(storage_package, storage['backend'])
except AttributeError:
try:
backend_cls = import_module(storage['backend'])
except ImportError:
self.logger.error('cannot find backend module %s',
storage['backend'])
sys.exit()
kwargs = storage.copy()
del kwargs['backend']
self.storage = backend_cls(**kwargs)
else:
raise TypeError('"storage" must be a storage object or dict') | python | def set_storage(self, storage):
"""Set storage backend for downloader
For full list of storage backend supported, please see :mod:`storage`.
Args:
storage (dict or BaseStorage): storage backend configuration or instance
"""
if isinstance(storage, BaseStorage):
self.storage = storage
elif isinstance(storage, dict):
if 'backend' not in storage and 'root_dir' in storage:
storage['backend'] = 'FileSystem'
try:
backend_cls = getattr(storage_package, storage['backend'])
except AttributeError:
try:
backend_cls = import_module(storage['backend'])
except ImportError:
self.logger.error('cannot find backend module %s',
storage['backend'])
sys.exit()
kwargs = storage.copy()
del kwargs['backend']
self.storage = backend_cls(**kwargs)
else:
raise TypeError('"storage" must be a storage object or dict') | [
"def",
"set_storage",
"(",
"self",
",",
"storage",
")",
":",
"if",
"isinstance",
"(",
"storage",
",",
"BaseStorage",
")",
":",
"self",
".",
"storage",
"=",
"storage",
"elif",
"isinstance",
"(",
"storage",
",",
"dict",
")",
":",
"if",
"'backend'",
"not",
... | Set storage backend for downloader
For full list of storage backend supported, please see :mod:`storage`.
Args:
storage (dict or BaseStorage): storage backend configuration or instance | [
"Set",
"storage",
"backend",
"for",
"downloader"
] | 38c925758fd3d3e568d3ecc993f77bc0acfa4788 | https://github.com/hellock/icrawler/blob/38c925758fd3d3e568d3ecc993f77bc0acfa4788/icrawler/crawler.py#L95-L122 | train | 215,447 |
hellock/icrawler | icrawler/crawler.py | Crawler.set_session | def set_session(self, headers=None):
"""Init session with default or custom headers
Args:
headers: A dict of headers (default None, thus using the default
header to init the session)
"""
if headers is None:
headers = {
'User-Agent':
('Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_3)'
' AppleWebKit/537.36 (KHTML, like Gecko) '
'Chrome/48.0.2564.116 Safari/537.36')
}
elif not isinstance(headers, dict):
raise TypeError('"headers" must be a dict object')
self.session = Session(self.proxy_pool)
self.session.headers.update(headers) | python | def set_session(self, headers=None):
"""Init session with default or custom headers
Args:
headers: A dict of headers (default None, thus using the default
header to init the session)
"""
if headers is None:
headers = {
'User-Agent':
('Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_3)'
' AppleWebKit/537.36 (KHTML, like Gecko) '
'Chrome/48.0.2564.116 Safari/537.36')
}
elif not isinstance(headers, dict):
raise TypeError('"headers" must be a dict object')
self.session = Session(self.proxy_pool)
self.session.headers.update(headers) | [
"def",
"set_session",
"(",
"self",
",",
"headers",
"=",
"None",
")",
":",
"if",
"headers",
"is",
"None",
":",
"headers",
"=",
"{",
"'User-Agent'",
":",
"(",
"'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_3)'",
"' AppleWebKit/537.36 (KHTML, like Gecko) '",
"'Chrome/48.0.... | Init session with default or custom headers
Args:
headers: A dict of headers (default None, thus using the default
header to init the session) | [
"Init",
"session",
"with",
"default",
"or",
"custom",
"headers"
] | 38c925758fd3d3e568d3ecc993f77bc0acfa4788 | https://github.com/hellock/icrawler/blob/38c925758fd3d3e568d3ecc993f77bc0acfa4788/icrawler/crawler.py#L134-L152 | train | 215,448 |
pmorissette/bt | bt/core.py | Node.value | def value(self):
"""
Current value of the Node
"""
if self.root.stale:
self.root.update(self.root.now, None)
return self._value | python | def value(self):
"""
Current value of the Node
"""
if self.root.stale:
self.root.update(self.root.now, None)
return self._value | [
"def",
"value",
"(",
"self",
")",
":",
"if",
"self",
".",
"root",
".",
"stale",
":",
"self",
".",
"root",
".",
"update",
"(",
"self",
".",
"root",
".",
"now",
",",
"None",
")",
"return",
"self",
".",
"_value"
] | Current value of the Node | [
"Current",
"value",
"of",
"the",
"Node"
] | 0363e6fa100d9392dd18e32e3d8379d5e83c28fa | https://github.com/pmorissette/bt/blob/0363e6fa100d9392dd18e32e3d8379d5e83c28fa/bt/core.py#L175-L181 | train | 215,449 |
pmorissette/bt | bt/core.py | Node.members | def members(self):
"""
Node members. Members include current node as well as Node's
children.
"""
res = [self]
for c in list(self.children.values()):
res.extend(c.members)
return res | python | def members(self):
"""
Node members. Members include current node as well as Node's
children.
"""
res = [self]
for c in list(self.children.values()):
res.extend(c.members)
return res | [
"def",
"members",
"(",
"self",
")",
":",
"res",
"=",
"[",
"self",
"]",
"for",
"c",
"in",
"list",
"(",
"self",
".",
"children",
".",
"values",
"(",
")",
")",
":",
"res",
".",
"extend",
"(",
"c",
".",
"members",
")",
"return",
"res"
] | Node members. Members include current node as well as Node's
children. | [
"Node",
"members",
".",
"Members",
"include",
"current",
"node",
"as",
"well",
"as",
"Node",
"s",
"children",
"."
] | 0363e6fa100d9392dd18e32e3d8379d5e83c28fa | https://github.com/pmorissette/bt/blob/0363e6fa100d9392dd18e32e3d8379d5e83c28fa/bt/core.py#L229-L237 | train | 215,450 |
pmorissette/bt | bt/core.py | StrategyBase.universe | def universe(self):
"""
Data universe available at the current time.
Universe contains the data passed in when creating a Backtest.
Use this data to determine strategy logic.
"""
# avoid windowing every time
# if calling and on same date return
# cached value
if self.now == self._last_chk:
return self._funiverse
else:
self._last_chk = self.now
self._funiverse = self._universe.loc[:self.now]
return self._funiverse | python | def universe(self):
"""
Data universe available at the current time.
Universe contains the data passed in when creating a Backtest.
Use this data to determine strategy logic.
"""
# avoid windowing every time
# if calling and on same date return
# cached value
if self.now == self._last_chk:
return self._funiverse
else:
self._last_chk = self.now
self._funiverse = self._universe.loc[:self.now]
return self._funiverse | [
"def",
"universe",
"(",
"self",
")",
":",
"# avoid windowing every time",
"# if calling and on same date return",
"# cached value",
"if",
"self",
".",
"now",
"==",
"self",
".",
"_last_chk",
":",
"return",
"self",
".",
"_funiverse",
"else",
":",
"self",
".",
"_last... | Data universe available at the current time.
Universe contains the data passed in when creating a Backtest.
Use this data to determine strategy logic. | [
"Data",
"universe",
"available",
"at",
"the",
"current",
"time",
".",
"Universe",
"contains",
"the",
"data",
"passed",
"in",
"when",
"creating",
"a",
"Backtest",
".",
"Use",
"this",
"data",
"to",
"determine",
"strategy",
"logic",
"."
] | 0363e6fa100d9392dd18e32e3d8379d5e83c28fa | https://github.com/pmorissette/bt/blob/0363e6fa100d9392dd18e32e3d8379d5e83c28fa/bt/core.py#L374-L388 | train | 215,451 |
pmorissette/bt | bt/core.py | StrategyBase.outlays | def outlays(self):
"""
Returns a DataFrame of outlays for each child SecurityBase
"""
return pd.DataFrame({x.name: x.outlays for x in self.securities}) | python | def outlays(self):
"""
Returns a DataFrame of outlays for each child SecurityBase
"""
return pd.DataFrame({x.name: x.outlays for x in self.securities}) | [
"def",
"outlays",
"(",
"self",
")",
":",
"return",
"pd",
".",
"DataFrame",
"(",
"{",
"x",
".",
"name",
":",
"x",
".",
"outlays",
"for",
"x",
"in",
"self",
".",
"securities",
"}",
")"
] | Returns a DataFrame of outlays for each child SecurityBase | [
"Returns",
"a",
"DataFrame",
"of",
"outlays",
"for",
"each",
"child",
"SecurityBase"
] | 0363e6fa100d9392dd18e32e3d8379d5e83c28fa | https://github.com/pmorissette/bt/blob/0363e6fa100d9392dd18e32e3d8379d5e83c28fa/bt/core.py#L398-L402 | train | 215,452 |
pmorissette/bt | bt/core.py | StrategyBase.setup | def setup(self, universe):
"""
Setup strategy with universe. This will speed up future calculations
and updates.
"""
# save full universe in case we need it
self._original_data = universe
# determine if needs paper trading
# and setup if so
if self is not self.parent:
self._paper_trade = True
self._paper_amount = 1000000
paper = deepcopy(self)
paper.parent = paper
paper.root = paper
paper._paper_trade = False
paper.setup(self._original_data)
paper.adjust(self._paper_amount)
self._paper = paper
# setup universe
funiverse = universe
if self._universe_tickers is not None:
# if we have universe_tickers defined, limit universe to
# those tickers
valid_filter = list(set(universe.columns)
.intersection(self._universe_tickers))
funiverse = universe[valid_filter].copy()
# if we have strat children, we will need to create their columns
# in the new universe
if self._has_strat_children:
for c in self._strat_children:
funiverse[c] = np.nan
# must create to avoid pandas warning
funiverse = pd.DataFrame(funiverse)
self._universe = funiverse
# holds filtered universe
self._funiverse = funiverse
self._last_chk = None
# We're not bankrupt yet
self.bankrupt = False
# setup internal data
self.data = pd.DataFrame(index=funiverse.index,
columns=['price', 'value', 'cash', 'fees'],
data=0.0)
self._prices = self.data['price']
self._values = self.data['value']
self._cash = self.data['cash']
self._fees = self.data['fees']
# setup children as well - use original universe here - don't want to
# pollute with potential strategy children in funiverse
if self.children is not None:
[c.setup(universe) for c in self._childrenv] | python | def setup(self, universe):
"""
Setup strategy with universe. This will speed up future calculations
and updates.
"""
# save full universe in case we need it
self._original_data = universe
# determine if needs paper trading
# and setup if so
if self is not self.parent:
self._paper_trade = True
self._paper_amount = 1000000
paper = deepcopy(self)
paper.parent = paper
paper.root = paper
paper._paper_trade = False
paper.setup(self._original_data)
paper.adjust(self._paper_amount)
self._paper = paper
# setup universe
funiverse = universe
if self._universe_tickers is not None:
# if we have universe_tickers defined, limit universe to
# those tickers
valid_filter = list(set(universe.columns)
.intersection(self._universe_tickers))
funiverse = universe[valid_filter].copy()
# if we have strat children, we will need to create their columns
# in the new universe
if self._has_strat_children:
for c in self._strat_children:
funiverse[c] = np.nan
# must create to avoid pandas warning
funiverse = pd.DataFrame(funiverse)
self._universe = funiverse
# holds filtered universe
self._funiverse = funiverse
self._last_chk = None
# We're not bankrupt yet
self.bankrupt = False
# setup internal data
self.data = pd.DataFrame(index=funiverse.index,
columns=['price', 'value', 'cash', 'fees'],
data=0.0)
self._prices = self.data['price']
self._values = self.data['value']
self._cash = self.data['cash']
self._fees = self.data['fees']
# setup children as well - use original universe here - don't want to
# pollute with potential strategy children in funiverse
if self.children is not None:
[c.setup(universe) for c in self._childrenv] | [
"def",
"setup",
"(",
"self",
",",
"universe",
")",
":",
"# save full universe in case we need it",
"self",
".",
"_original_data",
"=",
"universe",
"# determine if needs paper trading",
"# and setup if so",
"if",
"self",
"is",
"not",
"self",
".",
"parent",
":",
"self",... | Setup strategy with universe. This will speed up future calculations
and updates. | [
"Setup",
"strategy",
"with",
"universe",
".",
"This",
"will",
"speed",
"up",
"future",
"calculations",
"and",
"updates",
"."
] | 0363e6fa100d9392dd18e32e3d8379d5e83c28fa | https://github.com/pmorissette/bt/blob/0363e6fa100d9392dd18e32e3d8379d5e83c28fa/bt/core.py#L418-L481 | train | 215,453 |
pmorissette/bt | bt/core.py | StrategyBase.update | def update(self, date, data=None, inow=None):
"""
Update strategy. Updates prices, values, weight, etc.
"""
# resolve stale state
self.root.stale = False
# update helpers on date change
# also set newpt flag
newpt = False
if self.now == 0:
newpt = True
elif date != self.now:
self._net_flows = 0
self._last_price = self._price
self._last_value = self._value
self._last_fee = 0.0
newpt = True
# update now
self.now = date
if inow is None:
if self.now == 0:
inow = 0
else:
inow = self.data.index.get_loc(date)
# update children if any and calculate value
val = self._capital # default if no children
if self.children is not None:
for c in self._childrenv:
# avoid useless update call
if c._issec and not c._needupdate:
continue
c.update(date, data, inow)
val += c.value
if self.root == self:
if (val < 0) and not self.bankrupt:
# Declare a bankruptcy
self.bankrupt = True
self.flatten()
# update data if this value is different or
# if now has changed - avoid all this if not since it
# won't change
if newpt or self._value != val:
self._value = val
self._values.values[inow] = val
bottom = self._last_value + self._net_flows
if bottom != 0:
ret = self._value / (self._last_value + self._net_flows) - 1
else:
if self._value == 0:
ret = 0
else:
raise ZeroDivisionError(
'Could not update %s. Last value '
'was %s and net flows were %s. Current'
'value is %s. Therefore, '
'we are dividing by zero to obtain the return '
'for the period.' % (self.name,
self._last_value,
self._net_flows,
self._value))
self._price = self._last_price * (1 + ret)
self._prices.values[inow] = self._price
# update children weights
if self.children is not None:
for c in self._childrenv:
# avoid useless update call
if c._issec and not c._needupdate:
continue
if val != 0:
c._weight = c.value / val
else:
c._weight = 0.0
# if we have strategy children, we will need to update them in universe
if self._has_strat_children:
for c in self._strat_children:
# TODO: optimize ".loc" here as well
self._universe.loc[date, c] = self.children[c].price
# Cash should track the unallocated capital at the end of the day, so
# we should update it every time we call "update".
# Same for fees
self._cash.values[inow] = self._capital
self._fees.values[inow] = self._last_fee
# update paper trade if necessary
if newpt and self._paper_trade:
self._paper.update(date)
self._paper.run()
self._paper.update(date)
# update price
self._price = self._paper.price
self._prices.values[inow] = self._price | python | def update(self, date, data=None, inow=None):
"""
Update strategy. Updates prices, values, weight, etc.
"""
# resolve stale state
self.root.stale = False
# update helpers on date change
# also set newpt flag
newpt = False
if self.now == 0:
newpt = True
elif date != self.now:
self._net_flows = 0
self._last_price = self._price
self._last_value = self._value
self._last_fee = 0.0
newpt = True
# update now
self.now = date
if inow is None:
if self.now == 0:
inow = 0
else:
inow = self.data.index.get_loc(date)
# update children if any and calculate value
val = self._capital # default if no children
if self.children is not None:
for c in self._childrenv:
# avoid useless update call
if c._issec and not c._needupdate:
continue
c.update(date, data, inow)
val += c.value
if self.root == self:
if (val < 0) and not self.bankrupt:
# Declare a bankruptcy
self.bankrupt = True
self.flatten()
# update data if this value is different or
# if now has changed - avoid all this if not since it
# won't change
if newpt or self._value != val:
self._value = val
self._values.values[inow] = val
bottom = self._last_value + self._net_flows
if bottom != 0:
ret = self._value / (self._last_value + self._net_flows) - 1
else:
if self._value == 0:
ret = 0
else:
raise ZeroDivisionError(
'Could not update %s. Last value '
'was %s and net flows were %s. Current'
'value is %s. Therefore, '
'we are dividing by zero to obtain the return '
'for the period.' % (self.name,
self._last_value,
self._net_flows,
self._value))
self._price = self._last_price * (1 + ret)
self._prices.values[inow] = self._price
# update children weights
if self.children is not None:
for c in self._childrenv:
# avoid useless update call
if c._issec and not c._needupdate:
continue
if val != 0:
c._weight = c.value / val
else:
c._weight = 0.0
# if we have strategy children, we will need to update them in universe
if self._has_strat_children:
for c in self._strat_children:
# TODO: optimize ".loc" here as well
self._universe.loc[date, c] = self.children[c].price
# Cash should track the unallocated capital at the end of the day, so
# we should update it every time we call "update".
# Same for fees
self._cash.values[inow] = self._capital
self._fees.values[inow] = self._last_fee
# update paper trade if necessary
if newpt and self._paper_trade:
self._paper.update(date)
self._paper.run()
self._paper.update(date)
# update price
self._price = self._paper.price
self._prices.values[inow] = self._price | [
"def",
"update",
"(",
"self",
",",
"date",
",",
"data",
"=",
"None",
",",
"inow",
"=",
"None",
")",
":",
"# resolve stale state",
"self",
".",
"root",
".",
"stale",
"=",
"False",
"# update helpers on date change",
"# also set newpt flag",
"newpt",
"=",
"False"... | Update strategy. Updates prices, values, weight, etc. | [
"Update",
"strategy",
".",
"Updates",
"prices",
"values",
"weight",
"etc",
"."
] | 0363e6fa100d9392dd18e32e3d8379d5e83c28fa | https://github.com/pmorissette/bt/blob/0363e6fa100d9392dd18e32e3d8379d5e83c28fa/bt/core.py#L484-L586 | train | 215,454 |
pmorissette/bt | bt/core.py | StrategyBase.adjust | def adjust(self, amount, update=True, flow=True, fee=0.0):
"""
Adjust capital - used to inject capital to a Strategy. This injection
of capital will have no effect on the children.
Args:
* amount (float): Amount to adjust by.
* update (bool): Force update?
* flow (bool): Is this adjustment a flow? A flow will not have an
impact on the performance (price index). Example of flows are
simply capital injections (say a monthly contribution to a
portfolio). This should not be reflected in the returns. A
non-flow (flow=False) does impact performance. A good example
of this is a commission, or a dividend.
"""
# adjust capital
self._capital += amount
self._last_fee += fee
# if flow - increment net_flows - this will not affect
# performance. Commissions and other fees are not flows since
# they have a performance impact
if flow:
self._net_flows += amount
if update:
# indicates that data is now stale and must
# be updated before access
self.root.stale = True | python | def adjust(self, amount, update=True, flow=True, fee=0.0):
"""
Adjust capital - used to inject capital to a Strategy. This injection
of capital will have no effect on the children.
Args:
* amount (float): Amount to adjust by.
* update (bool): Force update?
* flow (bool): Is this adjustment a flow? A flow will not have an
impact on the performance (price index). Example of flows are
simply capital injections (say a monthly contribution to a
portfolio). This should not be reflected in the returns. A
non-flow (flow=False) does impact performance. A good example
of this is a commission, or a dividend.
"""
# adjust capital
self._capital += amount
self._last_fee += fee
# if flow - increment net_flows - this will not affect
# performance. Commissions and other fees are not flows since
# they have a performance impact
if flow:
self._net_flows += amount
if update:
# indicates that data is now stale and must
# be updated before access
self.root.stale = True | [
"def",
"adjust",
"(",
"self",
",",
"amount",
",",
"update",
"=",
"True",
",",
"flow",
"=",
"True",
",",
"fee",
"=",
"0.0",
")",
":",
"# adjust capital",
"self",
".",
"_capital",
"+=",
"amount",
"self",
".",
"_last_fee",
"+=",
"fee",
"# if flow - incremen... | Adjust capital - used to inject capital to a Strategy. This injection
of capital will have no effect on the children.
Args:
* amount (float): Amount to adjust by.
* update (bool): Force update?
* flow (bool): Is this adjustment a flow? A flow will not have an
impact on the performance (price index). Example of flows are
simply capital injections (say a monthly contribution to a
portfolio). This should not be reflected in the returns. A
non-flow (flow=False) does impact performance. A good example
of this is a commission, or a dividend. | [
"Adjust",
"capital",
"-",
"used",
"to",
"inject",
"capital",
"to",
"a",
"Strategy",
".",
"This",
"injection",
"of",
"capital",
"will",
"have",
"no",
"effect",
"on",
"the",
"children",
"."
] | 0363e6fa100d9392dd18e32e3d8379d5e83c28fa | https://github.com/pmorissette/bt/blob/0363e6fa100d9392dd18e32e3d8379d5e83c28fa/bt/core.py#L589-L618 | train | 215,455 |
pmorissette/bt | bt/core.py | StrategyBase.allocate | def allocate(self, amount, child=None, update=True):
"""
Allocate capital to Strategy. By default, capital is allocated
recursively down the children, proportionally to the children's
weights. If a child is specified, capital will be allocated
to that specific child.
Allocation also have a side-effect. They will deduct the same amount
from the parent's "account" to offset the allocation. If there is
remaining capital after allocation, it will remain in Strategy.
Args:
* amount (float): Amount to allocate.
* child (str): If specified, allocation will be directed to child
only. Specified by name.
* update (bool): Force update.
"""
# allocate to child
if child is not None:
if child not in self.children:
c = SecurityBase(child)
c.setup(self._universe)
# update to bring up to speed
c.update(self.now)
# add child to tree
self._add_child(c)
# allocate to child
self.children[child].allocate(amount)
# allocate to self
else:
# adjust parent's capital
# no need to update now - avoids repetition
if self.parent == self:
self.parent.adjust(-amount, update=False, flow=True)
else:
# do NOT set as flow - parent will be another strategy
# and therefore should not incur flow
self.parent.adjust(-amount, update=False, flow=False)
# adjust self's capital
self.adjust(amount, update=False, flow=True)
# push allocation down to children if any
# use _weight to avoid triggering an update
if self.children is not None:
[c.allocate(amount * c._weight, update=False)
for c in self._childrenv]
# mark as stale if update requested
if update:
self.root.stale = True | python | def allocate(self, amount, child=None, update=True):
"""
Allocate capital to Strategy. By default, capital is allocated
recursively down the children, proportionally to the children's
weights. If a child is specified, capital will be allocated
to that specific child.
Allocation also have a side-effect. They will deduct the same amount
from the parent's "account" to offset the allocation. If there is
remaining capital after allocation, it will remain in Strategy.
Args:
* amount (float): Amount to allocate.
* child (str): If specified, allocation will be directed to child
only. Specified by name.
* update (bool): Force update.
"""
# allocate to child
if child is not None:
if child not in self.children:
c = SecurityBase(child)
c.setup(self._universe)
# update to bring up to speed
c.update(self.now)
# add child to tree
self._add_child(c)
# allocate to child
self.children[child].allocate(amount)
# allocate to self
else:
# adjust parent's capital
# no need to update now - avoids repetition
if self.parent == self:
self.parent.adjust(-amount, update=False, flow=True)
else:
# do NOT set as flow - parent will be another strategy
# and therefore should not incur flow
self.parent.adjust(-amount, update=False, flow=False)
# adjust self's capital
self.adjust(amount, update=False, flow=True)
# push allocation down to children if any
# use _weight to avoid triggering an update
if self.children is not None:
[c.allocate(amount * c._weight, update=False)
for c in self._childrenv]
# mark as stale if update requested
if update:
self.root.stale = True | [
"def",
"allocate",
"(",
"self",
",",
"amount",
",",
"child",
"=",
"None",
",",
"update",
"=",
"True",
")",
":",
"# allocate to child",
"if",
"child",
"is",
"not",
"None",
":",
"if",
"child",
"not",
"in",
"self",
".",
"children",
":",
"c",
"=",
"Secur... | Allocate capital to Strategy. By default, capital is allocated
recursively down the children, proportionally to the children's
weights. If a child is specified, capital will be allocated
to that specific child.
Allocation also have a side-effect. They will deduct the same amount
from the parent's "account" to offset the allocation. If there is
remaining capital after allocation, it will remain in Strategy.
Args:
* amount (float): Amount to allocate.
* child (str): If specified, allocation will be directed to child
only. Specified by name.
* update (bool): Force update. | [
"Allocate",
"capital",
"to",
"Strategy",
".",
"By",
"default",
"capital",
"is",
"allocated",
"recursively",
"down",
"the",
"children",
"proportionally",
"to",
"the",
"children",
"s",
"weights",
".",
"If",
"a",
"child",
"is",
"specified",
"capital",
"will",
"be... | 0363e6fa100d9392dd18e32e3d8379d5e83c28fa | https://github.com/pmorissette/bt/blob/0363e6fa100d9392dd18e32e3d8379d5e83c28fa/bt/core.py#L621-L673 | train | 215,456 |
pmorissette/bt | bt/core.py | StrategyBase.rebalance | def rebalance(self, weight, child, base=np.nan, update=True):
"""
Rebalance a child to a given weight.
This is a helper method to simplify code logic. This method is used
when we want to se the weight of a particular child to a set amount.
It is similar to allocate, but it calculates the appropriate allocation
based on the current weight.
Args:
* weight (float): The target weight. Usually between -1.0 and 1.0.
* child (str): child to allocate to - specified by name.
* base (float): If specified, this is the base amount all weight
delta calculations will be based off of. This is useful when we
determine a set of weights and want to rebalance each child
given these new weights. However, as we iterate through each
child and call this method, the base (which is by default the
current value) will change. Therefore, we can set this base to
the original value before the iteration to ensure the proper
allocations are made.
* update (bool): Force update?
"""
# if weight is 0 - we want to close child
if weight == 0:
if child in self.children:
return self.close(child)
else:
return
# if no base specified use self's value
if np.isnan(base):
base = self.value
# else make sure we have child
if child not in self.children:
c = SecurityBase(child)
c.setup(self._universe)
# update child to bring up to speed
c.update(self.now)
self._add_child(c)
# allocate to child
# figure out weight delta
c = self.children[child]
delta = weight - c.weight
c.allocate(delta * base) | python | def rebalance(self, weight, child, base=np.nan, update=True):
"""
Rebalance a child to a given weight.
This is a helper method to simplify code logic. This method is used
when we want to se the weight of a particular child to a set amount.
It is similar to allocate, but it calculates the appropriate allocation
based on the current weight.
Args:
* weight (float): The target weight. Usually between -1.0 and 1.0.
* child (str): child to allocate to - specified by name.
* base (float): If specified, this is the base amount all weight
delta calculations will be based off of. This is useful when we
determine a set of weights and want to rebalance each child
given these new weights. However, as we iterate through each
child and call this method, the base (which is by default the
current value) will change. Therefore, we can set this base to
the original value before the iteration to ensure the proper
allocations are made.
* update (bool): Force update?
"""
# if weight is 0 - we want to close child
if weight == 0:
if child in self.children:
return self.close(child)
else:
return
# if no base specified use self's value
if np.isnan(base):
base = self.value
# else make sure we have child
if child not in self.children:
c = SecurityBase(child)
c.setup(self._universe)
# update child to bring up to speed
c.update(self.now)
self._add_child(c)
# allocate to child
# figure out weight delta
c = self.children[child]
delta = weight - c.weight
c.allocate(delta * base) | [
"def",
"rebalance",
"(",
"self",
",",
"weight",
",",
"child",
",",
"base",
"=",
"np",
".",
"nan",
",",
"update",
"=",
"True",
")",
":",
"# if weight is 0 - we want to close child",
"if",
"weight",
"==",
"0",
":",
"if",
"child",
"in",
"self",
".",
"childr... | Rebalance a child to a given weight.
This is a helper method to simplify code logic. This method is used
when we want to se the weight of a particular child to a set amount.
It is similar to allocate, but it calculates the appropriate allocation
based on the current weight.
Args:
* weight (float): The target weight. Usually between -1.0 and 1.0.
* child (str): child to allocate to - specified by name.
* base (float): If specified, this is the base amount all weight
delta calculations will be based off of. This is useful when we
determine a set of weights and want to rebalance each child
given these new weights. However, as we iterate through each
child and call this method, the base (which is by default the
current value) will change. Therefore, we can set this base to
the original value before the iteration to ensure the proper
allocations are made.
* update (bool): Force update? | [
"Rebalance",
"a",
"child",
"to",
"a",
"given",
"weight",
"."
] | 0363e6fa100d9392dd18e32e3d8379d5e83c28fa | https://github.com/pmorissette/bt/blob/0363e6fa100d9392dd18e32e3d8379d5e83c28fa/bt/core.py#L676-L722 | train | 215,457 |
pmorissette/bt | bt/core.py | StrategyBase.flatten | def flatten(self):
"""
Close all child positions.
"""
# go right to base alloc
[c.allocate(-c.value) for c in self._childrenv if c.value != 0] | python | def flatten(self):
"""
Close all child positions.
"""
# go right to base alloc
[c.allocate(-c.value) for c in self._childrenv if c.value != 0] | [
"def",
"flatten",
"(",
"self",
")",
":",
"# go right to base alloc",
"[",
"c",
".",
"allocate",
"(",
"-",
"c",
".",
"value",
")",
"for",
"c",
"in",
"self",
".",
"_childrenv",
"if",
"c",
".",
"value",
"!=",
"0",
"]"
] | Close all child positions. | [
"Close",
"all",
"child",
"positions",
"."
] | 0363e6fa100d9392dd18e32e3d8379d5e83c28fa | https://github.com/pmorissette/bt/blob/0363e6fa100d9392dd18e32e3d8379d5e83c28fa/bt/core.py#L740-L745 | train | 215,458 |
pmorissette/bt | bt/core.py | SecurityBase.setup | def setup(self, universe):
"""
Setup Security with universe. Speeds up future runs.
Args:
* universe (DataFrame): DataFrame of prices with security's name as
one of the columns.
"""
# if we already have all the prices, we will store them to speed up
# future updates
try:
prices = universe[self.name]
except KeyError:
prices = None
# setup internal data
if prices is not None:
self._prices = prices
self.data = pd.DataFrame(index=universe.index,
columns=['value', 'position'],
data=0.0)
self._prices_set = True
else:
self.data = pd.DataFrame(index=universe.index,
columns=['price', 'value', 'position'])
self._prices = self.data['price']
self._prices_set = False
self._values = self.data['value']
self._positions = self.data['position']
# add _outlay
self.data['outlay'] = 0.
self._outlays = self.data['outlay'] | python | def setup(self, universe):
"""
Setup Security with universe. Speeds up future runs.
Args:
* universe (DataFrame): DataFrame of prices with security's name as
one of the columns.
"""
# if we already have all the prices, we will store them to speed up
# future updates
try:
prices = universe[self.name]
except KeyError:
prices = None
# setup internal data
if prices is not None:
self._prices = prices
self.data = pd.DataFrame(index=universe.index,
columns=['value', 'position'],
data=0.0)
self._prices_set = True
else:
self.data = pd.DataFrame(index=universe.index,
columns=['price', 'value', 'position'])
self._prices = self.data['price']
self._prices_set = False
self._values = self.data['value']
self._positions = self.data['position']
# add _outlay
self.data['outlay'] = 0.
self._outlays = self.data['outlay'] | [
"def",
"setup",
"(",
"self",
",",
"universe",
")",
":",
"# if we already have all the prices, we will store them to speed up",
"# future updates",
"try",
":",
"prices",
"=",
"universe",
"[",
"self",
".",
"name",
"]",
"except",
"KeyError",
":",
"prices",
"=",
"None",... | Setup Security with universe. Speeds up future runs.
Args:
* universe (DataFrame): DataFrame of prices with security's name as
one of the columns. | [
"Setup",
"Security",
"with",
"universe",
".",
"Speeds",
"up",
"future",
"runs",
"."
] | 0363e6fa100d9392dd18e32e3d8379d5e83c28fa | https://github.com/pmorissette/bt/blob/0363e6fa100d9392dd18e32e3d8379d5e83c28fa/bt/core.py#L893-L927 | train | 215,459 |
pmorissette/bt | bt/core.py | SecurityBase.update | def update(self, date, data=None, inow=None):
"""
Update security with a given date and optionally, some data.
This will update price, value, weight, etc.
"""
# filter for internal calls when position has not changed - nothing to
# do. Internal calls (stale root calls) have None data. Also want to
# make sure date has not changed, because then we do indeed want to
# update.
if date == self.now and self._last_pos == self._position:
return
if inow is None:
if date == 0:
inow = 0
else:
inow = self.data.index.get_loc(date)
# date change - update price
if date != self.now:
# update now
self.now = date
if self._prices_set:
self._price = self._prices.values[inow]
# traditional data update
elif data is not None:
prc = data[self.name]
self._price = prc
self._prices.values[inow] = prc
self._positions.values[inow] = self._position
self._last_pos = self._position
if np.isnan(self._price):
if self._position == 0:
self._value = 0
else:
raise Exception(
'Position is open (non-zero) and latest price is NaN '
'for security %s. Cannot update node value.' % self.name)
else:
self._value = self._position * self._price * self.multiplier
self._values.values[inow] = self._value
if self._weight == 0 and self._position == 0:
self._needupdate = False
# save outlay to outlays
if self._outlay != 0:
self._outlays.values[inow] = self._outlay
# reset outlay back to 0
self._outlay = 0 | python | def update(self, date, data=None, inow=None):
"""
Update security with a given date and optionally, some data.
This will update price, value, weight, etc.
"""
# filter for internal calls when position has not changed - nothing to
# do. Internal calls (stale root calls) have None data. Also want to
# make sure date has not changed, because then we do indeed want to
# update.
if date == self.now and self._last_pos == self._position:
return
if inow is None:
if date == 0:
inow = 0
else:
inow = self.data.index.get_loc(date)
# date change - update price
if date != self.now:
# update now
self.now = date
if self._prices_set:
self._price = self._prices.values[inow]
# traditional data update
elif data is not None:
prc = data[self.name]
self._price = prc
self._prices.values[inow] = prc
self._positions.values[inow] = self._position
self._last_pos = self._position
if np.isnan(self._price):
if self._position == 0:
self._value = 0
else:
raise Exception(
'Position is open (non-zero) and latest price is NaN '
'for security %s. Cannot update node value.' % self.name)
else:
self._value = self._position * self._price * self.multiplier
self._values.values[inow] = self._value
if self._weight == 0 and self._position == 0:
self._needupdate = False
# save outlay to outlays
if self._outlay != 0:
self._outlays.values[inow] = self._outlay
# reset outlay back to 0
self._outlay = 0 | [
"def",
"update",
"(",
"self",
",",
"date",
",",
"data",
"=",
"None",
",",
"inow",
"=",
"None",
")",
":",
"# filter for internal calls when position has not changed - nothing to",
"# do. Internal calls (stale root calls) have None data. Also want to",
"# make sure date has not cha... | Update security with a given date and optionally, some data.
This will update price, value, weight, etc. | [
"Update",
"security",
"with",
"a",
"given",
"date",
"and",
"optionally",
"some",
"data",
".",
"This",
"will",
"update",
"price",
"value",
"weight",
"etc",
"."
] | 0363e6fa100d9392dd18e32e3d8379d5e83c28fa | https://github.com/pmorissette/bt/blob/0363e6fa100d9392dd18e32e3d8379d5e83c28fa/bt/core.py#L930-L983 | train | 215,460 |
pmorissette/bt | bt/core.py | Algo.name | def name(self):
"""
Algo name.
"""
if self._name is None:
self._name = self.__class__.__name__
return self._name | python | def name(self):
"""
Algo name.
"""
if self._name is None:
self._name = self.__class__.__name__
return self._name | [
"def",
"name",
"(",
"self",
")",
":",
"if",
"self",
".",
"_name",
"is",
"None",
":",
"self",
".",
"_name",
"=",
"self",
".",
"__class__",
".",
"__name__",
"return",
"self",
".",
"_name"
] | Algo name. | [
"Algo",
"name",
"."
] | 0363e6fa100d9392dd18e32e3d8379d5e83c28fa | https://github.com/pmorissette/bt/blob/0363e6fa100d9392dd18e32e3d8379d5e83c28fa/bt/core.py#L1217-L1223 | train | 215,461 |
pmorissette/bt | docs/source/_themes/klink/klink/__init__.py | convert_notebooks | def convert_notebooks():
"""
Converts IPython Notebooks to proper .rst files and moves static
content to the _static directory.
"""
convert_status = call(['ipython', 'nbconvert', '--to', 'rst', '*.ipynb'])
if convert_status != 0:
raise SystemError('Conversion failed! Status was %s' % convert_status)
notebooks = [x for x in os.listdir('.') if '.ipynb'
in x and os.path.isfile(x)]
names = [os.path.splitext(x)[0] for x in notebooks]
for i in range(len(notebooks)):
name = names[i]
notebook = notebooks[i]
print('processing %s (%s)' % (name, notebook))
# move static files
sdir = '%s_files' % name
statics = os.listdir(sdir)
statics = [os.path.join(sdir, x) for x in statics]
[shutil.copy(x, '_static/') for x in statics]
shutil.rmtree(sdir)
# rename static dir in rst file
rst_file = '%s.rst' % name
print('REsT file is %s' % rst_file)
data = None
with open(rst_file, 'r') as f:
data = f.read()
if data is not None:
with open(rst_file, 'w') as f:
data = re.sub('%s' % sdir, '_static', data)
f.write(data)
# add special tags
lines = None
with open(rst_file, 'r') as f:
lines = f.readlines()
if lines is not None:
n = len(lines)
i = 0
rawWatch = False
while i < n:
line = lines[i]
# add class tags to images for css formatting
if 'image::' in line:
lines.insert(i + 1, ' :class: pynb\n')
n += 1
elif 'parsed-literal::' in line:
lines.insert(i + 1, ' :class: pynb-result\n')
n += 1
elif 'raw:: html' in line:
rawWatch = True
if rawWatch:
if '<div' in line:
line = line.replace('<div', '<div class="pynb-result"')
lines[i] = line
rawWatch = False
i += 1
with open(rst_file, 'w') as f:
f.writelines(lines) | python | def convert_notebooks():
"""
Converts IPython Notebooks to proper .rst files and moves static
content to the _static directory.
"""
convert_status = call(['ipython', 'nbconvert', '--to', 'rst', '*.ipynb'])
if convert_status != 0:
raise SystemError('Conversion failed! Status was %s' % convert_status)
notebooks = [x for x in os.listdir('.') if '.ipynb'
in x and os.path.isfile(x)]
names = [os.path.splitext(x)[0] for x in notebooks]
for i in range(len(notebooks)):
name = names[i]
notebook = notebooks[i]
print('processing %s (%s)' % (name, notebook))
# move static files
sdir = '%s_files' % name
statics = os.listdir(sdir)
statics = [os.path.join(sdir, x) for x in statics]
[shutil.copy(x, '_static/') for x in statics]
shutil.rmtree(sdir)
# rename static dir in rst file
rst_file = '%s.rst' % name
print('REsT file is %s' % rst_file)
data = None
with open(rst_file, 'r') as f:
data = f.read()
if data is not None:
with open(rst_file, 'w') as f:
data = re.sub('%s' % sdir, '_static', data)
f.write(data)
# add special tags
lines = None
with open(rst_file, 'r') as f:
lines = f.readlines()
if lines is not None:
n = len(lines)
i = 0
rawWatch = False
while i < n:
line = lines[i]
# add class tags to images for css formatting
if 'image::' in line:
lines.insert(i + 1, ' :class: pynb\n')
n += 1
elif 'parsed-literal::' in line:
lines.insert(i + 1, ' :class: pynb-result\n')
n += 1
elif 'raw:: html' in line:
rawWatch = True
if rawWatch:
if '<div' in line:
line = line.replace('<div', '<div class="pynb-result"')
lines[i] = line
rawWatch = False
i += 1
with open(rst_file, 'w') as f:
f.writelines(lines) | [
"def",
"convert_notebooks",
"(",
")",
":",
"convert_status",
"=",
"call",
"(",
"[",
"'ipython'",
",",
"'nbconvert'",
",",
"'--to'",
",",
"'rst'",
",",
"'*.ipynb'",
"]",
")",
"if",
"convert_status",
"!=",
"0",
":",
"raise",
"SystemError",
"(",
"'Conversion fa... | Converts IPython Notebooks to proper .rst files and moves static
content to the _static directory. | [
"Converts",
"IPython",
"Notebooks",
"to",
"proper",
".",
"rst",
"files",
"and",
"moves",
"static",
"content",
"to",
"the",
"_static",
"directory",
"."
] | 0363e6fa100d9392dd18e32e3d8379d5e83c28fa | https://github.com/pmorissette/bt/blob/0363e6fa100d9392dd18e32e3d8379d5e83c28fa/docs/source/_themes/klink/klink/__init__.py#L7-L76 | train | 215,462 |
istresearch/scrapy-cluster | utils/scutils/settings_wrapper.py | SettingsWrapper.load | def load(self, local='localsettings.py', default='settings.py'):
'''
Load the settings dict
@param local: The local settings filename to use
@param default: The default settings module to read
@return: A dict of the loaded settings
'''
self._load_defaults(default)
self._load_custom(local)
return self.settings() | python | def load(self, local='localsettings.py', default='settings.py'):
'''
Load the settings dict
@param local: The local settings filename to use
@param default: The default settings module to read
@return: A dict of the loaded settings
'''
self._load_defaults(default)
self._load_custom(local)
return self.settings() | [
"def",
"load",
"(",
"self",
",",
"local",
"=",
"'localsettings.py'",
",",
"default",
"=",
"'settings.py'",
")",
":",
"self",
".",
"_load_defaults",
"(",
"default",
")",
"self",
".",
"_load_custom",
"(",
"local",
")",
"return",
"self",
".",
"settings",
"(",... | Load the settings dict
@param local: The local settings filename to use
@param default: The default settings module to read
@return: A dict of the loaded settings | [
"Load",
"the",
"settings",
"dict"
] | 13aaed2349af5d792d6bcbfcadc5563158aeb599 | https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/utils/scutils/settings_wrapper.py#L29-L40 | train | 215,463 |
istresearch/scrapy-cluster | utils/scutils/settings_wrapper.py | SettingsWrapper._load_defaults | def _load_defaults(self, default='settings.py'):
'''
Load the default settings
'''
if default[-3:] == '.py':
default = default[:-3]
self.my_settings = {}
try:
settings = importlib.import_module(default)
self.my_settings = self._convert_to_dict(settings)
except ImportError:
log.warning("No default settings found") | python | def _load_defaults(self, default='settings.py'):
'''
Load the default settings
'''
if default[-3:] == '.py':
default = default[:-3]
self.my_settings = {}
try:
settings = importlib.import_module(default)
self.my_settings = self._convert_to_dict(settings)
except ImportError:
log.warning("No default settings found") | [
"def",
"_load_defaults",
"(",
"self",
",",
"default",
"=",
"'settings.py'",
")",
":",
"if",
"default",
"[",
"-",
"3",
":",
"]",
"==",
"'.py'",
":",
"default",
"=",
"default",
"[",
":",
"-",
"3",
"]",
"self",
".",
"my_settings",
"=",
"{",
"}",
"try"... | Load the default settings | [
"Load",
"the",
"default",
"settings"
] | 13aaed2349af5d792d6bcbfcadc5563158aeb599 | https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/utils/scutils/settings_wrapper.py#L70-L82 | train | 215,464 |
istresearch/scrapy-cluster | utils/scutils/settings_wrapper.py | SettingsWrapper._load_custom | def _load_custom(self, settings_name='localsettings.py'):
'''
Load the user defined settings, overriding the defaults
'''
if settings_name[-3:] == '.py':
settings_name = settings_name[:-3]
new_settings = {}
try:
settings = importlib.import_module(settings_name)
new_settings = self._convert_to_dict(settings)
except ImportError:
log.info("No override settings found")
for key in new_settings:
if key in self.my_settings:
item = new_settings[key]
if isinstance(item, dict) and \
isinstance(self.my_settings[key], dict):
for key2 in item:
self.my_settings[key][key2] = item[key2]
else:
self.my_settings[key] = item
else:
self.my_settings[key] = new_settings[key] | python | def _load_custom(self, settings_name='localsettings.py'):
'''
Load the user defined settings, overriding the defaults
'''
if settings_name[-3:] == '.py':
settings_name = settings_name[:-3]
new_settings = {}
try:
settings = importlib.import_module(settings_name)
new_settings = self._convert_to_dict(settings)
except ImportError:
log.info("No override settings found")
for key in new_settings:
if key in self.my_settings:
item = new_settings[key]
if isinstance(item, dict) and \
isinstance(self.my_settings[key], dict):
for key2 in item:
self.my_settings[key][key2] = item[key2]
else:
self.my_settings[key] = item
else:
self.my_settings[key] = new_settings[key] | [
"def",
"_load_custom",
"(",
"self",
",",
"settings_name",
"=",
"'localsettings.py'",
")",
":",
"if",
"settings_name",
"[",
"-",
"3",
":",
"]",
"==",
"'.py'",
":",
"settings_name",
"=",
"settings_name",
"[",
":",
"-",
"3",
"]",
"new_settings",
"=",
"{",
"... | Load the user defined settings, overriding the defaults | [
"Load",
"the",
"user",
"defined",
"settings",
"overriding",
"the",
"defaults"
] | 13aaed2349af5d792d6bcbfcadc5563158aeb599 | https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/utils/scutils/settings_wrapper.py#L84-L109 | train | 215,465 |
istresearch/scrapy-cluster | utils/scutils/settings_wrapper.py | SettingsWrapper._convert_to_dict | def _convert_to_dict(self, setting):
'''
Converts a settings file into a dictionary, ignoring python defaults
@param setting: A loaded setting module
'''
the_dict = {}
set = dir(setting)
for key in set:
if key in self.ignore:
continue
value = getattr(setting, key)
the_dict[key] = value
return the_dict | python | def _convert_to_dict(self, setting):
'''
Converts a settings file into a dictionary, ignoring python defaults
@param setting: A loaded setting module
'''
the_dict = {}
set = dir(setting)
for key in set:
if key in self.ignore:
continue
value = getattr(setting, key)
the_dict[key] = value
return the_dict | [
"def",
"_convert_to_dict",
"(",
"self",
",",
"setting",
")",
":",
"the_dict",
"=",
"{",
"}",
"set",
"=",
"dir",
"(",
"setting",
")",
"for",
"key",
"in",
"set",
":",
"if",
"key",
"in",
"self",
".",
"ignore",
":",
"continue",
"value",
"=",
"getattr",
... | Converts a settings file into a dictionary, ignoring python defaults
@param setting: A loaded setting module | [
"Converts",
"a",
"settings",
"file",
"into",
"a",
"dictionary",
"ignoring",
"python",
"defaults"
] | 13aaed2349af5d792d6bcbfcadc5563158aeb599 | https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/utils/scutils/settings_wrapper.py#L111-L125 | train | 215,466 |
istresearch/scrapy-cluster | crawler/crawling/distributed_scheduler.py | DistributedScheduler.load_domain_config | def load_domain_config(self, loaded_config):
'''
Loads the domain_config and sets up queue_dict
@param loaded_config: the yaml loaded config dict from zookeeper
'''
self.domain_config = {}
# vetting process to ensure correct configs
if loaded_config:
if 'domains' in loaded_config:
for domain in loaded_config['domains']:
item = loaded_config['domains'][domain]
# check valid
if 'window' in item and 'hits' in item:
self.logger.debug("Added domain {dom} to loaded config"
.format(dom=domain))
self.domain_config[domain] = item
if 'blacklist' in loaded_config:
self.black_domains = loaded_config['blacklist']
self.config_flag = True | python | def load_domain_config(self, loaded_config):
'''
Loads the domain_config and sets up queue_dict
@param loaded_config: the yaml loaded config dict from zookeeper
'''
self.domain_config = {}
# vetting process to ensure correct configs
if loaded_config:
if 'domains' in loaded_config:
for domain in loaded_config['domains']:
item = loaded_config['domains'][domain]
# check valid
if 'window' in item and 'hits' in item:
self.logger.debug("Added domain {dom} to loaded config"
.format(dom=domain))
self.domain_config[domain] = item
if 'blacklist' in loaded_config:
self.black_domains = loaded_config['blacklist']
self.config_flag = True | [
"def",
"load_domain_config",
"(",
"self",
",",
"loaded_config",
")",
":",
"self",
".",
"domain_config",
"=",
"{",
"}",
"# vetting process to ensure correct configs",
"if",
"loaded_config",
":",
"if",
"'domains'",
"in",
"loaded_config",
":",
"for",
"domain",
"in",
... | Loads the domain_config and sets up queue_dict
@param loaded_config: the yaml loaded config dict from zookeeper | [
"Loads",
"the",
"domain_config",
"and",
"sets",
"up",
"queue_dict"
] | 13aaed2349af5d792d6bcbfcadc5563158aeb599 | https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/crawler/crawling/distributed_scheduler.py#L130-L149 | train | 215,467 |
istresearch/scrapy-cluster | crawler/crawling/distributed_scheduler.py | DistributedScheduler.update_domain_queues | def update_domain_queues(self):
'''
Check to update existing queues already in memory
new queues are created elsewhere
'''
for key in self.domain_config:
final_key = "{name}:{domain}:queue".format(
name=self.spider.name,
domain=key)
# we already have a throttled queue for this domain, update it to new settings
if final_key in self.queue_dict:
self.queue_dict[final_key][0].window = float(self.domain_config[key]['window'])
self.logger.debug("Updated queue {q} with new config"
.format(q=final_key))
# if scale is applied, scale back; otherwise use updated hits
if 'scale' in self.domain_config[key]:
# round to int
hits = int(self.domain_config[key]['hits'] * self.fit_scale(
self.domain_config[key]['scale']))
self.queue_dict[final_key][0].limit = float(hits)
else:
self.queue_dict[final_key][0].limit = float(self.domain_config[key]['hits']) | python | def update_domain_queues(self):
'''
Check to update existing queues already in memory
new queues are created elsewhere
'''
for key in self.domain_config:
final_key = "{name}:{domain}:queue".format(
name=self.spider.name,
domain=key)
# we already have a throttled queue for this domain, update it to new settings
if final_key in self.queue_dict:
self.queue_dict[final_key][0].window = float(self.domain_config[key]['window'])
self.logger.debug("Updated queue {q} with new config"
.format(q=final_key))
# if scale is applied, scale back; otherwise use updated hits
if 'scale' in self.domain_config[key]:
# round to int
hits = int(self.domain_config[key]['hits'] * self.fit_scale(
self.domain_config[key]['scale']))
self.queue_dict[final_key][0].limit = float(hits)
else:
self.queue_dict[final_key][0].limit = float(self.domain_config[key]['hits']) | [
"def",
"update_domain_queues",
"(",
"self",
")",
":",
"for",
"key",
"in",
"self",
".",
"domain_config",
":",
"final_key",
"=",
"\"{name}:{domain}:queue\"",
".",
"format",
"(",
"name",
"=",
"self",
".",
"spider",
".",
"name",
",",
"domain",
"=",
"key",
")",... | Check to update existing queues already in memory
new queues are created elsewhere | [
"Check",
"to",
"update",
"existing",
"queues",
"already",
"in",
"memory",
"new",
"queues",
"are",
"created",
"elsewhere"
] | 13aaed2349af5d792d6bcbfcadc5563158aeb599 | https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/crawler/crawling/distributed_scheduler.py#L151-L172 | train | 215,468 |
istresearch/scrapy-cluster | crawler/crawling/distributed_scheduler.py | DistributedScheduler.create_queues | def create_queues(self):
'''
Updates the in memory list of the redis queues
Creates new throttled queue instances if it does not have them
'''
# new config could have loaded between scrapes
newConf = self.check_config()
self.queue_keys = self.redis_conn.keys(self.spider.name + ":*:queue")
for key in self.queue_keys:
# build final queue key, depending on type and ip bools
throttle_key = ""
if self.add_type:
throttle_key = self.spider.name + ":"
if self.add_ip:
throttle_key = throttle_key + self.my_ip + ":"
# add the tld from the key `type:tld:queue`
the_domain = re.split(':', key)[1]
throttle_key = throttle_key + the_domain
if key not in self.queue_dict or newConf:
self.logger.debug("Added new Throttled Queue {q}"
.format(q=key))
q = RedisPriorityQueue(self.redis_conn, key, encoding=ujson)
# use default window and hits
if the_domain not in self.domain_config:
# this is now a tuple, all access needs to use [0] to get
# the object, use [1] to get the time
self.queue_dict[key] = [RedisThrottledQueue(self.redis_conn,
q, self.window, self.hits, self.moderated, throttle_key,
throttle_key, True), time.time()]
# use custom window and hits
else:
window = self.domain_config[the_domain]['window']
hits = self.domain_config[the_domain]['hits']
# adjust the crawl rate based on the scale if exists
if 'scale' in self.domain_config[the_domain]:
hits = int(hits * self.fit_scale(self.domain_config[the_domain]['scale']))
self.queue_dict[key] = [RedisThrottledQueue(self.redis_conn,
q, window, hits, self.moderated, throttle_key,
throttle_key, True), time.time()] | python | def create_queues(self):
'''
Updates the in memory list of the redis queues
Creates new throttled queue instances if it does not have them
'''
# new config could have loaded between scrapes
newConf = self.check_config()
self.queue_keys = self.redis_conn.keys(self.spider.name + ":*:queue")
for key in self.queue_keys:
# build final queue key, depending on type and ip bools
throttle_key = ""
if self.add_type:
throttle_key = self.spider.name + ":"
if self.add_ip:
throttle_key = throttle_key + self.my_ip + ":"
# add the tld from the key `type:tld:queue`
the_domain = re.split(':', key)[1]
throttle_key = throttle_key + the_domain
if key not in self.queue_dict or newConf:
self.logger.debug("Added new Throttled Queue {q}"
.format(q=key))
q = RedisPriorityQueue(self.redis_conn, key, encoding=ujson)
# use default window and hits
if the_domain not in self.domain_config:
# this is now a tuple, all access needs to use [0] to get
# the object, use [1] to get the time
self.queue_dict[key] = [RedisThrottledQueue(self.redis_conn,
q, self.window, self.hits, self.moderated, throttle_key,
throttle_key, True), time.time()]
# use custom window and hits
else:
window = self.domain_config[the_domain]['window']
hits = self.domain_config[the_domain]['hits']
# adjust the crawl rate based on the scale if exists
if 'scale' in self.domain_config[the_domain]:
hits = int(hits * self.fit_scale(self.domain_config[the_domain]['scale']))
self.queue_dict[key] = [RedisThrottledQueue(self.redis_conn,
q, window, hits, self.moderated, throttle_key,
throttle_key, True), time.time()] | [
"def",
"create_queues",
"(",
"self",
")",
":",
"# new config could have loaded between scrapes",
"newConf",
"=",
"self",
".",
"check_config",
"(",
")",
"self",
".",
"queue_keys",
"=",
"self",
".",
"redis_conn",
".",
"keys",
"(",
"self",
".",
"spider",
".",
"na... | Updates the in memory list of the redis queues
Creates new throttled queue instances if it does not have them | [
"Updates",
"the",
"in",
"memory",
"list",
"of",
"the",
"redis",
"queues",
"Creates",
"new",
"throttled",
"queue",
"instances",
"if",
"it",
"does",
"not",
"have",
"them"
] | 13aaed2349af5d792d6bcbfcadc5563158aeb599 | https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/crawler/crawling/distributed_scheduler.py#L202-L248 | train | 215,469 |
istresearch/scrapy-cluster | crawler/crawling/distributed_scheduler.py | DistributedScheduler.expire_queues | def expire_queues(self):
'''
Expires old queue_dict keys that have not been used in a long time.
Prevents slow memory build up when crawling lots of different domains
'''
curr_time = time.time()
for key in list(self.queue_dict):
diff = curr_time - self.queue_dict[key][1]
if diff > self.queue_timeout:
self.logger.debug("Expiring domain queue key " + key)
del self.queue_dict[key]
if key in self.queue_keys:
self.queue_keys.remove(key) | python | def expire_queues(self):
'''
Expires old queue_dict keys that have not been used in a long time.
Prevents slow memory build up when crawling lots of different domains
'''
curr_time = time.time()
for key in list(self.queue_dict):
diff = curr_time - self.queue_dict[key][1]
if diff > self.queue_timeout:
self.logger.debug("Expiring domain queue key " + key)
del self.queue_dict[key]
if key in self.queue_keys:
self.queue_keys.remove(key) | [
"def",
"expire_queues",
"(",
"self",
")",
":",
"curr_time",
"=",
"time",
".",
"time",
"(",
")",
"for",
"key",
"in",
"list",
"(",
"self",
".",
"queue_dict",
")",
":",
"diff",
"=",
"curr_time",
"-",
"self",
".",
"queue_dict",
"[",
"key",
"]",
"[",
"1... | Expires old queue_dict keys that have not been used in a long time.
Prevents slow memory build up when crawling lots of different domains | [
"Expires",
"old",
"queue_dict",
"keys",
"that",
"have",
"not",
"been",
"used",
"in",
"a",
"long",
"time",
".",
"Prevents",
"slow",
"memory",
"build",
"up",
"when",
"crawling",
"lots",
"of",
"different",
"domains"
] | 13aaed2349af5d792d6bcbfcadc5563158aeb599 | https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/crawler/crawling/distributed_scheduler.py#L250-L262 | train | 215,470 |
istresearch/scrapy-cluster | crawler/crawling/distributed_scheduler.py | DistributedScheduler.update_ipaddress | def update_ipaddress(self):
'''
Updates the scheduler so it knows its own ip address
'''
# assign local ip in case of exception
self.old_ip = self.my_ip
self.my_ip = '127.0.0.1'
try:
obj = urllib.request.urlopen(settings.get('PUBLIC_IP_URL',
'http://ip.42.pl/raw'))
results = self.ip_regex.findall(obj.read())
if len(results) > 0:
self.my_ip = results[0]
else:
raise IOError("Could not get valid IP Address")
obj.close()
self.logger.debug("Current public ip: {ip}".format(ip=self.my_ip))
except IOError:
self.logger.error("Could not reach out to get public ip")
pass
if self.old_ip != self.my_ip:
self.logger.info("Changed Public IP: {old} -> {new}".format(
old=self.old_ip, new=self.my_ip)) | python | def update_ipaddress(self):
'''
Updates the scheduler so it knows its own ip address
'''
# assign local ip in case of exception
self.old_ip = self.my_ip
self.my_ip = '127.0.0.1'
try:
obj = urllib.request.urlopen(settings.get('PUBLIC_IP_URL',
'http://ip.42.pl/raw'))
results = self.ip_regex.findall(obj.read())
if len(results) > 0:
self.my_ip = results[0]
else:
raise IOError("Could not get valid IP Address")
obj.close()
self.logger.debug("Current public ip: {ip}".format(ip=self.my_ip))
except IOError:
self.logger.error("Could not reach out to get public ip")
pass
if self.old_ip != self.my_ip:
self.logger.info("Changed Public IP: {old} -> {new}".format(
old=self.old_ip, new=self.my_ip)) | [
"def",
"update_ipaddress",
"(",
"self",
")",
":",
"# assign local ip in case of exception",
"self",
".",
"old_ip",
"=",
"self",
".",
"my_ip",
"self",
".",
"my_ip",
"=",
"'127.0.0.1'",
"try",
":",
"obj",
"=",
"urllib",
".",
"request",
".",
"urlopen",
"(",
"se... | Updates the scheduler so it knows its own ip address | [
"Updates",
"the",
"scheduler",
"so",
"it",
"knows",
"its",
"own",
"ip",
"address"
] | 13aaed2349af5d792d6bcbfcadc5563158aeb599 | https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/crawler/crawling/distributed_scheduler.py#L275-L298 | train | 215,471 |
istresearch/scrapy-cluster | crawler/crawling/distributed_scheduler.py | DistributedScheduler.is_blacklisted | def is_blacklisted(self, appid, crawlid):
'''
Checks the redis blacklist for crawls that should not be propagated
either from expiring or stopped
@return: True if the appid crawlid combo is blacklisted
'''
key_check = '{appid}||{crawlid}'.format(appid=appid,
crawlid=crawlid)
redis_key = self.spider.name + ":blacklist"
return self.redis_conn.sismember(redis_key, key_check) | python | def is_blacklisted(self, appid, crawlid):
'''
Checks the redis blacklist for crawls that should not be propagated
either from expiring or stopped
@return: True if the appid crawlid combo is blacklisted
'''
key_check = '{appid}||{crawlid}'.format(appid=appid,
crawlid=crawlid)
redis_key = self.spider.name + ":blacklist"
return self.redis_conn.sismember(redis_key, key_check) | [
"def",
"is_blacklisted",
"(",
"self",
",",
"appid",
",",
"crawlid",
")",
":",
"key_check",
"=",
"'{appid}||{crawlid}'",
".",
"format",
"(",
"appid",
"=",
"appid",
",",
"crawlid",
"=",
"crawlid",
")",
"redis_key",
"=",
"self",
".",
"spider",
".",
"name",
... | Checks the redis blacklist for crawls that should not be propagated
either from expiring or stopped
@return: True if the appid crawlid combo is blacklisted | [
"Checks",
"the",
"redis",
"blacklist",
"for",
"crawls",
"that",
"should",
"not",
"be",
"propagated",
"either",
"from",
"expiring",
"or",
"stopped"
] | 13aaed2349af5d792d6bcbfcadc5563158aeb599 | https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/crawler/crawling/distributed_scheduler.py#L375-L384 | train | 215,472 |
istresearch/scrapy-cluster | crawler/crawling/distributed_scheduler.py | DistributedScheduler.enqueue_request | def enqueue_request(self, request):
'''
Pushes a request from the spider into the proper throttled queue
'''
if not request.dont_filter and self.dupefilter.request_seen(request):
self.logger.debug("Request not added back to redis")
return
req_dict = self.request_to_dict(request)
if not self.is_blacklisted(req_dict['meta']['appid'],
req_dict['meta']['crawlid']):
# grab the tld of the request
ex_res = self.extract(req_dict['url'])
key = "{sid}:{dom}.{suf}:queue".format(
sid=req_dict['meta']['spiderid'],
dom=ex_res.domain,
suf=ex_res.suffix)
curr_time = time.time()
domain = "{d}.{s}".format(d=ex_res.domain, s=ex_res.suffix)
# allow only if we want all requests or we want
# everything but blacklisted domains
# insert if crawl never expires (0) or time < expires
if (self.backlog_blacklist or
(not self.backlog_blacklist and
domain not in self.black_domains)) and \
(req_dict['meta']['expires'] == 0 or
curr_time < req_dict['meta']['expires']):
# we may already have the queue in memory
if key in self.queue_keys:
self.queue_dict[key][0].push(req_dict,
req_dict['meta']['priority'])
else:
# shoving into a new redis queue, negative b/c of sorted sets
# this will populate ourself and other schedulers when
# they call create_queues
self.redis_conn.zadd(key, ujson.dumps(req_dict),
-req_dict['meta']['priority'])
self.logger.debug("Crawlid: '{id}' Appid: '{appid}' added to queue"
.format(appid=req_dict['meta']['appid'],
id=req_dict['meta']['crawlid']))
else:
self.logger.debug("Crawlid: '{id}' Appid: '{appid}' expired"
.format(appid=req_dict['meta']['appid'],
id=req_dict['meta']['crawlid']))
else:
self.logger.debug("Crawlid: '{id}' Appid: '{appid}' blacklisted"
.format(appid=req_dict['meta']['appid'],
id=req_dict['meta']['crawlid'])) | python | def enqueue_request(self, request):
'''
Pushes a request from the spider into the proper throttled queue
'''
if not request.dont_filter and self.dupefilter.request_seen(request):
self.logger.debug("Request not added back to redis")
return
req_dict = self.request_to_dict(request)
if not self.is_blacklisted(req_dict['meta']['appid'],
req_dict['meta']['crawlid']):
# grab the tld of the request
ex_res = self.extract(req_dict['url'])
key = "{sid}:{dom}.{suf}:queue".format(
sid=req_dict['meta']['spiderid'],
dom=ex_res.domain,
suf=ex_res.suffix)
curr_time = time.time()
domain = "{d}.{s}".format(d=ex_res.domain, s=ex_res.suffix)
# allow only if we want all requests or we want
# everything but blacklisted domains
# insert if crawl never expires (0) or time < expires
if (self.backlog_blacklist or
(not self.backlog_blacklist and
domain not in self.black_domains)) and \
(req_dict['meta']['expires'] == 0 or
curr_time < req_dict['meta']['expires']):
# we may already have the queue in memory
if key in self.queue_keys:
self.queue_dict[key][0].push(req_dict,
req_dict['meta']['priority'])
else:
# shoving into a new redis queue, negative b/c of sorted sets
# this will populate ourself and other schedulers when
# they call create_queues
self.redis_conn.zadd(key, ujson.dumps(req_dict),
-req_dict['meta']['priority'])
self.logger.debug("Crawlid: '{id}' Appid: '{appid}' added to queue"
.format(appid=req_dict['meta']['appid'],
id=req_dict['meta']['crawlid']))
else:
self.logger.debug("Crawlid: '{id}' Appid: '{appid}' expired"
.format(appid=req_dict['meta']['appid'],
id=req_dict['meta']['crawlid']))
else:
self.logger.debug("Crawlid: '{id}' Appid: '{appid}' blacklisted"
.format(appid=req_dict['meta']['appid'],
id=req_dict['meta']['crawlid'])) | [
"def",
"enqueue_request",
"(",
"self",
",",
"request",
")",
":",
"if",
"not",
"request",
".",
"dont_filter",
"and",
"self",
".",
"dupefilter",
".",
"request_seen",
"(",
"request",
")",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"\"Request not added back ... | Pushes a request from the spider into the proper throttled queue | [
"Pushes",
"a",
"request",
"from",
"the",
"spider",
"into",
"the",
"proper",
"throttled",
"queue"
] | 13aaed2349af5d792d6bcbfcadc5563158aeb599 | https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/crawler/crawling/distributed_scheduler.py#L386-L436 | train | 215,473 |
istresearch/scrapy-cluster | crawler/crawling/distributed_scheduler.py | DistributedScheduler.request_to_dict | def request_to_dict(self, request):
'''
Convert Request object to a dict.
modified from scrapy.utils.reqser
'''
req_dict = {
# urls should be safe (safe_string_url)
'url': to_unicode(request.url),
'method': request.method,
'headers': dict(request.headers),
'body': request.body,
'cookies': request.cookies,
'meta': request.meta,
'_encoding': request._encoding,
'priority': request.priority,
'dont_filter': request.dont_filter,
# callback/errback are assumed to be a bound instance of the spider
'callback': None if request.callback is None else request.callback.__name__,
'errback': None if request.errback is None else request.errback.__name__,
}
return req_dict | python | def request_to_dict(self, request):
'''
Convert Request object to a dict.
modified from scrapy.utils.reqser
'''
req_dict = {
# urls should be safe (safe_string_url)
'url': to_unicode(request.url),
'method': request.method,
'headers': dict(request.headers),
'body': request.body,
'cookies': request.cookies,
'meta': request.meta,
'_encoding': request._encoding,
'priority': request.priority,
'dont_filter': request.dont_filter,
# callback/errback are assumed to be a bound instance of the spider
'callback': None if request.callback is None else request.callback.__name__,
'errback': None if request.errback is None else request.errback.__name__,
}
return req_dict | [
"def",
"request_to_dict",
"(",
"self",
",",
"request",
")",
":",
"req_dict",
"=",
"{",
"# urls should be safe (safe_string_url)",
"'url'",
":",
"to_unicode",
"(",
"request",
".",
"url",
")",
",",
"'method'",
":",
"request",
".",
"method",
",",
"'headers'",
":"... | Convert Request object to a dict.
modified from scrapy.utils.reqser | [
"Convert",
"Request",
"object",
"to",
"a",
"dict",
".",
"modified",
"from",
"scrapy",
".",
"utils",
".",
"reqser"
] | 13aaed2349af5d792d6bcbfcadc5563158aeb599 | https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/crawler/crawling/distributed_scheduler.py#L438-L458 | train | 215,474 |
istresearch/scrapy-cluster | crawler/crawling/distributed_scheduler.py | DistributedScheduler.find_item | def find_item(self):
'''
Finds an item from the throttled queues
'''
random.shuffle(self.queue_keys)
count = 0
while count <= self.item_retries:
for key in self.queue_keys:
# skip if the whole domain has been blacklisted in zookeeper
if key.split(':')[1] in self.black_domains:
continue
# the throttled queue only returns an item if it is allowed
item = self.queue_dict[key][0].pop()
if item:
# update timeout and return
self.queue_dict[key][1] = time.time()
return item
count = count + 1
return None | python | def find_item(self):
'''
Finds an item from the throttled queues
'''
random.shuffle(self.queue_keys)
count = 0
while count <= self.item_retries:
for key in self.queue_keys:
# skip if the whole domain has been blacklisted in zookeeper
if key.split(':')[1] in self.black_domains:
continue
# the throttled queue only returns an item if it is allowed
item = self.queue_dict[key][0].pop()
if item:
# update timeout and return
self.queue_dict[key][1] = time.time()
return item
count = count + 1
return None | [
"def",
"find_item",
"(",
"self",
")",
":",
"random",
".",
"shuffle",
"(",
"self",
".",
"queue_keys",
")",
"count",
"=",
"0",
"while",
"count",
"<=",
"self",
".",
"item_retries",
":",
"for",
"key",
"in",
"self",
".",
"queue_keys",
":",
"# skip if the whol... | Finds an item from the throttled queues | [
"Finds",
"an",
"item",
"from",
"the",
"throttled",
"queues"
] | 13aaed2349af5d792d6bcbfcadc5563158aeb599 | https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/crawler/crawling/distributed_scheduler.py#L460-L482 | train | 215,475 |
istresearch/scrapy-cluster | crawler/crawling/distributed_scheduler.py | DistributedScheduler.next_request | def next_request(self):
'''
Logic to handle getting a new url request, from a bunch of
different queues
'''
t = time.time()
# update the redis queues every so often
if t - self.update_time > self.update_interval:
self.update_time = t
self.create_queues()
self.expire_queues()
# update the ip address every so often
if t - self.update_ip_time > self.ip_update_interval:
self.update_ip_time = t
self.update_ipaddress()
self.report_self()
item = self.find_item()
if item:
self.logger.debug("Found url to crawl {url}" \
.format(url=item['url']))
try:
req = Request(item['url'])
except ValueError:
# need absolute url
# need better url validation here
req = Request('http://' + item['url'])
try:
if 'callback' in item and item['callback'] is not None:
req.callback = getattr(self.spider, item['callback'])
except AttributeError:
self.logger.warn("Unable to find callback method")
try:
if 'errback' in item and item['errback'] is not None:
req.errback = getattr(self.spider, item['errback'])
except AttributeError:
self.logger.warn("Unable to find errback method")
if 'meta' in item:
item = item['meta']
# defaults not in schema
if 'curdepth' not in item:
item['curdepth'] = 0
if "retry_times" not in item:
item['retry_times'] = 0
for key in list(item.keys()):
req.meta[key] = item[key]
# extra check to add items to request
if 'useragent' in item and item['useragent'] is not None:
req.headers['User-Agent'] = item['useragent']
if 'cookie' in item and item['cookie'] is not None:
if isinstance(item['cookie'], dict):
req.cookies = item['cookie']
elif isinstance(item['cookie'], basestring):
req.cookies = self.parse_cookie(item['cookie'])
return req
return None | python | def next_request(self):
'''
Logic to handle getting a new url request, from a bunch of
different queues
'''
t = time.time()
# update the redis queues every so often
if t - self.update_time > self.update_interval:
self.update_time = t
self.create_queues()
self.expire_queues()
# update the ip address every so often
if t - self.update_ip_time > self.ip_update_interval:
self.update_ip_time = t
self.update_ipaddress()
self.report_self()
item = self.find_item()
if item:
self.logger.debug("Found url to crawl {url}" \
.format(url=item['url']))
try:
req = Request(item['url'])
except ValueError:
# need absolute url
# need better url validation here
req = Request('http://' + item['url'])
try:
if 'callback' in item and item['callback'] is not None:
req.callback = getattr(self.spider, item['callback'])
except AttributeError:
self.logger.warn("Unable to find callback method")
try:
if 'errback' in item and item['errback'] is not None:
req.errback = getattr(self.spider, item['errback'])
except AttributeError:
self.logger.warn("Unable to find errback method")
if 'meta' in item:
item = item['meta']
# defaults not in schema
if 'curdepth' not in item:
item['curdepth'] = 0
if "retry_times" not in item:
item['retry_times'] = 0
for key in list(item.keys()):
req.meta[key] = item[key]
# extra check to add items to request
if 'useragent' in item and item['useragent'] is not None:
req.headers['User-Agent'] = item['useragent']
if 'cookie' in item and item['cookie'] is not None:
if isinstance(item['cookie'], dict):
req.cookies = item['cookie']
elif isinstance(item['cookie'], basestring):
req.cookies = self.parse_cookie(item['cookie'])
return req
return None | [
"def",
"next_request",
"(",
"self",
")",
":",
"t",
"=",
"time",
".",
"time",
"(",
")",
"# update the redis queues every so often",
"if",
"t",
"-",
"self",
".",
"update_time",
">",
"self",
".",
"update_interval",
":",
"self",
".",
"update_time",
"=",
"t",
"... | Logic to handle getting a new url request, from a bunch of
different queues | [
"Logic",
"to",
"handle",
"getting",
"a",
"new",
"url",
"request",
"from",
"a",
"bunch",
"of",
"different",
"queues"
] | 13aaed2349af5d792d6bcbfcadc5563158aeb599 | https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/crawler/crawling/distributed_scheduler.py#L484-L548 | train | 215,476 |
istresearch/scrapy-cluster | crawler/crawling/distributed_scheduler.py | DistributedScheduler.parse_cookie | def parse_cookie(self, string):
'''
Parses a cookie string like returned in a Set-Cookie header
@param string: The cookie string
@return: the cookie dict
'''
results = re.findall('([^=]+)=([^\;]+);?\s?', string)
my_dict = {}
for item in results:
my_dict[item[0]] = item[1]
return my_dict | python | def parse_cookie(self, string):
'''
Parses a cookie string like returned in a Set-Cookie header
@param string: The cookie string
@return: the cookie dict
'''
results = re.findall('([^=]+)=([^\;]+);?\s?', string)
my_dict = {}
for item in results:
my_dict[item[0]] = item[1]
return my_dict | [
"def",
"parse_cookie",
"(",
"self",
",",
"string",
")",
":",
"results",
"=",
"re",
".",
"findall",
"(",
"'([^=]+)=([^\\;]+);?\\s?'",
",",
"string",
")",
"my_dict",
"=",
"{",
"}",
"for",
"item",
"in",
"results",
":",
"my_dict",
"[",
"item",
"[",
"0",
"]... | Parses a cookie string like returned in a Set-Cookie header
@param string: The cookie string
@return: the cookie dict | [
"Parses",
"a",
"cookie",
"string",
"like",
"returned",
"in",
"a",
"Set",
"-",
"Cookie",
"header"
] | 13aaed2349af5d792d6bcbfcadc5563158aeb599 | https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/crawler/crawling/distributed_scheduler.py#L550-L561 | train | 215,477 |
istresearch/scrapy-cluster | crawler/crawling/pipelines.py | KafkaPipeline._clean_item | def _clean_item(self, item):
'''
Cleans the item to be logged
'''
item_copy = dict(item)
del item_copy['body']
del item_copy['links']
del item_copy['response_headers']
del item_copy['request_headers']
del item_copy['status_code']
del item_copy['status_msg']
item_copy['action'] = 'ack'
item_copy['logger'] = self.logger.name
item_copy
return item_copy | python | def _clean_item(self, item):
'''
Cleans the item to be logged
'''
item_copy = dict(item)
del item_copy['body']
del item_copy['links']
del item_copy['response_headers']
del item_copy['request_headers']
del item_copy['status_code']
del item_copy['status_msg']
item_copy['action'] = 'ack'
item_copy['logger'] = self.logger.name
item_copy
return item_copy | [
"def",
"_clean_item",
"(",
"self",
",",
"item",
")",
":",
"item_copy",
"=",
"dict",
"(",
"item",
")",
"del",
"item_copy",
"[",
"'body'",
"]",
"del",
"item_copy",
"[",
"'links'",
"]",
"del",
"item_copy",
"[",
"'response_headers'",
"]",
"del",
"item_copy",
... | Cleans the item to be logged | [
"Cleans",
"the",
"item",
"to",
"be",
"logged"
] | 13aaed2349af5d792d6bcbfcadc5563158aeb599 | https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/crawler/crawling/pipelines.py#L138-L153 | train | 215,478 |
istresearch/scrapy-cluster | crawler/crawling/pipelines.py | KafkaPipeline._kafka_success | def _kafka_success(self, item, spider, response):
'''
Callback for successful send
'''
item['success'] = True
item = self._clean_item(item)
item['spiderid'] = spider.name
self.logger.info("Sent page to Kafka", item) | python | def _kafka_success(self, item, spider, response):
'''
Callback for successful send
'''
item['success'] = True
item = self._clean_item(item)
item['spiderid'] = spider.name
self.logger.info("Sent page to Kafka", item) | [
"def",
"_kafka_success",
"(",
"self",
",",
"item",
",",
"spider",
",",
"response",
")",
":",
"item",
"[",
"'success'",
"]",
"=",
"True",
"item",
"=",
"self",
".",
"_clean_item",
"(",
"item",
")",
"item",
"[",
"'spiderid'",
"]",
"=",
"spider",
".",
"n... | Callback for successful send | [
"Callback",
"for",
"successful",
"send"
] | 13aaed2349af5d792d6bcbfcadc5563158aeb599 | https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/crawler/crawling/pipelines.py#L155-L162 | train | 215,479 |
istresearch/scrapy-cluster | crawler/crawling/pipelines.py | KafkaPipeline._kafka_failure | def _kafka_failure(self, item, spider, response):
'''
Callback for failed send
'''
item['success'] = False
item['exception'] = traceback.format_exc()
item['spiderid'] = spider.name
item = self._clean_item(item)
self.logger.error("Failed to send page to Kafka", item) | python | def _kafka_failure(self, item, spider, response):
'''
Callback for failed send
'''
item['success'] = False
item['exception'] = traceback.format_exc()
item['spiderid'] = spider.name
item = self._clean_item(item)
self.logger.error("Failed to send page to Kafka", item) | [
"def",
"_kafka_failure",
"(",
"self",
",",
"item",
",",
"spider",
",",
"response",
")",
":",
"item",
"[",
"'success'",
"]",
"=",
"False",
"item",
"[",
"'exception'",
"]",
"=",
"traceback",
".",
"format_exc",
"(",
")",
"item",
"[",
"'spiderid'",
"]",
"=... | Callback for failed send | [
"Callback",
"for",
"failed",
"send"
] | 13aaed2349af5d792d6bcbfcadc5563158aeb599 | https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/crawler/crawling/pipelines.py#L165-L173 | train | 215,480 |
istresearch/scrapy-cluster | crawler/crawling/spiders/redis_spider.py | RedisSpider.reconstruct_headers | def reconstruct_headers(self, response):
"""
Purpose of this method is to reconstruct the headers dictionary that
is normally passed in with a "response" object from scrapy.
Args:
response: A scrapy response object
Returns: A dictionary that mirrors the "response.headers" dictionary
that is normally within a response object
Raises: None
Reason: Originally, there was a bug where the json.dumps() did not
properly serialize the headers. This method is a way to circumvent
the known issue
"""
header_dict = {}
# begin reconstructing headers from scratch...
for key in list(response.headers.keys()):
key_item_list = []
key_list = response.headers.getlist(key)
for item in key_list:
key_item_list.append(item)
header_dict[key] = key_item_list
return header_dict | python | def reconstruct_headers(self, response):
"""
Purpose of this method is to reconstruct the headers dictionary that
is normally passed in with a "response" object from scrapy.
Args:
response: A scrapy response object
Returns: A dictionary that mirrors the "response.headers" dictionary
that is normally within a response object
Raises: None
Reason: Originally, there was a bug where the json.dumps() did not
properly serialize the headers. This method is a way to circumvent
the known issue
"""
header_dict = {}
# begin reconstructing headers from scratch...
for key in list(response.headers.keys()):
key_item_list = []
key_list = response.headers.getlist(key)
for item in key_list:
key_item_list.append(item)
header_dict[key] = key_item_list
return header_dict | [
"def",
"reconstruct_headers",
"(",
"self",
",",
"response",
")",
":",
"header_dict",
"=",
"{",
"}",
"# begin reconstructing headers from scratch...",
"for",
"key",
"in",
"list",
"(",
"response",
".",
"headers",
".",
"keys",
"(",
")",
")",
":",
"key_item_list",
... | Purpose of this method is to reconstruct the headers dictionary that
is normally passed in with a "response" object from scrapy.
Args:
response: A scrapy response object
Returns: A dictionary that mirrors the "response.headers" dictionary
that is normally within a response object
Raises: None
Reason: Originally, there was a bug where the json.dumps() did not
properly serialize the headers. This method is a way to circumvent
the known issue | [
"Purpose",
"of",
"this",
"method",
"is",
"to",
"reconstruct",
"the",
"headers",
"dictionary",
"that",
"is",
"normally",
"passed",
"in",
"with",
"a",
"response",
"object",
"from",
"scrapy",
"."
] | 13aaed2349af5d792d6bcbfcadc5563158aeb599 | https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/crawler/crawling/spiders/redis_spider.py#L36-L61 | train | 215,481 |
istresearch/scrapy-cluster | kafka-monitor/plugins/scraper_handler.py | ScraperHandler.handle | def handle(self, dict):
'''
Processes a vaild crawl request
@param dict: a valid dictionary object
'''
# format key
ex_res = self.extract(dict['url'])
key = "{sid}:{dom}.{suf}:queue".format(
sid=dict['spiderid'],
dom=ex_res.domain,
suf=ex_res.suffix)
val = ujson.dumps(dict)
# shortcut to shove stuff into the priority queue
self.redis_conn.zadd(key, val, -dict['priority'])
# if timeout crawl, add value to redis
if 'expires' in dict and dict['expires'] != 0:
key = "timeout:{sid}:{appid}:{crawlid}".format(
sid=dict['spiderid'],
appid=dict['appid'],
crawlid=dict['crawlid'])
self.redis_conn.set(key, dict['expires'])
# log success
dict['parsed'] = True
dict['valid'] = True
self.logger.info('Added crawl to Redis', extra=dict) | python | def handle(self, dict):
'''
Processes a vaild crawl request
@param dict: a valid dictionary object
'''
# format key
ex_res = self.extract(dict['url'])
key = "{sid}:{dom}.{suf}:queue".format(
sid=dict['spiderid'],
dom=ex_res.domain,
suf=ex_res.suffix)
val = ujson.dumps(dict)
# shortcut to shove stuff into the priority queue
self.redis_conn.zadd(key, val, -dict['priority'])
# if timeout crawl, add value to redis
if 'expires' in dict and dict['expires'] != 0:
key = "timeout:{sid}:{appid}:{crawlid}".format(
sid=dict['spiderid'],
appid=dict['appid'],
crawlid=dict['crawlid'])
self.redis_conn.set(key, dict['expires'])
# log success
dict['parsed'] = True
dict['valid'] = True
self.logger.info('Added crawl to Redis', extra=dict) | [
"def",
"handle",
"(",
"self",
",",
"dict",
")",
":",
"# format key",
"ex_res",
"=",
"self",
".",
"extract",
"(",
"dict",
"[",
"'url'",
"]",
")",
"key",
"=",
"\"{sid}:{dom}.{suf}:queue\"",
".",
"format",
"(",
"sid",
"=",
"dict",
"[",
"'spiderid'",
"]",
... | Processes a vaild crawl request
@param dict: a valid dictionary object | [
"Processes",
"a",
"vaild",
"crawl",
"request"
] | 13aaed2349af5d792d6bcbfcadc5563158aeb599 | https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/kafka-monitor/plugins/scraper_handler.py#L31-L60 | train | 215,482 |
istresearch/scrapy-cluster | utils/scutils/method_timer.py | MethodTimer.timeout | def timeout(timeout_time, default):
'''
Decorate a method so it is required to execute in a given time period,
or return a default value.
'''
def timeout_function(f):
def f2(*args):
def timeout_handler(signum, frame):
raise MethodTimer.DecoratorTimeout()
old_handler = signal.signal(signal.SIGALRM, timeout_handler)
# triger alarm in timeout_time seconds
signal.alarm(timeout_time)
try:
retval = f(*args)
except MethodTimer.DecoratorTimeout:
return default
finally:
signal.signal(signal.SIGALRM, old_handler)
signal.alarm(0)
return retval
return f2
return timeout_function | python | def timeout(timeout_time, default):
'''
Decorate a method so it is required to execute in a given time period,
or return a default value.
'''
def timeout_function(f):
def f2(*args):
def timeout_handler(signum, frame):
raise MethodTimer.DecoratorTimeout()
old_handler = signal.signal(signal.SIGALRM, timeout_handler)
# triger alarm in timeout_time seconds
signal.alarm(timeout_time)
try:
retval = f(*args)
except MethodTimer.DecoratorTimeout:
return default
finally:
signal.signal(signal.SIGALRM, old_handler)
signal.alarm(0)
return retval
return f2
return timeout_function | [
"def",
"timeout",
"(",
"timeout_time",
",",
"default",
")",
":",
"def",
"timeout_function",
"(",
"f",
")",
":",
"def",
"f2",
"(",
"*",
"args",
")",
":",
"def",
"timeout_handler",
"(",
"signum",
",",
"frame",
")",
":",
"raise",
"MethodTimer",
".",
"Deco... | Decorate a method so it is required to execute in a given time period,
or return a default value. | [
"Decorate",
"a",
"method",
"so",
"it",
"is",
"required",
"to",
"execute",
"in",
"a",
"given",
"time",
"period",
"or",
"return",
"a",
"default",
"value",
"."
] | 13aaed2349af5d792d6bcbfcadc5563158aeb599 | https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/utils/scutils/method_timer.py#L33-L55 | train | 215,483 |
istresearch/scrapy-cluster | crawler/crawling/redis_stats_middleware.py | RedisStatsMiddleware._setup_stats_status_codes | def _setup_stats_status_codes(self, spider_name):
'''
Sets up the status code stats collectors
'''
self.stats_dict[spider_name] = {
'status_codes': {}
}
self.stats_dict[spider_name]['status_codes'] = {}
hostname = self._get_hostname()
# we chose to handle 504's here as well as in the middleware
# in case the middleware is disabled
for status_code in self.settings['STATS_RESPONSE_CODES']:
temp_key = 'stats:crawler:{h}:{n}:{s}'.format(
h=hostname, n=spider_name, s=status_code)
self.stats_dict[spider_name]['status_codes'][status_code] = {}
for item in self.settings['STATS_TIMES']:
try:
time = getattr(StatsCollector, item)
self.stats_dict[spider_name]['status_codes'][status_code][time] = StatsCollector \
.get_rolling_time_window(
redis_conn=self.redis_conn,
key='{k}:{t}'.format(k=temp_key, t=time),
window=time,
cycle_time=self.settings['STATS_CYCLE'])
self.logger.debug("Set up status code {s}, {n} spider,"\
" host {h} Stats Collector '{i}'"\
.format(h=hostname, n=spider_name, s=status_code, i=item))
except AttributeError as e:
self.logger.warning("Unable to find Stats Time '{s}'"\
.format(s=item))
total = StatsCollector.get_hll_counter(redis_conn=self.redis_conn,
key='{k}:lifetime'.format(k=temp_key),
cycle_time=self.settings['STATS_CYCLE'],
roll=False)
self.logger.debug("Set up status code {s}, {n} spider,"\
"host {h} Stats Collector 'lifetime'"\
.format(h=hostname, n=spider_name, s=status_code))
self.stats_dict[spider_name]['status_codes'][status_code]['lifetime'] = total | python | def _setup_stats_status_codes(self, spider_name):
'''
Sets up the status code stats collectors
'''
self.stats_dict[spider_name] = {
'status_codes': {}
}
self.stats_dict[spider_name]['status_codes'] = {}
hostname = self._get_hostname()
# we chose to handle 504's here as well as in the middleware
# in case the middleware is disabled
for status_code in self.settings['STATS_RESPONSE_CODES']:
temp_key = 'stats:crawler:{h}:{n}:{s}'.format(
h=hostname, n=spider_name, s=status_code)
self.stats_dict[spider_name]['status_codes'][status_code] = {}
for item in self.settings['STATS_TIMES']:
try:
time = getattr(StatsCollector, item)
self.stats_dict[spider_name]['status_codes'][status_code][time] = StatsCollector \
.get_rolling_time_window(
redis_conn=self.redis_conn,
key='{k}:{t}'.format(k=temp_key, t=time),
window=time,
cycle_time=self.settings['STATS_CYCLE'])
self.logger.debug("Set up status code {s}, {n} spider,"\
" host {h} Stats Collector '{i}'"\
.format(h=hostname, n=spider_name, s=status_code, i=item))
except AttributeError as e:
self.logger.warning("Unable to find Stats Time '{s}'"\
.format(s=item))
total = StatsCollector.get_hll_counter(redis_conn=self.redis_conn,
key='{k}:lifetime'.format(k=temp_key),
cycle_time=self.settings['STATS_CYCLE'],
roll=False)
self.logger.debug("Set up status code {s}, {n} spider,"\
"host {h} Stats Collector 'lifetime'"\
.format(h=hostname, n=spider_name, s=status_code))
self.stats_dict[spider_name]['status_codes'][status_code]['lifetime'] = total | [
"def",
"_setup_stats_status_codes",
"(",
"self",
",",
"spider_name",
")",
":",
"self",
".",
"stats_dict",
"[",
"spider_name",
"]",
"=",
"{",
"'status_codes'",
":",
"{",
"}",
"}",
"self",
".",
"stats_dict",
"[",
"spider_name",
"]",
"[",
"'status_codes'",
"]",... | Sets up the status code stats collectors | [
"Sets",
"up",
"the",
"status",
"code",
"stats",
"collectors"
] | 13aaed2349af5d792d6bcbfcadc5563158aeb599 | https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/crawler/crawling/redis_stats_middleware.py#L66-L104 | train | 215,484 |
istresearch/scrapy-cluster | redis-monitor/plugins/kafka_base_monitor.py | KafkaBaseMonitor.setup | def setup(self, settings):
'''
Setup the handler
@param settings: The loaded settings file
'''
self.producer = self._create_producer(settings)
self.topic_prefix = settings['KAFKA_TOPIC_PREFIX']
self.use_appid_topics = settings['KAFKA_APPID_TOPICS']
self.logger.debug("Successfully connected to Kafka in {name}"
.format(name=self.__class__.__name__)) | python | def setup(self, settings):
'''
Setup the handler
@param settings: The loaded settings file
'''
self.producer = self._create_producer(settings)
self.topic_prefix = settings['KAFKA_TOPIC_PREFIX']
self.use_appid_topics = settings['KAFKA_APPID_TOPICS']
self.logger.debug("Successfully connected to Kafka in {name}"
.format(name=self.__class__.__name__)) | [
"def",
"setup",
"(",
"self",
",",
"settings",
")",
":",
"self",
".",
"producer",
"=",
"self",
".",
"_create_producer",
"(",
"settings",
")",
"self",
".",
"topic_prefix",
"=",
"settings",
"[",
"'KAFKA_TOPIC_PREFIX'",
"]",
"self",
".",
"use_appid_topics",
"=",... | Setup the handler
@param settings: The loaded settings file | [
"Setup",
"the",
"handler"
] | 13aaed2349af5d792d6bcbfcadc5563158aeb599 | https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/redis-monitor/plugins/kafka_base_monitor.py#L19-L31 | train | 215,485 |
istresearch/scrapy-cluster | redis-monitor/plugins/kafka_base_monitor.py | KafkaBaseMonitor._send_to_kafka | def _send_to_kafka(self, master):
'''
Sends the message back to Kafka
@param master: the final dict to send
@returns: True if successfully sent to kafka
'''
appid_topic = "{prefix}.outbound_{appid}".format(
prefix=self.topic_prefix,
appid=master['appid'])
firehose_topic = "{prefix}.outbound_firehose".format(
prefix=self.topic_prefix)
try:
# dont want logger in outbound kafka message
if self.use_appid_topics:
f1 = self.producer.send(appid_topic, master)
f1.add_callback(self._kafka_success)
f1.add_errback(self._kafka_failure)
f2 = self.producer.send(firehose_topic, master)
f2.add_callback(self._kafka_success)
f2.add_errback(self._kafka_failure)
return True
except Exception as ex:
message = "An exception '{0}' occured while sending a message " \
"to kafka. Arguments:\n{1!r}" \
.format(type(ex).__name__, ex.args)
self.logger.error(message)
return False | python | def _send_to_kafka(self, master):
'''
Sends the message back to Kafka
@param master: the final dict to send
@returns: True if successfully sent to kafka
'''
appid_topic = "{prefix}.outbound_{appid}".format(
prefix=self.topic_prefix,
appid=master['appid'])
firehose_topic = "{prefix}.outbound_firehose".format(
prefix=self.topic_prefix)
try:
# dont want logger in outbound kafka message
if self.use_appid_topics:
f1 = self.producer.send(appid_topic, master)
f1.add_callback(self._kafka_success)
f1.add_errback(self._kafka_failure)
f2 = self.producer.send(firehose_topic, master)
f2.add_callback(self._kafka_success)
f2.add_errback(self._kafka_failure)
return True
except Exception as ex:
message = "An exception '{0}' occured while sending a message " \
"to kafka. Arguments:\n{1!r}" \
.format(type(ex).__name__, ex.args)
self.logger.error(message)
return False | [
"def",
"_send_to_kafka",
"(",
"self",
",",
"master",
")",
":",
"appid_topic",
"=",
"\"{prefix}.outbound_{appid}\"",
".",
"format",
"(",
"prefix",
"=",
"self",
".",
"topic_prefix",
",",
"appid",
"=",
"master",
"[",
"'appid'",
"]",
")",
"firehose_topic",
"=",
... | Sends the message back to Kafka
@param master: the final dict to send
@returns: True if successfully sent to kafka | [
"Sends",
"the",
"message",
"back",
"to",
"Kafka"
] | 13aaed2349af5d792d6bcbfcadc5563158aeb599 | https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/redis-monitor/plugins/kafka_base_monitor.py#L66-L94 | train | 215,486 |
istresearch/scrapy-cluster | kafka-monitor/kafka_monitor.py | KafkaMonitor._load_plugins | def _load_plugins(self):
'''
Sets up all plugins, defaults and settings.py
'''
plugins = self.settings['PLUGINS']
self.plugins_dict = {}
for key in plugins:
# skip loading the plugin if its value is None
if plugins[key] is None:
continue
# valid plugin, import and setup
self.logger.debug("Trying to load plugin {cls}".format(cls=key))
the_class = self._import_class(key)
instance = the_class()
instance._set_logger(self.logger)
if not self.unit_test:
instance.setup(self.settings)
the_schema = None
with open(self.settings['PLUGIN_DIR'] + instance.schema) as the_file:
the_schema = json.load(the_file)
mini = {}
mini['instance'] = instance
mini['schema'] = the_schema
self.logger.debug("Successfully loaded plugin {cls}".format(cls=key))
self.plugins_dict[plugins[key]] = mini
self.plugins_dict = OrderedDict(sorted(list(self.plugins_dict.items()),
key=lambda t: t[0])) | python | def _load_plugins(self):
'''
Sets up all plugins, defaults and settings.py
'''
plugins = self.settings['PLUGINS']
self.plugins_dict = {}
for key in plugins:
# skip loading the plugin if its value is None
if plugins[key] is None:
continue
# valid plugin, import and setup
self.logger.debug("Trying to load plugin {cls}".format(cls=key))
the_class = self._import_class(key)
instance = the_class()
instance._set_logger(self.logger)
if not self.unit_test:
instance.setup(self.settings)
the_schema = None
with open(self.settings['PLUGIN_DIR'] + instance.schema) as the_file:
the_schema = json.load(the_file)
mini = {}
mini['instance'] = instance
mini['schema'] = the_schema
self.logger.debug("Successfully loaded plugin {cls}".format(cls=key))
self.plugins_dict[plugins[key]] = mini
self.plugins_dict = OrderedDict(sorted(list(self.plugins_dict.items()),
key=lambda t: t[0])) | [
"def",
"_load_plugins",
"(",
"self",
")",
":",
"plugins",
"=",
"self",
".",
"settings",
"[",
"'PLUGINS'",
"]",
"self",
".",
"plugins_dict",
"=",
"{",
"}",
"for",
"key",
"in",
"plugins",
":",
"# skip loading the plugin if its value is None",
"if",
"plugins",
"[... | Sets up all plugins, defaults and settings.py | [
"Sets",
"up",
"all",
"plugins",
"defaults",
"and",
"settings",
".",
"py"
] | 13aaed2349af5d792d6bcbfcadc5563158aeb599 | https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/kafka-monitor/kafka_monitor.py#L62-L91 | train | 215,487 |
istresearch/scrapy-cluster | kafka-monitor/kafka_monitor.py | KafkaMonitor._setup_stats | def _setup_stats(self):
'''
Sets up the stats collection
'''
self.stats_dict = {}
redis_conn = redis.Redis(host=self.settings['REDIS_HOST'],
port=self.settings['REDIS_PORT'],
db=self.settings.get('REDIS_DB'))
try:
redis_conn.info()
self.logger.debug("Connected to Redis in StatsCollector Setup")
self.redis_conn = redis_conn
except ConnectionError:
self.logger.warn("Failed to connect to Redis in StatsCollector"
" Setup, no stats will be collected")
return
if self.settings['STATS_TOTAL']:
self._setup_stats_total(redis_conn)
if self.settings['STATS_PLUGINS']:
self._setup_stats_plugins(redis_conn) | python | def _setup_stats(self):
'''
Sets up the stats collection
'''
self.stats_dict = {}
redis_conn = redis.Redis(host=self.settings['REDIS_HOST'],
port=self.settings['REDIS_PORT'],
db=self.settings.get('REDIS_DB'))
try:
redis_conn.info()
self.logger.debug("Connected to Redis in StatsCollector Setup")
self.redis_conn = redis_conn
except ConnectionError:
self.logger.warn("Failed to connect to Redis in StatsCollector"
" Setup, no stats will be collected")
return
if self.settings['STATS_TOTAL']:
self._setup_stats_total(redis_conn)
if self.settings['STATS_PLUGINS']:
self._setup_stats_plugins(redis_conn) | [
"def",
"_setup_stats",
"(",
"self",
")",
":",
"self",
".",
"stats_dict",
"=",
"{",
"}",
"redis_conn",
"=",
"redis",
".",
"Redis",
"(",
"host",
"=",
"self",
".",
"settings",
"[",
"'REDIS_HOST'",
"]",
",",
"port",
"=",
"self",
".",
"settings",
"[",
"'R... | Sets up the stats collection | [
"Sets",
"up",
"the",
"stats",
"collection"
] | 13aaed2349af5d792d6bcbfcadc5563158aeb599 | https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/kafka-monitor/kafka_monitor.py#L118-L141 | train | 215,488 |
istresearch/scrapy-cluster | kafka-monitor/kafka_monitor.py | KafkaMonitor._setup_stats_total | def _setup_stats_total(self, redis_conn):
'''
Sets up the total stats collectors
@param redis_conn: the redis connection
'''
self.stats_dict['total'] = {}
self.stats_dict['fail'] = {}
temp_key1 = 'stats:kafka-monitor:total'
temp_key2 = 'stats:kafka-monitor:fail'
for item in self.settings['STATS_TIMES']:
try:
time = getattr(StatsCollector, item)
self.stats_dict['total'][time] = StatsCollector \
.get_rolling_time_window(
redis_conn=redis_conn,
key='{k}:{t}'.format(k=temp_key1, t=time),
window=time,
cycle_time=self.settings['STATS_CYCLE'])
self.stats_dict['fail'][time] = StatsCollector \
.get_rolling_time_window(
redis_conn=redis_conn,
key='{k}:{t}'.format(k=temp_key2, t=time),
window=time,
cycle_time=self.settings['STATS_CYCLE'])
self.logger.debug("Set up total/fail Stats Collector '{i}'"\
.format(i=item))
except AttributeError as e:
self.logger.warning("Unable to find Stats Time '{s}'"\
.format(s=item))
total1 = StatsCollector.get_hll_counter(redis_conn=redis_conn,
key='{k}:lifetime'.format(k=temp_key1),
cycle_time=self.settings['STATS_CYCLE'],
roll=False)
total2 = StatsCollector.get_hll_counter(redis_conn=redis_conn,
key='{k}:lifetime'.format(k=temp_key2),
cycle_time=self.settings['STATS_CYCLE'],
roll=False)
self.logger.debug("Set up total/fail Stats Collector 'lifetime'")
self.stats_dict['total']['lifetime'] = total1
self.stats_dict['fail']['lifetime'] = total2 | python | def _setup_stats_total(self, redis_conn):
'''
Sets up the total stats collectors
@param redis_conn: the redis connection
'''
self.stats_dict['total'] = {}
self.stats_dict['fail'] = {}
temp_key1 = 'stats:kafka-monitor:total'
temp_key2 = 'stats:kafka-monitor:fail'
for item in self.settings['STATS_TIMES']:
try:
time = getattr(StatsCollector, item)
self.stats_dict['total'][time] = StatsCollector \
.get_rolling_time_window(
redis_conn=redis_conn,
key='{k}:{t}'.format(k=temp_key1, t=time),
window=time,
cycle_time=self.settings['STATS_CYCLE'])
self.stats_dict['fail'][time] = StatsCollector \
.get_rolling_time_window(
redis_conn=redis_conn,
key='{k}:{t}'.format(k=temp_key2, t=time),
window=time,
cycle_time=self.settings['STATS_CYCLE'])
self.logger.debug("Set up total/fail Stats Collector '{i}'"\
.format(i=item))
except AttributeError as e:
self.logger.warning("Unable to find Stats Time '{s}'"\
.format(s=item))
total1 = StatsCollector.get_hll_counter(redis_conn=redis_conn,
key='{k}:lifetime'.format(k=temp_key1),
cycle_time=self.settings['STATS_CYCLE'],
roll=False)
total2 = StatsCollector.get_hll_counter(redis_conn=redis_conn,
key='{k}:lifetime'.format(k=temp_key2),
cycle_time=self.settings['STATS_CYCLE'],
roll=False)
self.logger.debug("Set up total/fail Stats Collector 'lifetime'")
self.stats_dict['total']['lifetime'] = total1
self.stats_dict['fail']['lifetime'] = total2 | [
"def",
"_setup_stats_total",
"(",
"self",
",",
"redis_conn",
")",
":",
"self",
".",
"stats_dict",
"[",
"'total'",
"]",
"=",
"{",
"}",
"self",
".",
"stats_dict",
"[",
"'fail'",
"]",
"=",
"{",
"}",
"temp_key1",
"=",
"'stats:kafka-monitor:total'",
"temp_key2",
... | Sets up the total stats collectors
@param redis_conn: the redis connection | [
"Sets",
"up",
"the",
"total",
"stats",
"collectors"
] | 13aaed2349af5d792d6bcbfcadc5563158aeb599 | https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/kafka-monitor/kafka_monitor.py#L143-L183 | train | 215,489 |
istresearch/scrapy-cluster | kafka-monitor/kafka_monitor.py | KafkaMonitor._main_loop | def _main_loop(self):
'''
Continuous loop that reads from a kafka topic and tries to validate
incoming messages
'''
self.logger.debug("Processing messages")
old_time = 0
while True:
self._process_messages()
if self.settings['STATS_DUMP'] != 0:
new_time = int(old_div(time.time(), self.settings['STATS_DUMP']))
# only log every X seconds
if new_time != old_time:
self._dump_stats()
old_time = new_time
self._report_self()
time.sleep(self.settings['SLEEP_TIME']) | python | def _main_loop(self):
'''
Continuous loop that reads from a kafka topic and tries to validate
incoming messages
'''
self.logger.debug("Processing messages")
old_time = 0
while True:
self._process_messages()
if self.settings['STATS_DUMP'] != 0:
new_time = int(old_div(time.time(), self.settings['STATS_DUMP']))
# only log every X seconds
if new_time != old_time:
self._dump_stats()
old_time = new_time
self._report_self()
time.sleep(self.settings['SLEEP_TIME']) | [
"def",
"_main_loop",
"(",
"self",
")",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"\"Processing messages\"",
")",
"old_time",
"=",
"0",
"while",
"True",
":",
"self",
".",
"_process_messages",
"(",
")",
"if",
"self",
".",
"settings",
"[",
"'STATS_DUMP'"... | Continuous loop that reads from a kafka topic and tries to validate
incoming messages | [
"Continuous",
"loop",
"that",
"reads",
"from",
"a",
"kafka",
"topic",
"and",
"tries",
"to",
"validate",
"incoming",
"messages"
] | 13aaed2349af5d792d6bcbfcadc5563158aeb599 | https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/kafka-monitor/kafka_monitor.py#L247-L264 | train | 215,490 |
istresearch/scrapy-cluster | kafka-monitor/kafka_monitor.py | KafkaMonitor._dump_stats | def _dump_stats(self):
'''
Dumps the stats out
'''
extras = {}
if 'total' in self.stats_dict:
self.logger.debug("Compiling total/fail dump stats")
for key in self.stats_dict['total']:
final = 'total_{t}'.format(t=key)
extras[final] = self.stats_dict['total'][key].value()
for key in self.stats_dict['fail']:
final = 'fail_{t}'.format(t=key)
extras[final] = self.stats_dict['fail'][key].value()
if 'plugins' in self.stats_dict:
self.logger.debug("Compiling plugin dump stats")
for name in self.stats_dict['plugins']:
for key in self.stats_dict['plugins'][name]:
final = 'plugin_{n}_{t}'.format(n=name, t=key)
extras[final] = self.stats_dict['plugins'][name][key].value()
if not self.logger.json:
self.logger.info('Kafka Monitor Stats Dump:\n{0}'.format(
json.dumps(extras, indent=4, sort_keys=True)))
else:
self.logger.info('Kafka Monitor Stats Dump', extra=extras) | python | def _dump_stats(self):
'''
Dumps the stats out
'''
extras = {}
if 'total' in self.stats_dict:
self.logger.debug("Compiling total/fail dump stats")
for key in self.stats_dict['total']:
final = 'total_{t}'.format(t=key)
extras[final] = self.stats_dict['total'][key].value()
for key in self.stats_dict['fail']:
final = 'fail_{t}'.format(t=key)
extras[final] = self.stats_dict['fail'][key].value()
if 'plugins' in self.stats_dict:
self.logger.debug("Compiling plugin dump stats")
for name in self.stats_dict['plugins']:
for key in self.stats_dict['plugins'][name]:
final = 'plugin_{n}_{t}'.format(n=name, t=key)
extras[final] = self.stats_dict['plugins'][name][key].value()
if not self.logger.json:
self.logger.info('Kafka Monitor Stats Dump:\n{0}'.format(
json.dumps(extras, indent=4, sort_keys=True)))
else:
self.logger.info('Kafka Monitor Stats Dump', extra=extras) | [
"def",
"_dump_stats",
"(",
"self",
")",
":",
"extras",
"=",
"{",
"}",
"if",
"'total'",
"in",
"self",
".",
"stats_dict",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"\"Compiling total/fail dump stats\"",
")",
"for",
"key",
"in",
"self",
".",
"stats_dict"... | Dumps the stats out | [
"Dumps",
"the",
"stats",
"out"
] | 13aaed2349af5d792d6bcbfcadc5563158aeb599 | https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/kafka-monitor/kafka_monitor.py#L367-L392 | train | 215,491 |
istresearch/scrapy-cluster | kafka-monitor/kafka_monitor.py | KafkaMonitor.run | def run(self):
'''
Set up and run
'''
self._setup_kafka()
self._load_plugins()
self._setup_stats()
self._main_loop() | python | def run(self):
'''
Set up and run
'''
self._setup_kafka()
self._load_plugins()
self._setup_stats()
self._main_loop() | [
"def",
"run",
"(",
"self",
")",
":",
"self",
".",
"_setup_kafka",
"(",
")",
"self",
".",
"_load_plugins",
"(",
")",
"self",
".",
"_setup_stats",
"(",
")",
"self",
".",
"_main_loop",
"(",
")"
] | Set up and run | [
"Set",
"up",
"and",
"run"
] | 13aaed2349af5d792d6bcbfcadc5563158aeb599 | https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/kafka-monitor/kafka_monitor.py#L394-L401 | train | 215,492 |
istresearch/scrapy-cluster | kafka-monitor/kafka_monitor.py | KafkaMonitor._report_self | def _report_self(self):
'''
Reports the kafka monitor uuid to redis
'''
key = "stats:kafka-monitor:self:{m}:{u}".format(
m=socket.gethostname(),
u=self.my_uuid)
self.redis_conn.set(key, time.time())
self.redis_conn.expire(key, self.settings['HEARTBEAT_TIMEOUT']) | python | def _report_self(self):
'''
Reports the kafka monitor uuid to redis
'''
key = "stats:kafka-monitor:self:{m}:{u}".format(
m=socket.gethostname(),
u=self.my_uuid)
self.redis_conn.set(key, time.time())
self.redis_conn.expire(key, self.settings['HEARTBEAT_TIMEOUT']) | [
"def",
"_report_self",
"(",
"self",
")",
":",
"key",
"=",
"\"stats:kafka-monitor:self:{m}:{u}\"",
".",
"format",
"(",
"m",
"=",
"socket",
".",
"gethostname",
"(",
")",
",",
"u",
"=",
"self",
".",
"my_uuid",
")",
"self",
".",
"redis_conn",
".",
"set",
"("... | Reports the kafka monitor uuid to redis | [
"Reports",
"the",
"kafka",
"monitor",
"uuid",
"to",
"redis"
] | 13aaed2349af5d792d6bcbfcadc5563158aeb599 | https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/kafka-monitor/kafka_monitor.py#L403-L411 | train | 215,493 |
istresearch/scrapy-cluster | kafka-monitor/kafka_monitor.py | KafkaMonitor.feed | def feed(self, json_item):
'''
Feeds a json item into the Kafka topic
@param json_item: The loaded json object
'''
@MethodTimer.timeout(self.settings['KAFKA_FEED_TIMEOUT'], False)
def _feed(json_item):
producer = self._create_producer()
topic = self.settings['KAFKA_INCOMING_TOPIC']
if not self.logger.json:
self.logger.info('Feeding JSON into {0}\n{1}'.format(
topic, json.dumps(json_item, indent=4)))
else:
self.logger.info('Feeding JSON into {0}\n'.format(topic),
extra={'value': json_item})
if producer is not None:
producer.send(topic, json_item)
producer.flush()
producer.close(timeout=10)
return True
else:
return False
result = _feed(json_item)
if result:
self.logger.info("Successfully fed item to Kafka")
else:
self.logger.error("Failed to feed item into Kafka") | python | def feed(self, json_item):
'''
Feeds a json item into the Kafka topic
@param json_item: The loaded json object
'''
@MethodTimer.timeout(self.settings['KAFKA_FEED_TIMEOUT'], False)
def _feed(json_item):
producer = self._create_producer()
topic = self.settings['KAFKA_INCOMING_TOPIC']
if not self.logger.json:
self.logger.info('Feeding JSON into {0}\n{1}'.format(
topic, json.dumps(json_item, indent=4)))
else:
self.logger.info('Feeding JSON into {0}\n'.format(topic),
extra={'value': json_item})
if producer is not None:
producer.send(topic, json_item)
producer.flush()
producer.close(timeout=10)
return True
else:
return False
result = _feed(json_item)
if result:
self.logger.info("Successfully fed item to Kafka")
else:
self.logger.error("Failed to feed item into Kafka") | [
"def",
"feed",
"(",
"self",
",",
"json_item",
")",
":",
"@",
"MethodTimer",
".",
"timeout",
"(",
"self",
".",
"settings",
"[",
"'KAFKA_FEED_TIMEOUT'",
"]",
",",
"False",
")",
"def",
"_feed",
"(",
"json_item",
")",
":",
"producer",
"=",
"self",
".",
"_c... | Feeds a json item into the Kafka topic
@param json_item: The loaded json object | [
"Feeds",
"a",
"json",
"item",
"into",
"the",
"Kafka",
"topic"
] | 13aaed2349af5d792d6bcbfcadc5563158aeb599 | https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/kafka-monitor/kafka_monitor.py#L413-L443 | train | 215,494 |
istresearch/scrapy-cluster | redis-monitor/plugins/expire_monitor.py | ExpireMonitor.check_precondition | def check_precondition(self, key, value):
'''
Override to check for timeout
'''
timeout = float(value)
curr_time = self.get_current_time()
if curr_time > timeout:
return True
return False | python | def check_precondition(self, key, value):
'''
Override to check for timeout
'''
timeout = float(value)
curr_time = self.get_current_time()
if curr_time > timeout:
return True
return False | [
"def",
"check_precondition",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"timeout",
"=",
"float",
"(",
"value",
")",
"curr_time",
"=",
"self",
".",
"get_current_time",
"(",
")",
"if",
"curr_time",
">",
"timeout",
":",
"return",
"True",
"return",
"Fa... | Override to check for timeout | [
"Override",
"to",
"check",
"for",
"timeout"
] | 13aaed2349af5d792d6bcbfcadc5563158aeb599 | https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/redis-monitor/plugins/expire_monitor.py#L18-L26 | train | 215,495 |
istresearch/scrapy-cluster | utils/scutils/stats_collector.py | StatsCollector.get_time_window | def get_time_window(self, redis_conn=None, host='localhost', port=6379,
key='time_window_counter', cycle_time=5,
start_time=None, window=SECONDS_1_HOUR, roll=True,
keep_max=12):
'''
Generate a new TimeWindow
Useful for collecting number of hits generated between certain times
@param redis_conn: A premade redis connection (overrides host and port)
@param host: the redis host
@param port: the redis port
@param key: the key for your stats collection
@param cycle_time: how often to check for expiring counts
@param start_time: the time to start valid collection
@param window: how long to collect data for in seconds (if rolling)
@param roll: Roll the window after it expires, to continue collecting
on a new date based key.
@keep_max: If rolling the static window, the max number of prior
windows to keep
'''
counter = TimeWindow(key=key, cycle_time=cycle_time,
start_time=start_time, window=window, roll=roll,
keep_max=keep_max)
counter.setup(redis_conn=redis_conn, host=host, port=port)
return counter | python | def get_time_window(self, redis_conn=None, host='localhost', port=6379,
key='time_window_counter', cycle_time=5,
start_time=None, window=SECONDS_1_HOUR, roll=True,
keep_max=12):
'''
Generate a new TimeWindow
Useful for collecting number of hits generated between certain times
@param redis_conn: A premade redis connection (overrides host and port)
@param host: the redis host
@param port: the redis port
@param key: the key for your stats collection
@param cycle_time: how often to check for expiring counts
@param start_time: the time to start valid collection
@param window: how long to collect data for in seconds (if rolling)
@param roll: Roll the window after it expires, to continue collecting
on a new date based key.
@keep_max: If rolling the static window, the max number of prior
windows to keep
'''
counter = TimeWindow(key=key, cycle_time=cycle_time,
start_time=start_time, window=window, roll=roll,
keep_max=keep_max)
counter.setup(redis_conn=redis_conn, host=host, port=port)
return counter | [
"def",
"get_time_window",
"(",
"self",
",",
"redis_conn",
"=",
"None",
",",
"host",
"=",
"'localhost'",
",",
"port",
"=",
"6379",
",",
"key",
"=",
"'time_window_counter'",
",",
"cycle_time",
"=",
"5",
",",
"start_time",
"=",
"None",
",",
"window",
"=",
"... | Generate a new TimeWindow
Useful for collecting number of hits generated between certain times
@param redis_conn: A premade redis connection (overrides host and port)
@param host: the redis host
@param port: the redis port
@param key: the key for your stats collection
@param cycle_time: how often to check for expiring counts
@param start_time: the time to start valid collection
@param window: how long to collect data for in seconds (if rolling)
@param roll: Roll the window after it expires, to continue collecting
on a new date based key.
@keep_max: If rolling the static window, the max number of prior
windows to keep | [
"Generate",
"a",
"new",
"TimeWindow",
"Useful",
"for",
"collecting",
"number",
"of",
"hits",
"generated",
"between",
"certain",
"times"
] | 13aaed2349af5d792d6bcbfcadc5563158aeb599 | https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/utils/scutils/stats_collector.py#L43-L67 | train | 215,496 |
istresearch/scrapy-cluster | utils/scutils/stats_collector.py | StatsCollector.get_rolling_time_window | def get_rolling_time_window(self, redis_conn=None, host='localhost',
port=6379, key='rolling_time_window_counter',
cycle_time=5, window=SECONDS_1_HOUR):
'''
Generate a new RollingTimeWindow
Useful for collect data about the number of hits in the past X seconds
@param redis_conn: A premade redis connection (overrides host and port)
@param host: the redis host
@param port: the redis port
@param key: the key for your stats collection
@param cycle_time: how often to check for expiring counts
@param window: the number of seconds behind now() to keep data for
'''
counter = RollingTimeWindow(key=key, cycle_time=cycle_time,
window=window)
counter.setup(redis_conn=redis_conn, host=host, port=port)
return counter | python | def get_rolling_time_window(self, redis_conn=None, host='localhost',
port=6379, key='rolling_time_window_counter',
cycle_time=5, window=SECONDS_1_HOUR):
'''
Generate a new RollingTimeWindow
Useful for collect data about the number of hits in the past X seconds
@param redis_conn: A premade redis connection (overrides host and port)
@param host: the redis host
@param port: the redis port
@param key: the key for your stats collection
@param cycle_time: how often to check for expiring counts
@param window: the number of seconds behind now() to keep data for
'''
counter = RollingTimeWindow(key=key, cycle_time=cycle_time,
window=window)
counter.setup(redis_conn=redis_conn, host=host, port=port)
return counter | [
"def",
"get_rolling_time_window",
"(",
"self",
",",
"redis_conn",
"=",
"None",
",",
"host",
"=",
"'localhost'",
",",
"port",
"=",
"6379",
",",
"key",
"=",
"'rolling_time_window_counter'",
",",
"cycle_time",
"=",
"5",
",",
"window",
"=",
"SECONDS_1_HOUR",
")",
... | Generate a new RollingTimeWindow
Useful for collect data about the number of hits in the past X seconds
@param redis_conn: A premade redis connection (overrides host and port)
@param host: the redis host
@param port: the redis port
@param key: the key for your stats collection
@param cycle_time: how often to check for expiring counts
@param window: the number of seconds behind now() to keep data for | [
"Generate",
"a",
"new",
"RollingTimeWindow",
"Useful",
"for",
"collect",
"data",
"about",
"the",
"number",
"of",
"hits",
"in",
"the",
"past",
"X",
"seconds"
] | 13aaed2349af5d792d6bcbfcadc5563158aeb599 | https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/utils/scutils/stats_collector.py#L70-L87 | train | 215,497 |
istresearch/scrapy-cluster | utils/scutils/stats_collector.py | StatsCollector.get_counter | def get_counter(self, redis_conn=None, host='localhost', port=6379,
key='counter', cycle_time=5, start_time=None,
window=SECONDS_1_HOUR, roll=True, keep_max=12, start_at=0):
'''
Generate a new Counter
Useful for generic distributed counters
@param redis_conn: A premade redis connection (overrides host and port)
@param host: the redis host
@param port: the redis port
@param key: the key for your stats collection
@param cycle_time: how often to check for expiring counts
@param start_time: the time to start valid collection
@param window: how long to collect data for in seconds (if rolling)
@param roll: Roll the window after it expires, to continue collecting
on a new date based key.
@keep_max: If rolling the static window, the max number of prior
windows to keep
@param start_at: The integer to start counting at
'''
counter = Counter(key=key, cycle_time=cycle_time,
start_time=start_time, window=window, roll=roll,
keep_max=keep_max)
counter.setup(redis_conn=redis_conn, host=host, port=port)
return counter | python | def get_counter(self, redis_conn=None, host='localhost', port=6379,
key='counter', cycle_time=5, start_time=None,
window=SECONDS_1_HOUR, roll=True, keep_max=12, start_at=0):
'''
Generate a new Counter
Useful for generic distributed counters
@param redis_conn: A premade redis connection (overrides host and port)
@param host: the redis host
@param port: the redis port
@param key: the key for your stats collection
@param cycle_time: how often to check for expiring counts
@param start_time: the time to start valid collection
@param window: how long to collect data for in seconds (if rolling)
@param roll: Roll the window after it expires, to continue collecting
on a new date based key.
@keep_max: If rolling the static window, the max number of prior
windows to keep
@param start_at: The integer to start counting at
'''
counter = Counter(key=key, cycle_time=cycle_time,
start_time=start_time, window=window, roll=roll,
keep_max=keep_max)
counter.setup(redis_conn=redis_conn, host=host, port=port)
return counter | [
"def",
"get_counter",
"(",
"self",
",",
"redis_conn",
"=",
"None",
",",
"host",
"=",
"'localhost'",
",",
"port",
"=",
"6379",
",",
"key",
"=",
"'counter'",
",",
"cycle_time",
"=",
"5",
",",
"start_time",
"=",
"None",
",",
"window",
"=",
"SECONDS_1_HOUR",... | Generate a new Counter
Useful for generic distributed counters
@param redis_conn: A premade redis connection (overrides host and port)
@param host: the redis host
@param port: the redis port
@param key: the key for your stats collection
@param cycle_time: how often to check for expiring counts
@param start_time: the time to start valid collection
@param window: how long to collect data for in seconds (if rolling)
@param roll: Roll the window after it expires, to continue collecting
on a new date based key.
@keep_max: If rolling the static window, the max number of prior
windows to keep
@param start_at: The integer to start counting at | [
"Generate",
"a",
"new",
"Counter",
"Useful",
"for",
"generic",
"distributed",
"counters"
] | 13aaed2349af5d792d6bcbfcadc5563158aeb599 | https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/utils/scutils/stats_collector.py#L90-L114 | train | 215,498 |
istresearch/scrapy-cluster | utils/scutils/stats_collector.py | StatsCollector.get_unique_counter | def get_unique_counter(self, redis_conn=None, host='localhost', port=6379,
key='unique_counter', cycle_time=5, start_time=None,
window=SECONDS_1_HOUR, roll=True, keep_max=12):
'''
Generate a new UniqueCounter.
Useful for exactly counting unique objects
@param redis_conn: A premade redis connection (overrides host and port)
@param host: the redis host
@param port: the redis port
@param key: the key for your stats collection
@param cycle_time: how often to check for expiring counts
@param start_time: the time to start valid collection
@param window: how long to collect data for in seconds (if rolling)
@param roll: Roll the window after it expires, to continue collecting
on a new date based key.
@keep_max: If rolling the static window, the max number of prior
windows to keep
'''
counter = UniqueCounter(key=key, cycle_time=cycle_time,
start_time=start_time, window=window,
roll=roll, keep_max=keep_max)
counter.setup(redis_conn=redis_conn, host=host, port=port)
return counter | python | def get_unique_counter(self, redis_conn=None, host='localhost', port=6379,
key='unique_counter', cycle_time=5, start_time=None,
window=SECONDS_1_HOUR, roll=True, keep_max=12):
'''
Generate a new UniqueCounter.
Useful for exactly counting unique objects
@param redis_conn: A premade redis connection (overrides host and port)
@param host: the redis host
@param port: the redis port
@param key: the key for your stats collection
@param cycle_time: how often to check for expiring counts
@param start_time: the time to start valid collection
@param window: how long to collect data for in seconds (if rolling)
@param roll: Roll the window after it expires, to continue collecting
on a new date based key.
@keep_max: If rolling the static window, the max number of prior
windows to keep
'''
counter = UniqueCounter(key=key, cycle_time=cycle_time,
start_time=start_time, window=window,
roll=roll, keep_max=keep_max)
counter.setup(redis_conn=redis_conn, host=host, port=port)
return counter | [
"def",
"get_unique_counter",
"(",
"self",
",",
"redis_conn",
"=",
"None",
",",
"host",
"=",
"'localhost'",
",",
"port",
"=",
"6379",
",",
"key",
"=",
"'unique_counter'",
",",
"cycle_time",
"=",
"5",
",",
"start_time",
"=",
"None",
",",
"window",
"=",
"SE... | Generate a new UniqueCounter.
Useful for exactly counting unique objects
@param redis_conn: A premade redis connection (overrides host and port)
@param host: the redis host
@param port: the redis port
@param key: the key for your stats collection
@param cycle_time: how often to check for expiring counts
@param start_time: the time to start valid collection
@param window: how long to collect data for in seconds (if rolling)
@param roll: Roll the window after it expires, to continue collecting
on a new date based key.
@keep_max: If rolling the static window, the max number of prior
windows to keep | [
"Generate",
"a",
"new",
"UniqueCounter",
".",
"Useful",
"for",
"exactly",
"counting",
"unique",
"objects"
] | 13aaed2349af5d792d6bcbfcadc5563158aeb599 | https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/utils/scutils/stats_collector.py#L117-L140 | train | 215,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.