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
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
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` h...
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` h...
[ "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...
[ "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
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 ...
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 ...
[ "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 elemen...
[ "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
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_chai...
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_chai...
[ "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...
[ "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
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: Inpu...
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: Inpu...
[ "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
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...
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...
[ "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.D...
[ "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
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_inpu...
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_inpu...
[ "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` ...
[ "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
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 ...
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 ...
[ "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 ha...
[ "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
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 retrievi...
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 retrievi...
[ "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 ...
[ "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
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-we...
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-we...
[ "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 r...
[ "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
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 loa...
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 loa...
[ "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 back...
[ "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
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 ...
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 ...
[ "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 val...
[ "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
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, dec...
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, dec...
[ "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_cha...
[ "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
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 th...
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 th...
[ "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 header...
[ "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
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) re...
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) re...
[ "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
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
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(sam...
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(sam...
[ "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
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
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....
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....
[ "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
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
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=s...
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=s...
[ "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
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 o...
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 o...
[ "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
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 polic...
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 polic...
[ "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 pr...
[ "Get", "the", "next", "proxy" ]
38c925758fd3d3e568d3ecc993f77bc0acfa4788
https://github.com/hellock/icrawler/blob/38c925758fd3d3e568d3ecc993f77bc0acfa4788/icrawler/utils/proxy_pool.py#L123-L154
train
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(seria...
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(seria...
[ "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
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'], prox...
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'], prox...
[ "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
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.prox...
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.prox...
[ "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
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
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
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
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 indic...
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 indic...
[ "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: ...
[ "Check", "if", "a", "proxy", "is", "valid" ]
38c925758fd3d3e568d3ecc993f77bc0acfa4788
https://github.com/hellock/icrawler/blob/38c925758fd3d3e568d3ecc993f77bc0acfa4788/icrawler/utils/proxy_pool.py#L212-L244
train
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 ...
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 ...
[ "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
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 ...
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 ...
[ "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 us...
[ "Scan", "and", "validate", "proxies" ]
38c925758fd3d3e568d3ecc993f77bc0acfa4788
https://github.com/hellock/icrawler/blob/38c925758fd3d3e568d3ecc993f77bc0acfa4788/icrawler/utils/proxy_pool.py#L282-L327
train
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 m...
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 m...
[ "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 ...
[ "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
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.appen...
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.appen...
[ "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
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(): ...
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(): ...
[ "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
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(le...
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(le...
[ "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
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. ...
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. ...
[ "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 ite...
[ "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
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
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] = sig...
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] = sig...
[ "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
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
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...
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...
[ "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. ...
[ "Feed", "urls", "once" ]
38c925758fd3d3e568d3ecc993f77bc0acfa4788
https://github.com/hellock/icrawler/blob/38c925758fd3d3e568d3ecc993f77bc0acfa4788/icrawler/feeder.py#L79-L92
train
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. Re...
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. Re...
[ "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 modifi...
[ "Connect", "two", "ThreadPools", "." ]
38c925758fd3d3e568d3ecc993f77bc0acfa4788
https://github.com/hellock/icrawler/blob/38c925758fd3d3e568d3ecc993f77bc0acfa4788/icrawler/utils/thread_pool.py#L85-L99
train
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 ...
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 ...
[ "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
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 fr...
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 fr...
[ "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 ...
[ "Set", "the", "path", "where", "the", "image", "will", "be", "saved", "." ]
38c925758fd3d3e568d3ecc993f77bc0acfa4788
https://github.com/hellock/icrawler/blob/38c925758fd3d3e568d3ecc993f77bc0acfa4788/icrawler/downloader.py#L61-L78
train
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 ...
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 ...
[ "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
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 f...
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 f...
[ "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 arg...
[ "Download", "the", "image", "and", "save", "it", "to", "the", "corresponding", "path", "." ]
38c925758fd3d3e568d3ecc993f77bc0acfa4788
https://github.com/hellock/icrawler/blob/38c925758fd3d3e568d3ecc993f77bc0acfa4788/icrawler/downloader.py#L96-L151
train
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 im...
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 im...
[ "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. ...
[ "Decide", "whether", "to", "keep", "the", "image" ]
38c925758fd3d3e568d3ecc993f77bc0acfa4788
https://github.com/hellock/icrawler/blob/38c925758fd3d3e568d3ecc993f77bc0acfa4788/icrawler/downloader.py#L232-L253
train
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__) l...
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__) l...
[ "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
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): ...
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): ...
[ "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
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-A...
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-A...
[ "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
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
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
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 va...
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 va...
[ "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
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
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 sel...
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 sel...
[ "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
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: ...
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: ...
[ "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
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? ...
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? ...
[ "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 ...
[ "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
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. Al...
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. Al...
[ "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 ...
[ "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
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 calcu...
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 calcu...
[ "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. Arg...
[ "Rebalance", "a", "child", "to", "a", "given", "weight", "." ]
0363e6fa100d9392dd18e32e3d8379d5e83c28fa
https://github.com/pmorissette/bt/blob/0363e6fa100d9392dd18e32e3d8379d5e83c28fa/bt/core.py#L676-L722
train
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
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 ...
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 ...
[ "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
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) ha...
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) ha...
[ "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
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
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' % con...
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' % con...
[ "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
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...
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...
[ "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
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...
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...
[ "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
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...
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...
[ "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
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 ...
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 ...
[ "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
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: i...
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: i...
[ "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
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=...
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=...
[ "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
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...
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...
[ "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
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_d...
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_d...
[ "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
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', ...
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', ...
[ "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
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, ...
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, ...
[ "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
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.r...
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.r...
[ "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
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'...
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'...
[ "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
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 ...
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 ...
[ "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
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.c...
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.c...
[ "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
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: ...
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: ...
[ "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
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_c...
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_c...
[ "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
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
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 Kaf...
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 Kaf...
[ "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
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.he...
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.he...
[ "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 ...
[ "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
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, ...
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, ...
[ "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
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 MethodTi...
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 MethodTi...
[ "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
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 chos...
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 chos...
[ "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
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...
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...
[ "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
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.t...
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.t...
[ "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
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: co...
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: co...
[ "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
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')) ...
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')) ...
[ "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
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-monito...
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-monito...
[ "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
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'] !=...
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'] !=...
[ "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
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...
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...
[ "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
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
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['HEARTB...
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['HEARTB...
[ "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
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 = se...
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 = se...
[ "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
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
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 colle...
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 colle...
[ "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 @p...
[ "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
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 o...
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 o...
[ "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 ...
[ "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
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...
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...
[ "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 ch...
[ "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
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 uniq...
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 uniq...
[ "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 o...
[ "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